需要输入数组直到用户输入0 JAVA

我需要帮助理解如何编写一个接受一定数量整数的for循环(必须是1到10)并且一旦输入0就停止接收数字(0将是最后一个数字)。 到目前为止我的代码是:

import java.util.Scanner; public class countNum { public static void main(String[] args) { int[] array; Scanner input = new Scanner(System.in); System.out.println ("Enter in numbers (1-10) enter 0 when finished:"); int x = input.nextInt(); while (x != 0) { if (x > 2 && x < 10) { //Don't know what to put here to make array[] take in the values } else //Can I just put break? How do I get it to go back to the top of the while loop? } } } 

}

我不明白如何同时初始化具有设定长度的数组,同时让扫描仪读取该未知长度的一定数量的数字,直到输入0,然后循环停止接收该数组的输入。

谢谢你的帮助!

好的,这里有更多细节: –

  • 如果需要动态增加的数组,则需要使用ArrayList 。 你这样做: –

     List numbers = new ArrayList(); 
  • 现在,在上面的代码中,您可以将number读取语句( nextInt )放在while循环中,因为您需要定期读取它。 并在while循环中放入一个条件来检查输入的数字是否为int: –

     int num = 0; while (scanner.hasNextInt()) { num = scanner.nextInt(); } 
  • 此外,您可以自己移动。 只需检查数字是否为0 。 如果它不是0 ,则将其添加到ArrayList : –

     numbers.add(num); 
  • 如果为0 ,则跳出你的while循环。

  • 而且你在while循环中不需要x != 0条件,因为你已经在循环中检查了它。

在您的情况下,用户似乎能够输入任意数量的数字。 对于这种情况,拥有一个数组并不理想,因为在数组初始化之前需要知道数组的大小。 你有一些选择:

  1. 使用ArrayList 。 这是一种动态扩展的动态数据结构。
  2. 询问用户他/她将要输入的数量,并使用它来初始化arrays。
  3. 基于大小的一些假设创建一个数组。

在情况2和3中,您还需要包含一些逻辑,使程序在以下情况下停止:(1)用户输入0(2)或当用户提供的数字量超过数组大小时。

我建议坚持第一个解决方案,因为它更容易实现。

我强烈建议你去学习Java Collections。

你可以修改你的程序

 import java.util.ArrayList; import java.util.InputMismatchException; import java.util.List; import java.util.Scanner; public class arrayQuestion { public static void main(String[] args) { List userInputArray = new ArrayList(); Scanner input = new Scanner(System.in); System.out.println("Enter 10 Numbers "); int count = 0; int x; try { do { x = input.nextInt(); if (x != 0) { System.out.println("Given Number is " + x); userInputArray.add(x); } else { System.out .println("Program will stop Getting input from USER"); break; } count++; } while (x != 0 && count < 10); System.out.println("Numbers from USER : " + userInputArray); } catch (InputMismatchException iex) { System.out.println("Sorry You have entered a invalid input"); } catch (Exception e) { System.out.println("Something went wrong :-( "); } // Perform Anything you want to do from this Array List } } 

我希望这可以解决你的疑问..除此之外,如果用户输入如上所述的任何字符或无效输入,则需要处理exception