java for next_我的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

{

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

{

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值