ユーザーが3つの数字を入力し、これらの個々の数字を私が持っている数字と比較するプログラムを作成しています。
これらの使用入力番号を個々の整数に分割して保存するにはどうすればよいですか?
String input = "12 23 12";
String[] split = input.split(" "); // or "\t" according to need
int[] arr = new int[split.length];
int count = 0;
for(String s:split)
{
arr[count] = Integer.parseInt(s).intValue();
count++;
}
という非常に便利なクラスが Java 1.5 に追加されましたScanner
。
を読み取りString
、すべての 10 進数を検索してコンソールに出力するサンプル プログラムを次に示します。デフォルトの区切り文字は空白です。
public static void main(String[] args) {
String userInput = "1 2 3 4 5 6";
try (Scanner scanner = new Scanner(userInput)) {
scanner.useRadix(10);
while (scanner.hasNextInt()) {
int i = scanner.nextInt();
System.out.println(i);
}
}
}
例String userInput = "1 2 3 4 5 df 6";
// 出力 1 2 3 4 5
いくつかの利点があります。
parseInt
に未チェックの例外をスローできるメソッドを呼び出す必要はありません。NumberFormatException
int
(または選択した他の型) の値を返しますFile
入力ソースは、InputStream
、Readable
、 、ReadableByteChannel
に簡単に変更できますPath
。