GoldShovel
GoldShovel

Reputation: 35

Why is this code returning -1?

I have some code and line 33 is returning -1 because it could not find the value. But why is it not finding it?! I think it might have something to do with char[] but I'm really not too sure here.

It could also be because of line 31 (int temp) but I really don't know.

import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;

class Main {

public static void main(String args[]) {

HashMap<Integer, String> map = new HashMap<Integer, String>();

System.out.println("Enter your string to cipher: ");

Scanner s =  new Scanner(System.in);
String str = s.nextLine();

char[] letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
Integer[] numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25};

if (str instanceof String) {
    System.out.println("Input received: OK.");
} else {
    System.out.println("Error! You cannot input numbers. Exiting program...");
    System.exit(1);
}

for (int i = 0; i < str.length(); i++) {
    char l = str.charAt(i);

    System.out.println(l);

    int temp = Arrays.asList(letters).indexOf(l);

    System.out.println(temp);


    }


  }

}

Upvotes: 0

Views: 80

Answers (1)

Fminus
Fminus

Reputation: 61

Change the type of the variable 'letters' to Character[] and it'll work.

Bonus small optimization advice: move this line int temp = Arrays.asList(letters).indexOf(l) outside the loop, as it is you are creating a list on every iteration.

Also decide if you want to use generic collections using Arrays or arrays like char[] etc.

Upvotes: 1

Related Questions