【问题标题】:Why do I get an error unless I ask for the same input twice? (Java)除非我两次要求相同的输入,否则为什么会出现错误? (爪哇)
【发布时间】:2013-08-25 22:42:14
【问题描述】:

我运行的程序只有一个quit = input.nextLine();,但这会导致错误。但是,如果我两次使用该行,则不会发生错误,并且程序按预期运行。 为什么?

错误信息:Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.String.charAt(String.java:686) at testjava.Test.main(Testjava.java:24)

    import java.util.Scanner;

    public class Test
    {
        public static void main(String[] args)
        {
            boolean x = true;
            boolean y = true;
            Scanner input = new Scanner(System.in);

            while (x) {
                while (y) {
                    System.out.print("Enter -1 to quit ");
                    int val = input.nextInt();
                    if (val == -1)
                        y = false;
                }  

                System.out.print("Are you sure you want to quit? (y/n) ");
                String quit = input.nextLine();
                quit = input.nextLine();

                if (quit.charAt(0) == 'y')
                    x = false;                  
            }
        }

【问题讨论】:

  • 你最好把你得到的什么错误写进去。
  • 你是对的。另一个错误不包括该错误。

标签: java input while-loop conditional


【解决方案1】:

你应该使用 input.next()。

input.nextLine() 跳过当前行并输出被跳过的行。

【讨论】:

  • 就是这样!谢谢你。几天前我才开始学习java。我会尽快标记。
【解决方案2】:

我的猜测是您输入的数字相当 (-1) 没有得到仅由您的第一个 nextLine() 抓取的行尾字符

我认为你应该得到数字的整行然后解析 int:

 System.out.print("Enter -1 to quit ");
 String line = input.nextLine();
 int val = Integer.parseInt(line);

 ...

【讨论】:

    【解决方案3】:

    来自Scanner#nextLine()

    将此扫描器前进到当前行并返回被跳过的输入。此方法返回当前行的其余部分, 不包括末尾的任何行分隔符。位置设置为 下一行的开头。

    当您只使用一个.nextLine() 时,扫描仪会跳过当前行。而且您的输入永远不会被读取。结果quit 变为""。而你的下一个代码行抛出异常。

    if (quit.charAt(0) == 'y')
    

    按照@UpAllNight 的建议使用:.next()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-30
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      • 2012-12-26
      • 2011-08-18
      相关资源
      最近更新 更多