繁体   English   中英

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

[英]Java using a while loop to load user input into an array

我想知道如何使用 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]);
}

您的代码有很多问题:

首先

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
}

另一种方法来做到这一点

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);
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]);
    }
}

希望这段代码有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM