gpt4 book ai didi

java - 它到达 if 语句并停止工作,我做错了什么(java 新手)

转载 作者:行者123 更新时间:2023-12-01 12:47:05 26 4
gpt4 key购买 nike

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)运行:这些是本周末播放的电影 Nerd 的攻击 Nerd lyfe Nerd 冒险 Nerd 玩耍时间请输入您的年龄14输入您想看的电影:BUILD SUCCESSFUL(总时间:4秒)

最佳答案

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

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

关于java - 它到达 if 语句并停止工作,我做错了什么(java 新手),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24592076/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com