繁体   English   中英

为什么我的for循环中的提示第一次打印两次?

[英]Why is the prompt in my for loop printing twice the first time?

我的for循环中的第一个print语句打印两次,然后再转到下一行。 但是之后它会像之后那样贯穿循环?

我尝试使用我的调试器,但我以前从未使用它,我们没有在我的任何课程中使用它,我不太确定我在做什么

public static void main(String[] args) 
{
    int numElements;

    Scanner keyboard = new Scanner(System.in);

    System.out.println("How many people are you adding: ");
    numElements = keyboard.nextInt();
    ArrayBndQueue queue = new ArrayBndQueue<>(numElements + 1);

    for(int index =0; index <= numElements; index++)
    {
        System.out.println("Enter a gender and name (ex: f jenny)");
        String name = keyboard.nextLine();
        System.out.println(name);
        queue.enqueue(name);

    }

}  

你有一个所谓的一个一个错误 许多语言的基础之一是它们在索引时是零基础的。 你有一半的权利,你有一个错误(实际上是两个),而不是修复该错误,你只修复了症状....

关闭一个bug

这个bug在你的for循环中:

for(int index =0; index <= numElements; index++)

如果循环次数过多......在测试条件下应该使用<而不是<= 这样你就会循环numElements次。

您没有修复它,而是使队列1元素太大,因此您应该更改:

ArrayBndQueue queue = new ArrayBndQueue<>(numElements + 1);

成为:

ArrayBndQueue queue = new ArrayBndQueue<>(numElements);

这应该排除额外的循环,你仍然有值的空间。

扫描仪管理错误

Scanner.nextInt()仅从扫描器中提取int值,而不是终止换行符/回车符,因此当您在循环中调用nextLine() ,它会清除扫描器中已有的行,而不是等待输入。

您需要清除扫描仪中的行,然后在nextInt()调用之后前进:

numElements = keyboard.nextInt();
keyboard.nextLine();

这应该清除您的扫描仪下一个输入。

文档

nextInt() - 将输入的下一个标记扫描为int。 如果下一个标记无法转换为有效的int值,则此方法将抛出InputMismatchException,如下所述。 如果翻译成功,扫描仪将超过匹配的输入。

“超过匹配的输入”意味着换行/回车之前

最好的解决方法是简单地从scanner方法中删除elementType。 通过这样做,可以防止循环的第一个实例清除输入,如上面的rolfl提到的那样。 修改后的代码如下:

for(int index =0; index <= numElements; index++)
{
    System.out.println("Enter a gender and name (ex: f jenny)");
    //removed "Line" from ".nextLine" to prevent clearing below       
    String name = keyboard.next();
    System.out.println(name);
    queue.enqueue(name);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM