2016-03-05 41 views
-3

我在Eclipse中編碼,所以我的一些錯誤消息可能會不同我試圖打印一條消息,所以如果沒有字符'a '在String s3中,那麼它會告訴用戶嘗試另一行代碼。我的語句的if部分沒有問題,但其他部分是。我似乎無法弄清楚如何修正我的語句,所以如果有人能夠幫助,謝謝!試圖操縱Java中的字符串,並繼續獲得「」布爾值「

//print the index of the last occurrence of the character 'a' in string s3 
if (s3.indexOf('a')>= 0 { 
System.out.println("The first occurrence of the character 'a' in both strings is at index " + s3.indexOf('a')); 
} 
else (s3.indexOf('a') > 0) 
System.out.println("There is no occurrence of the character 'a' in either string."); 
} 
+2

開始通過在第一行中添加近距離括號,所以代碼將被編譯。 – Andreas

回答

1

if-then-else語句在「if」子句的計算結果爲false時提供了輔助執行路徑。所以在其他部分你不需要一個條件。

if (s3.indexOf('a')>= 0 { 
System.out.println("The first occurrence of the character 'a' in both strings is at index " + s3.indexOf('a')); 
} 
else { 
System.out.println("There is no occurrence of the character 'a' in either string."); 
} 

而你錯過了其他部分的開放大括號。 欲瞭解更多信息,你可以讀取official java documentation

0

else缺少你的第二個測試的else if,這是無效的(你已經把條件給定有不可達第一個if測試),你可以使用else.S omething像

if (s3.indexOf('a')>= 0 { 
    System.out.println("The first occurrence of the character 'a' " 
      + "in both strings is at index " + s3.indexOf('a')); 
} else { 
    System.out.println("There is no occurrence of the character 'a' " 
      + "in either string."); 
} 

變化

else (s3.indexOf('a') > 0) 

else if (s3.indexOf('a') < 0) 
-1

使用其他的if語句。

if(s3.indexOf('a')>= 0  { 
    System.out.println("The first occurrence of the character 'a' in both strings is at index " + s3.indexOf('a')); 
} 
else if (s3.indexOf('a') < 0) 
    System.out.println("There is no occurrence of the character 'a' in either string."); 
} 
-1

只需使用別的就足夠 第二否則是無法訪問的第一個,如果含有相同的條件