简体   繁体   English

Java:使用BufferedReader检查字符串中的更改

[英]Java: Checking for changes in a String with BufferedReader

If trying to get user input into a string, using the code: 如果尝试使用户输入字符串,请使用以下代码:

String X = input("\nDon't just press Enter: ");

and if they did't enter anything, to ask them until they do. 如果他们什么都没输入,请问他们直到他们输入。

I've tried to check if it's null with while(x==null) but it doesn't work. 我试图用while(x == null)检查它是否为null,但是它不起作用。 Any ideas on what I am doing wrong/need to do differently? 关于我做错了/需要做的事情的任何想法?

input() is: input()是:

  static String input (String prompt)
    {
        String iput = null;
        System.out.print(prompt);
        try
        {
            BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
            iput = is.readLine();

        }

        catch (IOException e)
        {
            System.out.println("IO Exception: " + e);
        }
        return iput; 
        //return iput.toLowerCase(); //Enable for lowercase
    }

In order to ask a user for an input in Java, I would recommend using the Scanner (java.util.Scanner). 为了向用户请求Java输入,我建议使用扫描仪(java.util.Scanner)。

Scanner input = new Scanner(System.in);

You can then use 然后,您可以使用

String userInput = input.nextLine();

to retrieve the user's input. 检索用户的输入。 Finally, for comparing strings you should use the string.equals() method: 最后,为了比较字符串,您应该使用string.equals()方法:

public String getUserInput(){
    Scanner input = new Scanner(System.in);
    String userInput = input.nextLine();
    if (!userInput.equals("")){
        //call next method
    } else {
        getUserInput();
    }
}

What this "getUserInput" method does is to take the user's input and check that it's not blank. 此“ getUserInput”方法的作用是获取用户的输入并检查其是否为空白。 If it isn't blank (the first pat of the "if"), then it will continue on to the next method. 如果不为空(“ if”的第一拍),则它将继续进行下一个方法。 However, if it is blank (""), then it will simply call the "getUserInput()" method all over again. 但是,如果为空(“”),则它将再次简单地再次调用“ getUserInput()”方法。 There are many ways to do this, but this is probably just one of the simplest ones. 有很多方法可以做到这一点,但这可能只是最简单的方法之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM