Home > Back-end >  How to multiply different indexes by different values?
How to multiply different indexes by different values?

Time:11-14

I am creating a scrabble game, where the characters get the same values as scrabble,(q & z =10),(k=5), etc, and the main issue that I am having is that I am asking the user to input 2 ints after the word, the first being the index of the bonus tile, and the second being the multiplier to multiply the word with. The value without the multiplier is correct, but the multiplier is not working.

public class Main {

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        String word = kb.next();
        int bonusI = kb.nextInt();
        int bonusMult = kb.nextInt();
        int score=0;
        for (int i=0; i<word.length();i  ){
            int letterScore;
            String letter=word.substring(i,i 1);
            if (letter.equals("d")||letter.equals("g")){
                letterScore=2;
            }
            else if (letter.equals("k")) {
                letterScore=5;
            }
            else if (letter.equals("j")||letter.equals("x")){
                 letterScore=8;
            }
            else if (letter.equals("q")||letter.equals("z")) {
                letterScore=10;
            }
            else {
                letterScore=1;
            }    
            
             for (int j=0;j<1;j  ){
                 if (word.substring(i,i 1).equals(bonusI)){
                     letterScore*=bonusMult;
                 }
             }

        
            score =letterScore;
           
    }
    System.out.println(score);

  }
}

For example, if the input is dog 2 3 then the correct output would be 9,(d is 2 points,o according to scrabble is 1 point, and g is 2 points, but since the 1st int inputted was 2, and g has an index of 2, it is then multiplied by the bonus of 3, which makes g=6, adding them 2 1 6=9) but instead my output is 5 because the multiplier for g is not working.

CodePudding user response:

Looks like you have a mistake here.

word.substring(i,i 1).equals(bonusI)
  • word.substring(i,i 1) is String and gives one letter
  • bonusI is an int and tives one number

This will never be true

CodePudding user response:

if (word.substring(i,i 1).equals(bonusI)) - This condition will be always false as you can't compare a string with int value.

Instead you can just replace the internal for loop with below code

if (bonusI == i)
{
  letterScore*=bonusMult;
}
  •  Tags:  
  • java
  • Related