This question already has an answer here:
Can't use Scanner.nextInt() and Scanner.nextLine() together [duplicate]

(1个答案)


5年前关闭。





import java.util.Scanner;

public class JavaMovies {
      Scanner det = new Scanner(System.in);
      int age = det.nextInt();

public static void main(String[] args){
    calculator();


}


public static void calculator(){

Scanner det = new Scanner(System.in);

    String rMovie = "Attack of the nerds";
    String mMovie = "Nerd lyfe";
    String pgMovie = "Nerd adventures";
    String gMovie = "Nerd playtime";
    System.out.println("These are the movies that are playing this weekend"
            + rMovie
            + mMovie
            + pgMovie
            + gMovie);
    System.out.println("Please input your age");
   int age = det.nextInt();


System.out.print("Input the movie you wish to see:");
    String x = det.nextLine();                             //Program ends here...

    if(x.equals("Attack of the nerds") & age > 17){
        System.out.println("You can see Attack of the nerds");

    }else if(x.equals("Attack of the nerds") & age < 18){
        System.out.println("You can see attack of the nerds!");

    }if(x.equals("Nerd lyfe")& age > 15){
        System.out.println("You can see Nerd lyfe");

    }else if(x.equals("Nerd lyfe")& age < 16){
        System.out.println("You can not see Nerd lyfe");

    }if (x.equals("Nerd adventures")& age > 10){
        System.out.println("You can see Nerd adventures");

    }else if(x.equals("Nerd adventures")& age < 11){
        System.out.println("You can not see Nerd adventures");

    }if(x.equals("Nerd playtime")& age > 5){
        System.out.println("You can see Nerd playtime");

    }else if(x.equals("Nerd playtime")& age < 6){
        System.out.println("You can not see Nerd playtime");


    }
}
}


一切正常,直到if语句的开始,我该怎么做才能解决此问题?

控制台输出(使用netbeans)
跑:
这些是本周末上映的电影书呆子的攻击书呆子lyfe书呆子冒险书呆子玩耍时间
请输入您的年龄
14
输入您想看的电影:成功完成(总时间:4秒)

最佳答案

我认为问题在于nextInt不会用完整行。如果在提示您输入年龄时键入32,则nextInt将使用32字符,但是输入字符串中仍剩余换行符。然后,当您调用nextLine时,效果是返回当前行中剩余的所有内容,直到下一个新行。由于当前行仍具有换行符,因此导致String x = det.nextLine()x设置为空字符串。

提示播放电影之前,尝试det.nextLine();。 (您无需将其分配给变量;只需丢弃结果即可。)这将导致扫描程序使用换行符,以便下一个nextLine()将获得另一行输入。

07-24 09:38
查看更多