簡體   English   中英

每當我從鍵盤(java)輸入新數字時,如何將數字存儲到數組中?

[英]How can I store numbers into array every time I input a new number from keyboard (java)?

import java.util.Scanner;
public class smth {
      Scanner input = new Scanner(System.in);
      int array[]={};

}

接下來我該怎么做,將我從鍵盤輸入的每個數字存儲到數組中。

涉及Scanner對象的while()循環將是有益的。 您不需要每次通過循環都重新初始化/聲明它。

import java.util.Scanner;
public class smth {
    final int SIZE = 10; // You need to define a size.
    Scanner input = new Scanner(System.in);
    int array[]= new int[SIZE];

    public void readFromTerminal() {
        System.out.println("Read lines, please enter some other character to stop.");
        String in = input.nextLine();
        while ( ) { } // I encourage you to fill in the blanks!
    }
}

[編輯]如果希望用戶能夠輸入“無限”的整數,那么ArrayList<Integer>會更理想。

import java.util.Scanner;
public class smth {
    Scanner input = new Scanner(System.in);
    ArrayList<Integer> array = new ArrayList<Integer>(); //  Please reference the documentation to see why I'm using the Integer wrapper class, and not a standard int.

    public void readFromTerminal() {
        System.out.println("Read lines, please enter some other character to stop.");
        String in = input.nextLine();
        while ( ) { } // I encourage you to fill in the blanks!
    }
}
Scanner input = new Scanner(System.in);
          ArrayList<Integer> al = new ArrayList<Integer>();

            int check=0;
            while(true){
                check = input.nextInt();
                if(check == 0) break;
                al.add(check);

            }

            for (int i : al) {
                System.out.print(i);
            }


}

那就是我所做的。 當用戶輸入“ 0”時,它將中斷。

您將要根據某些條件將其包裝在while循環中。 現在,它可能只是while(true)... ,但是稍后您將要使用一個會在某個時刻終止的條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM