Islam Ismayilov Islam Ismayilov - 3 months ago 19
Java Question

how can i count index of constants in word and sum its in java?

I cannot fix below mentioned issue. i want to see in console correct index of string which insert from scanner. but this code show index of first char which find and dont show correct sum of index of string:

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

Answer

For me, you should simply move the increment in the if test to increment only when we have a match, something like this:

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

Response Update:

You have 1 more issue in your program, you should not use str.indexOf(ch_str) to get the index of the current character as it will give you the index of the first character that matches in the complete String which is not correct if you have several times the same character in the input String, you should use simply s instead as you iterate already over the characters of the String.

The correct code is this:

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

NB: To brake in the inner loop when we have a match, I use a label to go directly to the next iteration of the main loop.

Output:

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

A faster approach could be to use a switch statement instead of an inner loop, something like this:

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