相同的用户输入导致我的 while 循环中的不同输出

The same user input leads to different output in my while loop

我的以下代码有问题。

当我输入选项 1 时,它会要求我输入 IATA 代码并显示我期望的输出,但是如果我再次输入选项 1,即使我输入了有效代码,控件也会变成无效的 IATA 代码。

如果我输入除 1 和 2 以外的其他选择,它应该会显示无效选择,但事实并非如此。

我不明白为什么会这样,有人可以帮忙吗?

import java.util.*;
import java.io.*;
public class AirportCode {

    public static void main(String[] args) throws IOException {

    Scanner sc = new Scanner(System. in );
    System.out.print("Enter input file name >>");
    String fname = sc.next();
    File fp = new File("E:/task.txt");
    Scanner kb = new Scanner(fp);
    int choice = 0;

    while (choice != 2) {
        System.out.println("AirPort Finder");
        System.out.println("1. Enter Airport");
        System.out.println("2. Close");
        choice = sc.nextInt();
        if (choice == 2) {
            break;
        } else if (choice == 1) {
            System.out.println("Enter IATA code >>");
            String code = sc.next();
            kb.useDelimiter(",");
            boolean check = false;
            if (code.length() == 3) {
                while (kb.hasNextLine()) {
                    String icode = kb.next();
                    String apcode = kb.next();
                    String icode1 = kb.next();
                    String apcode1 = kb.nextLine();

                    if (icode.contains(code)) {
                        check = true;
                        System.out.println(icode1 + " " + apcode1);
                    }
                    if (icode1.contains(code)) {
                        check = true;
                        System.out.println(icode + " " + apcode);
                    }
                }
                if (check == false) System.out.println("Invalid IATA code");
            } else System.out.println("Invalid IATA code");
        }
    }
    System.out.println("Invalid menu choice");
    }
}

据我所知,您应该将最后一个 System.out.println...无效菜单选项用 else-block 包裹起来...就像您现在做的那样,您将转到那个行,无论您输入 1、2 还是任何其他数字,因为此行位于您的 if-else 块之后,而不是它的一部分。 我希望这有帮助。 问候

If i again enter choice 1 the control goes to invalid iata code

您的问题是您用于检查文件 (kb) 中有效 IATA 代码的扫描程序在您第一次使用后就已耗尽。

如果您使用 ScannerFile 获取输入,一旦您完成一次,kb.hasNextLine() 将始终为假。因此,您第二次尝试选项 1 时,从未进入检查循环 (while(kb.hasNextLine()))。

您有两个选择 - 在外部 while 循环中为文件创建 Scanner 以便每次都得到一个新的,或者将文件中的数据读入某种本地数据类型以便您可以多次浏览它。

If i enter different choice other than 1 and 2. it should display invalid choice

您的无效菜单选择文本永远不会显示,因为它在 while (choice != 2) 循环之外。因此,只有当您输入选项 2 并跳出循环时,您才会看到它。您应该将其上移一级(即紧接其前的花括号上方)。