gpt4 book ai didi

java - 如果第一个为真,则不要运行第二个

转载 作者:行者123 更新时间:2023-12-01 23:16:34 25 4
gpt4 key购买 nike

你好,我是 Java 新手,在阅读了一些相关内容后,我尝试编写一个小程序。该程序包含两个 if 堆栈,我希望如果第一个堆栈解决程序结束并且根本不读取第二个堆栈。这是我想出的代码:

扫描仪 myScanner = new Scanner(System.in);

     String independent1 = "money";
String independent2 = "succes";
String independent3 = "career";
String userInput;
int randomNumber;
System.out.println("I'm listening mortal. Pick your topic.");

userInput = myScanner.next();



if(independent1.equals(userInput))
System.out.println("You should rely on yourself more than on mystic forces like me");
if(independent2.equals(userInput))
System.out.println("You should rely on yourself more than on mystic forces like me");
if(independent3.equals(userInput))
System.out.println("You should rely on yourself more than on mystic forces like me");

Random myRandom = new Random();
randomNumber =myRandom.nextInt(100)+1;
if (randomNumber >= 50){
System.out.println(randomNumber);
System.out.println("Yes");
} else {
System.out.println(randomNumber);
System.out.println("No!");

我想如果“独立如果”为真,则程序结束并且不运行第二个程序,有人可以帮助我吗?

最佳答案

使用if/else if

if(independent1.equals(userInput)){
....
} else if(independent2.equals(userInput)){
....
} else if(independent3.equals(userInput)){
...
}

如果您使用java 1.7您还可以将 switch 语句与字符串一起使用。它们的介绍是 JSR 334 .

switch(userInput){
case "money":
....
break;
case "succes":
....
break;
case "career":
....
break;
}

关于java - 如果第一个为真,则不要运行第二个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21120184/

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