Home > Software design >  Scan 2 Strings and give points for each right char
Scan 2 Strings and give points for each right char

Time:06-04

String[] ergebnisse = {"Err", "Baum", "Schule", "Pferd", "Maschine"};
String eingabe = textField1.getText();
int[] punkte = new int[ergebnisse.length];

for (int w = 0; w < ergebnisse.length; w  ) {
      for (int b = 0; b < ergebnisse[w].length(); b  ) {
        if (ergebnisse[w].charAt(b) == eingabe.charAt(b)) {
          punkte[w]  ;   
        }
      }
    }

Error Oud of Bounds only apears in the if case on the second run. if i replace if(ergebnisse[w].charAt(b)) == eingabe.charAt(X)) it works but only for thr one caracter.

CodePudding user response:

Let's say you input "Pferd".

Your code runs once for each ergebnisse, so eventually it gets to Schule.

schule's length is 6, of course. So that for (int b ) loop is going to run 6 times. Unfortunately, you're going to run into real issues on that 6th run (where b is 5): eingabe.charAt(5) - that does not work - there is no 6th character in eingabe, as eingabe has only 5 letters in it.

The fix is to deal with that. You can't switch it up and change the loop to for (int b = 0; b < eingabe.length(); b ) either - what if the eingabe is longer than one of the ergebnisse?

You could go by whichever one is smaller:

for (int b = 0; i < Math.min(eingabe.length(), ergebnisse[w].length()); b  )`

You could also simply 'detect' this is pick some action:

if (b < eingabe.length() && ergebnisse[w].charAt(b) == eingabe.charAt(b)) {

for example.

You need to pick one of the two to 'scan length'

  • Related