Search code examples
javanosuchelementexception

charAt() issues


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); 
        }       
    }   
}

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.