這個問題在這里已經有了答案: 如何比較 Java 中的字串? (23 個回答) 36 分鐘前關閉。
這是代碼-
import java.util.Scanner;
class Main {
public static void main(String[] args) {
String name;
String genInput;
Scanner sc = new Scanner(System.in);
System.out.println("What is your name?");
name = sc.nextLine();
System.out.println ("Are you sure your name is " name "? Y/N");
genInput = sc.nextLine();
if (genInput == "Y") { //the block thats supposed to react to you confirming your name
System.out.println("Test line A"); }
else if(genInput == "N") { //the block thats supposed to react to you denying your name is correct
System.out.println("Test line B"); }
else; {
System.out.println("Test line C"); } //the block that keeps playing back even when the input shouldnt make it (supposed to account for typos and whatnot)
}
}
當輸入Y時,它應該列印Test Line A,當輸入N時,它應該輸出Test Line B。但是,無論你輸入什么,它都會跳到else陳述句并列印Test Line C。
如果 Else 塊被移除,它不會列印任何內容,如果你將 else 陳述句設為 else if != 到 Y 或 N,那么會發生同樣的效果,它會列印出測驗行 C。我很確定它有一些東西要處理大括號不正常,但我無法弄清楚問題出在哪里,因為即使您將 else if (B) 和 else (C) 陳述句留在外面,它也不會列印任何內容,所以我想出了這個問題在測驗行 A “if”陳述句中或之前。
編輯 - 現在用 .equals 而不是 == 來修復它。感謝@Neddo 和@sam!甚至永遠不會知道 .equals 存在。預審。
uj5u.com熱心網友回復:
在 Java 中,要比較Strings,您不能使用==(我的意思是您可以,但它不會執行您在此處嘗試執行的操作)。相反,使用如下.equals方法:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
String name;
String genInput;
Scanner sc = new Scanner(System.in);
System.out.println("What is your name?");
name = sc.nextLine();
System.out.println ("Are you sure your name is " name "? Y/N");
genInput = sc.nextLine();
if (genInput.equals("Y")) { //the block thats supposed to react to you confirming your name
System.out.println("Test line A"); }
else if(genInput.equals("N")) { //the block thats supposed to react to you denying your name is correct
System.out.println("Test line B"); }
else; {
System.out.println("Test line C"); } //the block that keeps playing back even when the input shouldnt make it (supposed to account for typos and whatnot)
}
}
uj5u.com熱心網友回復:
對 Sam 剛剛回答的內容添加一點,== 比較記憶體位置,因此在以下情況下為真:a) 是具有相同值 (int、double、boolean、float...) 的原始資料型別 b) 兩個變數指向同一個物件。
Strings 有一個特殊情況,如果兩個不同的 String 物件從相同的 String 文字(即:“hello”)中創建,也將回傳 true。
如果你想比較物件內容(狀態),你應該使用 .equals
uj5u.com熱心網友回復:
為什么 ; 之后呢??洗掉它并再次檢查:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/360169.html
標籤:爪哇
上一篇:TabControl-切換選項卡時將UserControlTabItems保留在記憶體中
下一篇:Java同步集合-價值是什么?
