我是靠谱客的博主 纯情乌冬面,最近开发中收集的这篇文章主要介绍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

最后

以上就是纯情乌冬面为你收集整理的java for next_我的java for循环跳过了一步的全部内容,希望文章能够帮你解决java for next_我的java for循环跳过了一步所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(61)

评论列表共有 0 条评论

立即
投稿
返回
顶部