使用Scanner逐字母分析for循环中的字符串(抛出IndexOutOfBoundExceptions)



我需要计算字母在字符串中出现的频率。

为此,我考虑使用一个scanner对象,将字符串传递给它

扫描仪s=新扫描仪(字符串(

并使用next((方法通过switch语句分析每个字符。

我在这些板上进行了搜索,并设计了以下内容:-

for (int i = 0; i < outputString.length(); i++) {
Scanner s = new Scanner(outputString);
char letter = s.next().charAt(i);
switch (letter) {
switch code;
}

当我正在分析的字符串包含除空白之外的任何内容(_z1等(时,这似乎有效,这将导致程序抛出string.IndexOutOfBoundException(4(。

还有什么我可以尝试的吗?还是应该删除单词中的所有空格(即,我正在考虑使用for循环创建一个新词字符串来添加每个字符串。charAt(I(!="(。

编辑:我忘了扫描仪在for循环中,我会把它拿出来。其次,不确定它是否会改变,但我正在尝试计算字符串中字母表中每个字母出现的次数,而不仅仅是一种类型的字母。感谢您的评论!

提前感谢

以下是在另一个问题上提供的解决此问题的另一种方法。(还不能留下评论…所以必须给出答案…(如何计算字符串中字符的频率?

当有这个:

Scanner s = new Scanner(outputString);

for循环中,您在每次迭代中都要创建一个新的Scanner(既不高效,也不符合您的要求(。

如果您已经有一个名为outputStringString,您可以直接访问其字符/字母,如下所示:

for (int i = 0; i < outputString.length(); i++) {
char letter = outputString.charAt(i);
//The rest of you code here
}

我强烈认为使用这种方法会使事情变得复杂。您可以简单地将字符串(和您正在搜索的字符(传递到如下方法中:

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;
}

我希望这能有所帮助。。编码快乐!

您应该按照上面的解决方案来获取字符串中的重复字符。然而,我只会给你一个提示,为什么你会得到异常

考虑以下代码:

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);
}

首先,您不应该在每次准备下一个字符时创建new Scanner。只做一次,在for loop之前。

Second-要逐个字符读取扫描仪,您已将delimeter设置为""。在这种情况下,scan.next()返回下一个字符。

Third-您使用Scanner来分析字符串,这是可以的(不是最佳的和开销,但可以(。然后创建新的Scanner属性,并依赖于它的数据,而不依赖于管理字符串的长度;务必使用CCD_ 12方法。我的意思是,你所需要的只是添加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
}
}

p.S.这是代码示例,说明如何用不同的方法计算给定字符串中的字符频率。也许,你会发现其中一个与你的任务更相关。

// 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();
}

最新更新