null
这是我的代码atm。如何返回if语句并在捕获后继续循环?
答案 0 :(得分:0)
您可以将其嵌入循环中,
for (;;) { // <-- start an infinite loop
System.out.println("Please enter the item name");
if (s.nextLine() != "") {
item = s.nextLine();
}
try {
ZybezChecker zb = new ZybezChecker(item);
zb.getAveragePrice();
System.out.println(zb.toString());
break; // <-- terminate the infinite loop.
} catch(Exception e) {
System.out.println("Something went wrong. Perhaps an "
+ "invalid item name?");
e.printStackTrace(); // <-- tell them what went wrong.
}
}
答案 1 :(得分:0)
我认为(如果我理解你的问题和代码正确)你想要的是一个包含s.nextLine()的循环。请注意,我在这里假设了几件事:
如果是这种情况,那么你应该创建一个这样的循环:
while (true) {
System.out.println("Please enter the item name");
if (s.nextLine() != "") {
item = s.nextLine();
}
try {
ZybezChecker zb = new ZybezChecker(item);
zb.getAveragePrice();
System.out.println(zb.toString());
break;
} catch(Exception e) {
System.out.println("Something went wrong. Perhaps an invalid item name?");
}
}
另外,为什么要两次调用nextLine()?当您第一次调用它时,它将从扫描仪读取一行。当你再次调用它时,它不会返回同一行;它将改为等待换行。这意味着用户必须输入一些随机字符串,然后输入实际值。最后,你不应该在字符串上使用==或!=。由于它们是引用类型,因此您基本上检查它们是否占用内存中的相同位置,而不是它们是否相等。使用s.nextLine()。equals(&#34;&#34;)代替。