Java使用while循环将用户输入加载到数组中

时间:2014-09-16 02:55:46

标签: java arrays

我想知道如何使用while循环加载数组(使用用户输入)。下面的代码打印出一个0。

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int i = 0;
    int n = 0;
    int[] myArray = new int[10];
    System.out.printf("enter a value>>");
    while (scan.nextInt() > 0) {
        for (i = 0; i > 0; i++) {
            myArray[i] = scan.nextInt();
        }
        System.out.printf("enter a value>>");
    }
    System.out.printf("array index 2 is %d", myArray[2]);
}

3 个答案:

答案 0 :(得分:2)

您的代码存在多处问题:

首先

while(scan.nextInt() > 0){

Scanner.nextInt()会从您的标准输入中返回int,因此您实际上必须获取该值。您在这里检查用户键入的内容,然后根本不使用并存储用户键入的下一个内容:

myArray[i] = scan.nextInt();

你真的不需要外部while循环,只需使用for循环即可。

但是,您的for循环也已关闭:

for(i = 0; i > 0; i++){

i开始等于0并在i大于0时运行。这意味着它永远不会在循环中实际运行代码,因为0永远不会大于0.如果它确实运行了(你开始使用某个数字<0),你最终会进入无限循环,因为对于正数,你的条件i > 0 总是为真。

将循环更改为:

for(i = 0; i < 10; i++){

现在,您的循环可能如下所示:

for(i = 0; i < 10; i++){                  // do this 10 times
    System.out.printf("enter a value>>"); // print a statement to the screen 
    myArray[i] = scan.nextInt();          // read an integer from the user and store it into the array
}

答案 1 :(得分:0)

另一种方法

Scanner scan = new Scanner(System.in);
List list = new ArrayList();
while(true){
    System.out.println("Enter a value to store in list");
    list.add(scan.nextInt());
    System.out.println("Enter more value y to continue or enter n to exit");
    Scanner s = new Scanner(System.in);
    String ans = s.nextLine();
    if(ans.equals("n"))
        break;
}
System.out.println(list);

答案 2 :(得分:0)

public static void main(String[] args)
{
    Scanner input =new Scanner(System.in);
    int[] arr=new int[4];
    int i;
    for(i=0;i<4;i++)
    {
        System.out.println("Enter the number: ");
        arr[i]=input.nextInt();         
    }

    for(i=0;i<4;i++) 
    {
        System.out.println(arr[i]);
    }
}

希望此代码有帮助。

相关问题