System.out.print("Enter Number to Search: ");
String get = br.readLine();
int input = Integer.parseInt(get);
for(int i = 0; i < 5; i++)
{
num[i] = inFile.nextInt();
}
for(int j = 0; j < 5; j++)
{
if(input == num[j])
{
System.out.println("Search number is found!");
break;
}
else
{
System.out.println("Search number is lost!");
}
}
num [i]内的数字是1,2,3,4,5。
我的问题是,当我尝试搜索数字5时,输出是这样的:
Enter Number to Search: 5
Search number is lost!
Search number is lost!
Search number is lost!
Search number is lost!
Search number found!
如何打印“找到的搜索号码”!没有打印“搜索号丢失!”??
答案 0 :(得分:3)
创建一个布尔表达式并将其设置为false。迭代循环,如果找到了数字,则将其设置为true,然后打印“找到搜索号”。循环结束后,检查布尔值是否为false。如果为false,则打印“搜索号丢失!”
答案 1 :(得分:1)
在第二轮中丢失else语句。
boolean found = false;
for(int j = 0; j < 5; j++) {
if(input == num[j]) {
found = true;
break;
}
}
if(found)
System.out.println("Search number is found!");
else
System.out.println("Search number is lost!");
答案 2 :(得分:0)
基本上我已经从for循环中删除了else语句,并在if语句中添加了一个布尔标志。如果找到该号码,则打印输出并将flag设置为true。循环结束后,检查标志以查看是否找到了该号码。如果没有,请打印出来。
System.out.print("Enter Number to Search: ");
boolean found = false;
String get = br.readLine();
int input = Integer.parseInt(get);
for(int i = 0; i < 5; i++)
{
num[i] = inFile.nextInt();
}
for(int j = 0; j < 5; j++)
{
if(input == num[j])
{
System.out.println("Search number is found!");
found = true;
break;
}
}
if(!found){
System.out.println("Search number is lost!");
}
答案 3 :(得分:0)
尝试以下代码,在输出找到/丢失的号码之前清除所有文本的屏幕。
System.out.print("Enter Number to Search: ");
String get = br.readLine();
int input = Integer.parseInt(get);
for(int i = 0; i < 5; i++)
{
num[i] = inFile.nextInt();
}
for(int j = 0; j < 5; j++)
{
if(input == num[j])
{
system("CLS");
System.out.println("Search number is found!");
break;
}
else
{
system("CLS");
System.out.println("Search number is lost!");
}
}