2016-04-12 152 views
0

請幫忙,我試圖根據從輸入文件中讀取的數量來計算書籍總數。我試圖計算書的總數,但現在我的代碼只是產生它從文件中讀取的最後一個數量,作爲totalBooks的總數。我不確定我做錯了什麼,但任何指導都將不勝感激。Java總計書籍計算

這是我有...

注:我的節目,我試圖解決的部分是在評論//計算總書

import java.util.Scanner; 
import java.io.File; 
import java.io.IOException; 

public class BookstoreInventory 
{ 
public static void main(String[] args)throws IOException 
{ 
//Vaiable declartions 
int edition, quanity; 
double pricePerBook; 
String isbn, author, title, publisherCode; 

//Open the file and set delimiters 
File file = new File("inventory.txt"); 
Scanner inputFile = new Scanner(file); 
inputFile.useDelimiter("_|/|\\r?\\n"); 

//read from the file 
while (inputFile.hasNext()) 
{ 
    isbn = inputFile.next(); 
    System.out.println(formatISBN(isbn)); //Need to move at end 
    author = inputFile.next(); 
    System.out.println(getLastName(author)); //need to remove at end 
    title = inputFile.next(); 
    System.out.println(truncateTitle(title)); //need to remove at end 
    edition = inputFile.nextInt(); 
    System.out.println(edition(edition)); //need to remove at end 
    publisherCode = inputFile.next(); 
    System.out.println(publisher(publisherCode)); //need to remove at end 
    quanity = inputFile.nextInt(); 
    System.out.println(quanity);  //need to remove at end 
    pricePerBook = inputFile.nextDouble(); 
    System.out.println("$" + pricePerBook); //need to remove at end 

    //Calculate Total Books 
    int totalBooks = 0; 
    totalBooks += quanity; 
    System.out.println("Total books: " + totalBooks); 
} 

//Close the flie 
inputFile.close(); 
} 

回答

0

您需要使用quantity+= inputFile.nextInt();

您必須計算總量,因此您需要通過添加下一個數量來更新以前的數量,而不用替代