Yahoo 知識+ 將於 2021 年 5 月 4 日 (美國東岸時間) 停止服務,而 Yahoo 知識+ 網站現已轉為僅限瀏覽模式。其他 Yahoo 資產或服務,或你的 Yahoo 帳戶將不會有任何變更。你可以在此服務中心網頁進一步了解 Yahoo 知識+ 停止服務的事宜,以及了解如何下載你的資料。
A very simple Java question involving Strings and if else statements.?
Hello there. I am a new java programmer and am learning about all the features. So my question is, is how can I add Strings into if else statements? I know how to do it with integers, but not strings.
Example with integers.
import java.util.Scanner;
public class yahooTest {
public static void main(String args []) {
Scanner kb = new Scanner(System.in);
int yes, no.
yes = 1;
no - 0;
System.out.println("Yes or No?");
Scanner kb = answer.nextInt();
if (yes == 1) {
System.out.println("You've chosen yes.");
}else{
System.out.println("You've chosen no.");
}
}
}
Would someone please help me out by telling me how I can do this with Strings? I am trying to make a choose your own adventure game, and it would be very very helpful to know. Thank you very much!
1 個解答
- brilliant_movesLv 76 年前最愛解答
Hi, Finn. This is how you would use if / else with a String. You could use .equals() instead of .equalsIgnoreCase() if you want.
import java.util.Scanner;
public class YahooTest {
public static void main(String args []) {
Scanner kb = new Scanner(System.in);
String answer;
System.out.println("Yes or No?");
answer = kb.nextLine();
if (answer.equalsIgnoreCase("yes")) {
System.out.println("You've chosen yes.");
}else{
System.out.println("You've chosen no.");
}
}
}