我的java for loop跳过了一个步骤



我正在为我在技术学院做的课程中的练习编写一个应用程序。它应该实例化类Book的5个对象,其中包含一本书标题,作者和页数的数据字段。我在for.. loop时遇到问题。每次在第一个循环之后它都会跳过一个步骤,我不知道为什么。这是我的代码

import java.util.*;
public class LibraryBook2
{
    public static void main(String[]args)
{
    String name;
    String author;
    int pages;
    Book[] novel = new Book[5];
    novel[0] = new Book();
    novel[1] = new Book();
    novel[2] = new Book();
    novel[3] = new Book();
    novel[4] = new Book();
    Scanner kb = new Scanner(System.in);
    for (int i = 0; i< novel.length;)
    {   
        System.out.println("Please Enter the books title");
        name = kb.nextLine();
        novel[i].setTitle(name);
        System.out.println("Please enter the books author");
        author = kb.nextLine();
        novel[i].setAuthor(author);
        System.out.println("Please enter the number of pages in this book");
        pages = kb.nextInt();
        novel[i].setPages(pages);
        System.out.println(""+novel[i].title);
        System.out.println(""+novel[i].author);
        System.out.println(""+novel[i].pages);
        ++i;
    }
    for (int x = 0; x<novel.length; x++)
    {
    System.out.print(""+ novel[x].title + "n" + novel[x].author + "n" + novel[x].pages);
    }
  }
}

在第一个for循环中,它会循环一次,打印书名、作者和我输入的页数,就像它应该的那样。但是第二次,它打印"请输入书名",然后直接跳到第二个println,无需等待输入。我是对象数组和一般 Java 的新手,因此非常感谢任何帮助。提前谢谢。

让我猜猜,你输入的是"13"作为页数,对吧?

您使用程序错误。不要在书中的页数之后按回车键。立即键入下一本书的标题,没有空格或任何内容。代码读取一个整数,然后读取标题的一行。因此,您不能在整数和标题之间放置任何内容,因为这不是代码所期望的。

这使得程序非常难以使用,因为在您输入标题后会出现输入标题的提示。这是编写程序的一种非常愚蠢的方式,你不觉得吗?

一个简单的解决方法:kb.nextInt后,调用kb.nextLine并扔掉空行。

这一行:

name = kb.nextLine();
读取尽可能多的字符,

直到找到换行符,然后读取该字符。而这一行:

pages = kb.nextInt();

以数字字符序列读取,但保留换行符不变。

下次你遍历循环时,有一个尚未阅读的新行字符挂在周围。因此,kb.nextLine() 尽职尽责地读取该字符(即使它之前没有字符)并继续。

您可能想要做的是确保在下一个循环之前,这个额外的换行符从输入缓冲区中消失。

像这样更改代码:

public static void main(String []arg){
    String name;
    String author;
    String pages;
    Book[] novel = new Book[2];
    novel[0] = new Book();
    novel[1] = new Book();
    novel[2] = new Book();
    novel[3] = new Book();
    novel[4] = new Book();
    Scanner kb = new Scanner(System.in);
    for (int i = 0; i< novel.length;)
    {   
        System.out.println("Please Enter the books title");
        name = kb.nextLine();
        novel[i].setTitle(name);
        System.out.println("Please enter the books author");
        author = kb.nextLine();
        novel[i].setAuthor(author);
        System.out.println("Please enter the number of pages in this book");
        pages = kb.nextLine();
        novel[i].setPages(Integer.parseInt(pages));
        System.out.println(""+novel[i].title);
        System.out.println(""+novel[i].author);
        System.out.println(""+novel[i].getPages());
        ++i;
    }
    for (int x = 0; x<novel.length; x++)
    {
    System.out.print(""+ novel[x].title + "n" + novel[x].author + "n" + novel[x].pages);
    }

将页码读取为 nextLine,而不是整数。

最新更新