문제

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