在Java中结束while循环
问题描述:
我正在为我的任务制作一个程序。这不是整个计划,但它只是其中的一部分。在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();
}
}
答
有一些失误即如果你可以添加错误,它会更好。
试试看看这个代码。
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");
}
}
}
}
答
你的问题是这一行: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)
}
}
}
答
在其他答案的顶部,我想提醒你改变从
while(true)
的循环,从而
//first you need to remove the local variable i
for(int i = 0; i < items.length; ++i)
使用这种方法会帮助你避免IndexOutOfBoundsException异常当用户键入超过100个整数值时。
有什么错误?这是相当重要的 – Carcigenicate
“一些错误” - 这是值得在你的问题中包括这些错误。 – px06
你去了:线程“主”异常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