gpt4 book ai didi

java - 我如何计算 word 中常量的索引并在 java 中对其求和?

转载 作者:行者123 更新时间:2023-11-30 10:39:48 30 4
gpt4 key购买 nike

我无法解决下面提到的问题。我想在控制台中看到从扫描仪插入的字符串的正确索引。但是此代码显示第一个字符的索引,它找到但不显示字符串索引的正确总和:

public class task8 {

public static void main(String[] args) {
Scanner sc= new Scanner(System.in);

System.out.println("Insert word:");

String str;
str = sc.nextLine();

char [] consonants = {'b', 'c', 'd', 'f','g','j','h','q','x','z','l','m','p','s','r' , 'n', 't'};
int conlenth = consonants.length;
int sum_ind =0;


for (int s=0; s < str.length(); s++){
for ( int i = 0; i < conlenth ; i++){
char ch_cons = consonants[i];
char ch_str = str.charAt(s);
int con_ind = str.indexOf(ch_str);
sum_ind = sum_ind + con_ind;
if (ch_str == ch_cons){
System.out.println( "cons. = " + ch_cons + " index = " + con_ind );

}
}
}
System.out.println("summ index = " + sum_ind);
}
}

最佳答案

对我来说,您应该简单地将 if 测试中的增量移动到仅当我们有匹配项时才增加,如下所示:

...
int con_ind = str.indexOf(ch_str);
if (ch_str == ch_cons) {
sum_ind += con_ind;
System.out.println( "cons. = " + ch_cons + " index = " + con_ind );
}

响应更新:

你的程序还有一个问题,你不应该使用 str.indexOf(ch_str) 来获取当前字符的索引,因为它会给你第一个匹配字符的索引在完整的 String 中,如果您在输入的 String 中有多次相同的字符,那么这是不正确的,您应该简单地使用 s 而不是已经遍历 String 的字符。

正确的代码是这样的:

main: for (int s=0; s < str.length(); s++){
char ch_str = str.charAt(s);
for ( int i = 0; i < conlenth ; i++){
char ch_cons = consonants[i];
if (ch_str == ch_cons){
sum_ind += s;
System.out.println( "cons. = " + ch_cons + " index = " + s );
continue main;
}
}
}

注意:当我们有匹配项时,为了在内部循环中停止,我使用标签直接进入主循环的下一个迭代。

输出:

Insert word:
hello
cons. = h index = 0
cons. = l index = 2
cons. = l index = 3
summ index = 5

更快的方法可能是使用 switch 语句而不是内部循环,如下所示:

for (int s=0; s < str.length(); s++){
char ch_str = str.charAt(s);
switch (ch_str){
case 'b':
case 'c':
...
case 'z':
sum_ind += s;
System.out.println( "cons. = " + ch_cons + " index = " + s );
break;
}
}

关于java - 我如何计算 word 中常量的索引并在 java 中对其求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39172364/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com