有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为用户重复程序

我是一名Java初学者,我编写了一个简单的Java输入程序。我给了用户一个选项,让他们可以在一段时间内重复这个程序,但是它不能正常运行。有人能指出我的错误吗

public static void main(String args[]){
    char repeat = 0;
    Scanner input = new Scanner(System.in);
    do{ 
        String word = null;
        boolean oneWord = false;
        while(!oneWord){
            System.out.println("Please enter a word: ");
            try{
                word = input.nextLine().toLowerCase();
                word= word.trim();
                int words = word.isEmpty() ? 0 : word.split("\\s+").length;
                if(words==1 && word.length()>1 && word.length()<100){
                    System.out.println("Success");
                    oneWord = true;
                    System.out.println("Continue(Y/N)");
                    repeat = input.next().charAt(0);
                }else{
                    System.out.println("Failure.");
                }
            } catch (Exception e) {
                System.out.println("Exception occurred");
            }
        }
    }while(repeat=='Y'|| repeat=='y');
    input.close();
}

共 (2) 个答案

  1. # 1 楼答案

    即使是复制品,也要看一看这条线

    repeat = input.next().charAt(0);
    

    把它改成

    repeat = input.nextLine().charAt(0);
    

    这会解决你的问题。有关该问题的更多信息,请阅读duplicate link

  2. # 2 楼答案

    我建议您使用Scanner类的nextLine()函数,而不是next()函数

    See the difference here