扫描程序在java中出现问题

时间:2015-08-27 18:11:27

标签: java java.util.scanner

我的扫描仪出了什么问题?我试图不把它放在一个循环中,它不起作用。我希望用户输入一个选项,然后将服务器与选择一起打印出来?

private static String getLogLocation(){
    System.out.print("Please pick one (Dev, UAT, Lab, Sandbox): ");
    Scanner scan = new Scanner(System.in);
    String server = null;
    Boolean breaking = true;
    String choice = scan.nextLine();

    while(scan.hasNext() && breaking){
        if(choice.equals("Dev")){
            server = "CNNDCPV02465.dcld.nndc.kp.org";
            breaking = false;
        }
        if(choice.equals("UAT")){
            server = "CNNDCPV02464.dcld.nndc.kp.org";
            breaking = false;
        }
        if(choice.equals("Lab")){
            server = "CNNDCBIPP242.nndc.kp.org";
            breaking = false;
        }
        if(choice.equals("Sandbox")){
            server = "CNNDCBIPP241.nndc.kp.org";
            breaking = false;
        }
    }
    System.out.println("Server" + server);
    return server;
}

1 个答案:

答案 0 :(得分:2)

您的代码中存在一些问题。

  • 在以前的版本中,你存在循环而有下一个元素,但对于System.in我们无法知道是否有下一个元素,因为这个流总是打开,所以有机会获得新的数据和方法hasNext将等待新数据或关闭此流的信号
  • 在您的代码的较新版本中,每次调用此方法时,您都会创建Scanner包裹System.in,之后您将关闭它,这意味着您也在关闭System.in已关闭,你无法再读它。

因此,不是每次都重新创建Scanner,而是创建一次并将其传递给您的方法,如

private static String getLogLocation(Scanner scanner){
    ...
    String data = scanner.readLine();
    ...
    //scanner.close(); //DON'T do it in this method!!!
}

现在关于你的循环,你可以创建类似的东西:

Set<String> correctOptions = new HashSet<>(Arrays.asList("opt1", "opt2"));// and so on
String option = null;
do {
    System.out.print("select option: ");
    option = scanner.nextLine();
} while (!correctOptions.contains(option));
//here you are sure that selected option is correct
//handle it as you want.