1
0

More than 3 years have passed since last update.

【Java】String型配列の要素一つをInt型に型変換する方法

Last updated at Posted at 2020-09-24

例えば従業員の情報を、名前、年齢と入力されそれを一つの配列にScannerを使って代入すると
yamada 20

  Scanner sc = new Scanner( System.in);
  String[] employee = sc.nextLine();

となるが、javaは静的型付のため配列内の名前も年齢もString型となる
年齢をInt型にキャスト(型変換)しなくてはならない
そこでInteger.parseIntメソッドを使う

 int age = Integer.parseInt( employee[1] );

これでString型からInt型へのキャストは終了
たとえば1歳年を増やしたければ

 int addAge = Integer.parseInt( employee[1] ) + 1;

となる。
()内は引数なのでもちろん普通の変数でも問題ありません。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0