2017-04-20 103 views
-3

我正在为我的任务制作一个程序。这不是整个计划,但它只是其中的一部分。在Java中结束while循环

我想从用户输入一些整数值来存储在“items”数组中。当用户输入“停止”循环应该关闭,这是问题..当我写停止程序停止并给我一些错误。

public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 
    int i=0, lines=1; 
    int[] items = new int[100]; 
    int total = 0; 
    System.out.println("Enter the items with its price"); 

    while(true){ 
      i=i+1; 
      if ("stop".equals(scan.nextLine())) 
       break; 
      else 
       items[i] = scan.nextInt(); 
    } 

} 
+3

有什么错误?这是相当重要的 – Carcigenicate

+0

“一些错误” - 这是值得在你的问题中包括这些错误。 – px06

+0

你去了:线程“主”异常java.util.InputMismatchException \t at java.util.Scanner.throwFor(Scanner.java:864) \t at java.util.Scanner.next(Scanner.java:1485) \t在java.util.Scanner.nextInt(Scanner.java:2117) \t在java.util.Scanner.nextInt(Scanner.java:2076) \t在mohammedkabbani_301502670.MohammedKabbani_301502670.main(MohammedKabbani_301502670.java:34) C:\ Users \ Mohammed \ AppData \ Local \ NetBeans \ Cache \ 8.2 \ executor-snippets \ run.xml:53:Java返回:1 BUILD FAILED(总时间:8秒) – Mick2160

回答

1

有一些失误即如果你可以添加错误,它会更好。

试试看看这个代码。

public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 
    int i = 0, lines = 1; 
    int[] items = new int[100]; 
    int total = 0; 
    System.out.println("Enter the items with its price"); 

    while(true){ 
      String InputTxt = scan.nextLine(); 
      if (InputTxt.equals("stop")) 
       break; 
      else{   
       try{ 
       items[i] = Integer.parseInt(InputTxt); 
       i++; 
       }catch(Exception e){ 
       System.out.println("Please enter a number"); 
       } 
      } 

    } 

} 
-1

你的问题是这一行:items[i] = scan.nextInt();因为你试图让整时,在输入字符串stop

编辑 一个可能的解决方案是,你得到你的数据串并检查它是否是stop与否,如果没有然后尝试解析成整型波纹管类似的代码:

在鳕鱼
public static void main(String[] args) { 

Scanner scan = new Scanner(System.in); 
int i=0, lines=1; 
int[] items = new int[100]; 
int total = 0; 
System.out.println("Enter the items with its price"); 
while(true) 
    { 
    i=i+1; 
    String str = scan.nextLine() 
    if ("stop".equals(str)) 
     break; 
    else 
     { 
     items[i] = Integer.parseInt(str) 
     } 
    } 
} 
+0

好的,现在我该怎么办?我想从用户输入整数,当他写完整数时,他应该写停止来结束程序。 – Mick2160

+0

我不认为这是问题,因为'scan.nextLine()'将在该阶段读取任何内容,这不是'NumberFormatException',其中存在转换问题。 – px06

+0

@ px06你对'scan.nextLine()'是正确的,但考虑到在代码中有另外一行是items [i] = scan.nextInt();'所以它会尝试以整数形式获得输入。 – pooyan

0

在其他答案的顶部,我想提醒你改变从

while(true) 

的循环,从而

//first you need to remove the local variable i 
for(int i = 0; i < items.length; ++i) 

使用这种方法会帮助你避免IndexOutOfBoundsException异常当用户键入超过100个整数值时。