我正在處理一個賦值,它讓我們填寫8種不同的方法。對於我正在處理的特定方法,我必須查看該字符串是否包含字母'G'並返回。我想出了一些我認爲可行的事情,但事實並非如此。此外,這是一個基本的Java類,我很新,所以請解釋你做了什麼。編寫一個方法來查看字符串x是否包含字母「G」
/**
* Where is the location of the letter G (upper or lower case) in
* the given string?
* @param x String to check
* @return 0 based location of first occurrence of G in x,
* -1 if G is not present.
*/
public static int indexOfG(String x) {
char[] array = x.toCharArray();
for(int i = 0; i < array.length; i++){
if(array[i] == 'G'){
return i ;
}
}
}
對不起,這不是StackOverflow的是如何工作的方法。問題形式_「這是我的一堆代碼,請爲我調試」_被認爲是無關緊要的。請訪問[幫助]並閱讀[問]以獲取更多信息。 「不起作用」是不夠的。 –
首先,如果在字符串中找不到字母,最後(在for循環後)缺少'return -1;'。另外,該方法是不區分大小寫的?如果是這樣,將你的'if'改爲:'if(array [i] =='G'|| array [i] =='g')'。 – AntonH
爲什麼要創建一個字符數組?正如其他人所說,你可以使用x,indexOf()。如果你不允許這樣做(即,如果你需要自己寫),爲什麼不測試x.charAt(i)? – FredK