2012-05-16 17 views
3

我正在寫一個練習的應用程序,我正在做科技課程。它應該實例化類別Book的5個對象,其中包含書籍標題,作者和頁數的數據字段。我遇到for.. loop問題。它在第一次循環後每次跳過一步,我無法弄清楚原因。這裏是我的代碼我的Java 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,所以任何幫助表示讚賞。 在此先感謝。

回答

0

改變這樣的代碼:

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。

+0

謝謝你,你的回答是我實施的。我感謝所有幫助過的人。 –

+0

歡呼@StevenAyerst !!! – UVM

2

讓我猜,你正在輸入的東西,如「13 <輸入>」的頁數,對吧?

您正在使用該程序錯誤。請勿在本書中的頁數之後按回車鍵。立即鍵入下一本書的標題,不要有空格或任何東西。該代碼讀取一個整數,然後爲標題讀取一行。所以你不能把什麼之間的整數和標題,因爲這不是代碼的預期。

這使得程序非常難以使用,因爲輸入標題的提示將在您輸入標題後出現。這是寫程序的一種非常愚蠢的方式,你不覺得嗎?

一個簡單的修復:在kb.nextInt之後,請撥kb.nextLine並將空行丟棄。

1

這條線:

name = kb.nextLine(); 

,直到它找到一個新行字符閱讀儘可能多的字符就可以了,然後在文字閱讀爲好。而這條線:

pages = kb.nextInt(); 

正在讀取的個數字符的序列,但保留新行字符不變。

下次你經過這個循環時,會有一個新的行字符掛在其中還沒有被讀取。因此,kb.nextLine()忠實地讀取該字符(即使在它之前沒有字符)並繼續。

你可能想要做的就是確保這個額外的換行符在輸入緩衝區之前從開始,然後再循環。