编程语言
首页 > 编程语言> > 我的java for循环跳过了一步

我的java for循环跳过了一步

作者:互联网

我正在技术学院的课程中编写练习申请.应该实例化Book类的5个对象,该类包含有关书名,作者和页数的数据字段.我在for ..循环时遇到问题.第一次循环后,它每次都会跳过一个步骤,我无法弄清原因.这是我的代码

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的新手,所以对您的帮助表示赞赏.
提前致谢.

解决方法:

像这样更改代码:

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,而不是整数.

标签:java-util-scanner,loops,for-loop,java
来源: https://codeday.me/bug/20191201/2079945.html