Java if(!found)语句工作不正常
程序将要求用户输入他想要搜索的项目的代码。如果该项目的代码存在,它将打印到屏幕上,所有工作正常,直到这里。问题是当用户输入不存在的代码时,程序将无法运行。它不打印“未找到项目” 这是密码Java if(!found)语句工作不正常,java,Java,程序将要求用户输入他想要搜索的项目的代码。如果该项目的代码存在,它将打印到屏幕上,所有工作正常,直到这里。问题是当用户输入不存在的代码时,程序将无法运行。它不打印“未找到项目” 这是密码 public void searchItem(){ boolean invalidInput; int q = -1; do { try { boolean found = false; invali
public void searchItem(){
boolean invalidInput;
int q = -1;
do {
try {
boolean found = false;
invalidInput = false;
System.out.println("Enter the item's code you want to search for : ");
q = s.nextInt();
out: for (int i = 0; i<items.length; i++){
if(q == items[i].getCode()){
System.out.println(items[i].toString());
found = true;
System.exit(2);
}
counter++;
}
if(!found)
System.out.print("Item not found");
} catch (InputMismatchException e) {
System.out.println("Please enter a valid code [Numbers Only]");
s.next();
invalidInput = true; // This is what will get the program to loop back
}
} while (invalidInput);
}
public void searchItem(){
布尔输入;
int q=-1;
做{
试试{
布尔值=false;
无效输入=假;
System.out.println(“输入要搜索的项目代码:”);
q=s.nextInt();
out:for(int i=0;i如果我使用你的代码的这个(压缩形式),它会工作,并像我们预期的那样打印“Item not found”…所以问题出在我感觉的其他地方
请提供有关如果您输入丢失(但有效)的项目编号会发生什么情况的更多信息
public static void main(String[] args) {
boolean invalidInput;
int q = -1;
int[] items = { 1, 2, 3, 4 };
do {
boolean found = false;
invalidInput = false;
System.out.println("Enter the item's code you want to search for : ");
q = 5;
for (int i = 0; i < items.length; i++) {
if (q == items[i]) {
System.out.println(items[i]);
found = true;
System.exit(2);
}
}
if (!found)
System.out.print("Item not found");
} while (invalidInput);
}
publicstaticvoidmain(字符串[]args){
布尔输入;
int q=-1;
int[]项={1,2,3,4};
做{
布尔值=false;
无效输入=假;
System.out.println(“输入要搜索的项目代码:”);
q=5;
对于(int i=0;i
请正确格式化您的代码。这样您将更容易看到任何错误。因为,您在找到某个内容后退出程序,您可以简单地在循环后打印not found。为什么不按照您在其他文件中的建议使用break
?我尝试过了,它不起作用getCode()返回什么?请详细解释。