Java 关于我的数组代码
我需要一点帮助。我希望它遍历数组并找到与输入的目的地相同的所有目的地,但这只会找到打印出的1。有什么建议吗? 多谢各位Java 关于我的数组代码,java,arrays,Java,Arrays,我需要一点帮助。我希望它遍历数组并找到与输入的目的地相同的所有目的地,但这只会找到打印出的1。有什么建议吗? 多谢各位 for (int x = 0; x<40;x++){ String flight; Scanner input = new Scanner (System.in); System.out.println("Enter Flight destination to find: ") ; flight = input.next(); i
for (int x = 0; x<40;x++){
String flight;
Scanner input = new Scanner (System.in);
System.out.println("Enter Flight destination to find: ") ;
flight = input.next();
if (plane[x].destination.equals(flight)){
System.out.println("Found destination! " + "\t" + "at array " + x);
System.out.println(plane[x].flightid + "\t" + plane[x].origin + "\t" + plane[x].destination);
break;
}
}
for(int x=0;x一旦找到第一个目的地,您将中断for
循环:
if (plane[x].destination.equals(flight)){
System.out.println("Found destination! " + "\t" + "at array " + x);
System.out.println(plane[x].flightid + "\t" + plane[x].origin + "\t" + plane[x].destination);
break;
}
因此循环的其余部分没有执行。您需要删除此break;
语句
if (plane[x].destination.equals(flight)){
System.out.println("Found destination! " + "\t" + "at array " + x);
System.out.println(plane[x].flightid + "\t" + plane[x].origin + "\t" + plane[x].destination);
//break;
}
您不需要在if
语句中使用break
。该break
退出循环,这解释了为什么您只看到一个航班。您还需要将输入移到循环之外,否则您将在飞机循环的每次迭代中请求输入
Scanner input = new Scanner (System.in);
System.out.println("Enter Flight destination to find: ") ;
String flight = input.next();
for (int x = 0; x<40;x++){
if (plane[x].destination.equals(flight)){
System.out.println("Found destination! " + "\t" + "at array " + x);
System.out.println(plane[x].flightid + "\t" + plane[x].origin + "\t" + plane[x].destination);
}
}
扫描仪输入=新扫描仪(System.in);
System.out.println(“输入要查找的航班目的地:”);
字符串flight=input.next();
对于(int x=0;xy)您想从整个列表中找到一个目的地吗?谢谢。那真的很容易。谢谢。那真的很容易。