如何在数组中拥有用户控制的输入?

时间:2014-09-21 20:36:47

标签: java arrays user-input

我在没有程序的情况下显示数据时出现问题只允许用户输入一个数字

import java.util.Scanner;

public class ArrayEvenNumber {

        public static void main (String[] args)
        {

            int i,x,a[] = new int[10];



            Scanner input = new Scanner(System.in);


            //user input
            for(i=0;i<10;i++)
            {
             System.out.println("Enter Number :");
             System.out.println("Enter -1 When Finished");
             a[i] = input.nextInt();
             //printing the data
             System.out.println("The integers you've entered are : ");
             for (i=0;i<a.length;i++)
                System.out.println(a[i]);


            }

            System.out.println("Even Numbers are :-");
            //showing the even numbers
            for(i=0;i<10;i++)
            {
                x=a[i]%2;
                if(x==0)
                System.out.println(a[i]);
            }
        }
}

1 个答案:

答案 0 :(得分:1)

只有在您输入数据时才需要打印数据。

 for(i=0;i<10;i++)
    {
     System.out.println("Enter Number :");
     System.out.println("Enter -1 When Finished");
     a[i] = input.nextInt();

    }
//printing the data
     System.out.println("The integers you've entered are : ");
     for (i=0;i<a.length;i++)
        System.out.println(a[i]);

另外,我注意到您的整体代码可以使用一些改进:

Scanner input = new Scanner(System.in);


System.out.println("Enter Number :");
System.out.println("Enter -1 When Finished");

int entered = 0;
int counter = 0;
while(counter < a.length) {
     entered = input.nextInt();
     if(entered == -1) break;
     a[counter] = entered;
     counter++;
}


 System.out.println("The integers you've entered are : ");
 for (i=0;i<a.length;i++)
    System.out.println(a[i]);
 }