我目前正在嘗試獲取 only 的值。不知道為什么它不讓我在 wordArray 上使用 indexOf。
String bestThing = "The best thing about a boolean is even if you
are wrong you are only off by a bit";
Write code that finds and returns the index of "only" in
"bestThing" once turned into an array
// Display your result using System.out.println(index);
// String bestThing = "The best thing about a boolean is even if
//you are wrong you are
//only off by a bit";
String[] wordArray = bestThing.split(" ");
int index = 0;
for( int i = 0 ; i < wordArray.length; i ){
if (wordArray[i] =="only") {
index = i;
}
}
System.out.println(index);
uj5u.com熱心網友回復:
String[] wordArray = bestThing.split(" ");
int index = 0;
for( int i = 0 ; i < wordArray.length; i ){
System.out.println(wordArray[i]);
if (wordArray[i].equalsIgnoreCase("only")) {
index = i;
}
}
System.out.println(index);
“僅”的輸出使用“.equalsIgnoreCase”給了我 14
uj5u.com熱心網友回復:
在java中你需要使用 String.equals 所以解決方案是:
for( int i = 0 ; i < wordArray.length; i ){
if (wordArray[i].equals("only")) {
index = i;
}
}
System.out.println(index);
uj5u.com熱心網友回復:
你非常親近。問題出在這一行。
if (wordArray[i] == "only")
應該是這個。
if (wordArray[i].equals("only"))
在 Java 中,運算子和方法之間有很大的區別。==
.equals()
==
-- 這將檢查 2 個參考是否確實指向完全相同的物件。我們不關心物件的值,我們關心的是它們是否在字面上參考同一個物件.equals()
-- 這將檢查 2 個參考是否指向相等值的物件。我們不關心兩個參考是否指向同一個物件,我們關心兩個參考是否指向具有相等值的物件
這是一個可能有幫助的類比。
想象一下,我有一瓶水,而你有一瓶水。兩瓶水都未開封,看起來完全一樣。沒有辦法將它們區分開來。
WaterBottle a = my water bottle
WaterBottle b = your water bottle
- a.等于(b)嗎?
是的,這兩種水域之間沒有可測量的差異。如果我們快速旋轉它們,我們就無法知道誰的水瓶是誰的,因為它們完全相同。因此,.equals()
回傳 true
- a == b嗎?
不,我的水瓶是我的,你的水是你的。僅僅因為這兩個水瓶的價值相同,并不意味著==
會退貨true
。==
不關心水的價值,它關心的是a
字面意思 b
。我的水瓶和你的很相似,但我的水瓶不是你的水瓶。我的就是我的,你的就是你的——它們是兩個獨立的物體,在這個時候看起來和嘗起來完全一樣。
更具體地說,在 Java 中,==
運算子檢查參考是否具有完全相同的值。這意味著 this -a
是一個參考,如果您要物理打開計算機并查看 的字面值a
,它將類似于0xaf9121ed
. 那一系列丑陋的值是計算機記憶體中的一個地址。因此,如果兩者a
和b
都具有 的參考0xaf9121ed
,那么它們就是==
。
.equals()
是不同的 - 它是Object
Java 中存在的一種方法,實際上是一種您可以自己定義/覆寫的方法。
例如,在我們的水瓶示例中,假設我們撰寫了.equals()
這樣的方法。
If both bottles have the same color cap, then they are equals
這樣做,我們就可以擁有一個像房子一樣高的水瓶,只要它們的蓋子顏色相同,它就等于一個普通大小的水瓶。.equals()
完全由 objects 方法定義equals()
,您可以自己覆寫它。
在您的示例中,您不在乎 2 個String
物件(您找到的那個,以及您在 if 陳述句中輸入的“唯一”)實際上是同一個物件,您是在詢問String
您是否在 for回圈具有與相同的值"only"
。如果它們具有相同的值,那么這意味著您的字串就是您要查找的字串,然后您可以做任何您想做的事情(僅在原始句子中列印單詞的索引)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475614.html
上一篇:如何在統一2d中翻轉復合字符?
下一篇:如何遍歷陣列并獲取所有專案的值