0

Trying to take data from scanner and pass it to a function that compares that data to an array, but when I send the data that the scanner receives it won't compare.

Scan class

Key.use(scan.nextLine().toString(), retrievedkey);

Key function that iterates through the array to compare the first parameter to the arraylist

public static void use(String door, String[][] key){
        var arraylength = key[1].length;
        for (int i = 0; i<=arraylength;){
            i++;
            if (door == key[1][i]) {
                canOpen = true;
                System.out.println(canOpen);
            }
            else {
                canOpen = false; 
                System.out.println(canOpen + " " + door + " " + Arrays.toString(key[1]));
            }
            return;
        }
        
    }
    
}

When sending data separately from the scan function the key function works. Ex:

Key.use("Front door", retrievedkey)

But the scanner prints the input as "door" yet isn't read by the function. Any help? Thanks.

  • Java uses methods, not functions. Also, that's an array, not ArrayList. – ublec Apr 17 '21 at 03:48
  • The following lines also seem wrong: `var arraylength = key.length; // rows` `for(int i = 0; i < arraylength; i++) {` `if(door.equals(key[0][i])) { // arrays in Java are zero indexed`. – Kaplan Apr 17 '21 at 07:22

1 Answers1

0
            if (door == key[1][i]) {
                canOpen = true;
                System.out.println(canOpen);
            }

You should use

if (door.equals(key[i][1]))

instead of

if (door == key[1][i])

And there is no need to use toString() method in

Key.use(scan.nextLine().toString(), retrievedkey);

since nextLine() reads String as input.

Marivishnu
  • 80
  • 1
  • 7