如果第一个是真的不要运行第二个
问题描述:
你好,我是新来的Java,并在阅读了一些后,我试图做一个小程序。该程序包含两个如果堆栈,我希望如果一个解决程序结束,而不是读第二个。 这里是我想出的代码:如果第一个是真的不要运行第二个
Scanner 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!");
我想如果“独立如果”是真的程序结束而不运行第二个,有人可以帮助我吗?
答
您也可以使用开关情况:
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
答
尝试像下面
boolean b = false;
if(independent1.equals(userInput)){
System.out.println("You should rely on yourself more than on mystic forces like me");
b = true;
} else if(independent2.equals(userInput)) {
System.out.println("You should rely on yourself more than on mystic forces like me");
b = true;
}else if(independent3.equals(userInput)){
b = true;
System.out.println("You should rely on yourself more than on mystic forces like me");
}
if(!b){
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!");
}
答
我不知道,但下面可能是合适的。
userInput = myScanner.nextLine(); // Entire line maybe?
if (userInput.contains(independent1)) {
...
} else if (userInput.contains(independent2)) {
...
} else if (userInput.contains(independent3)) {
...
} else {
// Maybe you meant the rest to go in here, as alternative.
Random ...
}
看看[IF-then-else语句(http://docs.oracle.com/javase/tutorial/java/nutsandbolts/if.html) – gtgaxiola
怎么样的“否则,如果() “而不是许多”如果“? if(independent1.equals(userInput)) System.out.println(“bla”); else if(independent2.equals(userInput)) System.out.println(“foo”); – Sadik