3 回答

TA貢獻1827條經(jīng)驗 獲得超9個贊
我強烈認為您使用這種方法會使事情復(fù)雜化。您可以簡單地將字符串(以及您正在搜索的字符)傳遞給一個方法,如下所示:
public int checkFreq(char letter, String word){
int freq = 0;
for(int i = 0; i < word.length(); i++){
if((word.charAt(i)) == letter){
freq++;
}
}
return freq;
}
我希望這會有所幫助.. 編碼愉快!

TA貢獻1982條經(jīng)驗 獲得超2個贊
首先,new Scanner當(dāng)你準(zhǔn)備好下一個角色時,你不應(yīng)該每次都創(chuàng)建。只做一次,之前for loop。
第二- 要逐個字符讀取掃描儀,您已設(shè)置delimeter為"". 在這種情況下,scan.next()返回下一個字符。
第三- 你Scanner用來分析字符串,沒關(guān)系(不是最佳和開銷,但沒關(guān)系)。然后創(chuàng)建新的Scanner實例并依賴它的數(shù)據(jù),但不依賴于被治理字符串的長度;使用Scanner.hasNext()方法。我的意思是,您所需要的只是添加hasNext()以確保掃描儀的流中存在更多字符:
try (Scanner scan = new Scanner(outputString)) {
scan.useDelimiter(""); // to make scan.next() return one single character
while (scan.hasNext()) {
char ch = scan.next().charAt(0); // next() returns String with one character
// do your work
}
}
PS這是代碼示例,如何用不同的方式計算給定字符串中的字符頻率。您可能會發(fā)現(xiàn)其中之一與您的任務(wù)更相關(guān)。
// this is your approach
public static int characterFrequency(String str, char ch) {
try (Scanner scan = new Scanner(str)) {
scan.useDelimiter("");
int count = 0;
while (scan.hasNext())
count += scan.next().charAt(0) == ch ? 1 : 0;
return count;
}
}
// this one is the most efficient
public static int characterFrequency(String str, char ch) {
int count = 0;
for (int i = 0; i < str.length(); i++)
count += str.charAt(i) == ch ? 1 : 0;
return count;
}
// this one is the smallest of code
public static int characterFrequency(String str, char ch) {
return (int)str.chars().filter(e -> e == ch).count();
}

TA貢獻1796條經(jīng)驗 獲得超4個贊
您應(yīng)該按照上述解決方案獲取字符串中的重復(fù)字符。但是,我只會提示您為什么會遇到異常
考慮以下代碼:
String outputString = "Pre ";
for (int i = 0; i < outputString.length(); i++) {
Scanner s = new Scanner(outputString);
System.out.println(outputString.length()); // output is 4
System.out.println(s.next().length()); //output is 3, not considering the space
//char letter = s.next().charAt(i);
//System.out.println(letter);
}
添加回答
舉報