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); 
        }       
    }   
}
有帮助吗?

解决方案

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.

其他提示

Keep in mind charAt is zero-indexed.

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top