Scanner sc = new Scanner (System.in);
String enter = new String ("Enter your name brave soul: ");
System.out.println (enter);
String name = sc.next();
System.out.println ("Your name is: " + name + "? Y/N");
boolean y = true;
boolean n = false;
String yesorno = sc.next();
String intro1 = new String ("Welcome to Urieka! The objective of this game is quite simple, just find the key to escape.");
if (true) {System.out.println (intro1);} //here
else if (false) {System.out.println (enter);} //here
我遇到问题,如果用户输入y,我想打印intro1,如果输入错误,我想要提示输入名称。无论我输入是否,它目前只能打印intro1。
此外,有没有办法让我再次运行扫描仪,因为我认为如果我让这个工作并且用户输入n / false,那么它只会打印"输入你的名字勇敢的灵魂&#34 ;没有别的。我会以某种方式将扫描程序添加到else if行上的语句中吗?
答案 0 :(得分:3)
if (true) {System.out.println (intro1);} //here
始终 为true,并且始终会运行。其他人同样从不运行。
你想要
if ("y".equalsIgnoreCase(yesorno)) {
//...
}
答案 1 :(得分:3)
嗯...... true
总是如此
if (true) { ... }
将永远执行。你应该做点什么:
System.out.println("y".equalsIgnoreCase(yesorno) ? intro1 : enter);
答案 2 :(得分:2)
你永远不会改变这些布尔值:
boolean y = true;
boolean n = false;
同时尽量避免使用if(true),如前一篇文章所述:
if (true) {System.out.println (intro1);} //here
实例化String对象时不必使用构造函数:
String enter = new String("Enter your name brave soul: ");
// IS THE SAME AS <=>
String enter = "Enter your name brave soul: ";
以下是我的问题解决方案:
Scanner scanner = new Scanner(System.in);
boolean correctName = false;
String name = "";
while(!correctName){ //== Will run as long "correctName" is false.
System.out.println("Enter your name brave soul: ");
name = scanner.next();
System.out.println("Your name is: " + name + "? Y/N");
String yesorno = scanner.next();
correctName = "Y".equalsIgnoreCase(yesorno); //== changes the boolean depending on the answer
}
System.out.println("Welcome to Urieka" + name + "! The objective of this game is quite simple, just find the key to escape.");
答案 3 :(得分:0)
如果(true)表示它将始终进入if条件,它将始终按原样打印intro01。 永远不会达到其他条件。
你的情况应该是这样的:
if("y".equalsIgnoreCase(yesorno))
System.out.println (intro1);
else
System.out.println (enter);