![](/img/trans.png)
[英]How to read values from mutiple lines and save them to different array as user inputs them in Java
[英]Reading values from keyboard to save them to an array
這個想法是從鍵盤輸入數字以將它們保存到數組中:
public void set_numbersQ() {
ArrayList<int[]> lf = new ArrayList<>();
int[] fraction= new int[1];
for(int i = 0; i < 2; i++){
try {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
fraction[i] = Integer.valueOf(br.readLine());
}
catch(Exception e){}
}
lf.add(fraction);
System.out.println(fraction[0] + " / " + fraction[1] );
}
這段代碼給了我一個錯誤:
java.lang.ArrayIndexOutOfBoundsException:索引 1 超出長度 1 的范圍。
因為fraction[0]
被正確保存,但fraction[1]
不是。 我認為錯誤可能在InputStreamReader
或BufferedReader
中,因為嘗試正確執行。
Stream 閱讀器應立即打開, fraction
大小必須為2
。
public static void set_numbersQ() {
int[] fraction = new int[2];
try (InputStreamReader input = new InputStreamReader(System.in)) {
Scanner scanner = new Scanner(input);
fraction[0] = scanner.nextInt();
fraction[1] = scanner.nextInt();
System.out.println(fraction[0] + " / " + fraction[1] + " = " + (fraction[0] / fraction[1]));
} catch (Exception ex) {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.