這個想法基本上是回圈接受輸入,它一直運行直到我輸入“退出”,但它不能按照我想要的方式作業,我不知道為什么:((ps我是一個來自python的初學者請成為種類)
import java.util.Scanner;
class HelloWorld {
static String s1;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
do {
s1 = in.next();
} while (s1 != "quit");
System.out.println(s1);
}
}
我還嘗試添加一個臨時變數,以便 while 回圈可以在繼續之前檢查條件,但它也不能那樣作業......
import java.util.Scanner;
class HelloWorld {
static String s1;
static String s2;
static int s3;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
do {
s1=in.next();
if (s1=="quit"){
break;
}
s2=in.next();
s3=in.nextInt();
} while (s1!="quit");
System.out.println("Terminate");
}
}
uj5u.com熱心網友回復:
您的代碼作業正常,您不能使用==
運算子來比較字串。改用equals()
orequalsIgnoreCase()
方法。
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
do {
s1 = in.next();
} while (!"quit".equals(s1)); // use equals
System.out.println(s1);
}
如果您通過 == 進行比較,則您正在檢查雙方是否參考同一個物件。當您使用 equals() 時,您正在比較字串值。因此,即使您有多個值為“quit”的物件,==
也會回傳false
,但equals()
會回傳true
。
你可以在這里閱讀更多
uj5u.com熱心網友回復:
要比較字串,您必須使用.equal()
or.equalsIgnoreCase()
方法。這應該作業
uj5u.com熱心網友回復:
你可以試試這個: !s1.equals("quit")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/527501.html
標籤:爪哇
上一篇:如何創建一個空的lucene查詢