charAt()问题

时间:2013-10-08 07:13:29

标签: java nosuchelementexception

我正在编写一个程序,它从一个从命令行重定向的文本文件中解码一个秘密消息。第一行是关键短语,第二行是一组索引关键短语的整数。我试图使用charAt()方法,但我不断收到这样的元素异常错误消息。

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

2 个答案:

答案 0 :(得分:1)

请注意,当您执行int numbers = keyboard.nextInt();时,它只会读取int值(并跳过\n,这是您之后按下的回车键) - 请参阅Scanner#nextInt

因此,当您继续使用keyboard.nextLine()阅读时,您会收到\n

您可以添加其他keyboard.nextLine(),以便从\n读取已跳过的nextInt()

您获得的例外情况是因为您尝试在charAt上使用\n

答案 1 :(得分:0)

请注意,charAt为零索引。

e.g。如果键入“test”,然后键入“3”,则输出应为“t”。