-4

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); 
        }       
    }   
}
Maroun
  • 94,125
  • 30
  • 188
  • 241

2 Answers2

1

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.

Maroun
  • 94,125
  • 30
  • 188
  • 241
0

Keep in mind charAt is zero-indexed.

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

Georgian
  • 8,795
  • 8
  • 46
  • 87
  • Line 1= five hexing wizard bots jump quickly Line 2= 21 5 6 11 15 9 10 3 34 22 28 5 15 2 3 4 21 5 3 18 27 5 20 9 6 23 19 20 7 here is the text file it is being read from. I want to get each int and use the charAt to reference the first line and output what that character is to form the message. – Corey Crawford Oct 08 '13 at 07:20
  • Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:907) at java.util.Scanner.next(Scanner.java:1530) at java.util.Scanner.nextInt(Scanner.java:2160) at java.util.Scanner.nextInt(Scanner.java:2119) at Decoder.main(Decoder.java:22) These are the messages i keep getting. – Corey Crawford Oct 08 '13 at 07:20