Question

I'm writing a program that decodes a secret message from a text file that is redirected from the command line. First line is a key phrase and the second is a set of integers that index the key phrase. I am trying to use the charAt() method but I keep getting a no such element exception error message.

public class Decoder 
{
    public static void main(String[] args) 
    {
        Scanner keyboard = new Scanner(System.in);

        while (keyboard.hasNext())
        {
           String phrase = keyboard.nextLine();
           int numbers = keyboard.nextInt();
           char results = phrase.charAt(numbers); 
               System.out.print(results); 
        }       
    }   
}
Was it helpful?

Solution

Note that when you do int numbers = keyboard.nextInt();, it reads only the int value (and skips the \n which is the enter key you press right after) - See Scanner#nextInt.

So when you continue reading with keyboard.nextLine() you receive the \n.

You can add another keyboard.nextLine() in order to read the skipped \n from nextInt().

The exception you're getting is because you're trying to use charAt on \n.

OTHER TIPS

Keep in mind charAt is zero-indexed.

e.g. If you type "test", and then "3", the output should be "t".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top