0

我需要一点帮助。我希望它通过数组并找到与输入的目的地相同的所有目的地,但这只会打印出 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();
    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;   
    }
}
4

2 回答 2

1

你不需要break里面的if声明。这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);
    }
}
于 2013-10-30T10:52:31.187 回答
0

You are breaking the for loop once it finds the first destination:

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;   

}

so the rest of the loop is not getting executed. You need to remove this break; statement.

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;
}
于 2013-10-30T10:41:27.727 回答