2014-10-22 43 views
1

因此,对于一个任务,我必须从文件读取输入,然后输出它。 该文件中的信息采用以下格式:1行包含股票代码,下一行包含购买的数量。 如文件,我们会使用:当从一个文件读取输入时,文件中的所有行都不是用Java读取的?

.ab 
15 
mox 
16 
.fy 
8 
mixe 
34 

然后,我要输出的数量和每个符号的总价格。 但不知何故,当我运行它时,它只读取前三组数据 - 在这个例子中只有3行数据而不是4。 例如。输出将是:

Enter filename ... lab5data.txt 
00000 54.05 
00002 Symbol mox does not exist 
00003 10.70 
00004 Symbol mixe does not exist 

我的代码将无法输出的最后一行“00004符号mixe不存在”

这是我的代码:

import java.util.Scanner; 
import java.io.PrintStream; 
import type.lib.Stock; 
import java.io.File; 
import java.text.DecimalFormat; 
public class Check05B 
{ 
    public static void main(String[] args) throws java.io.IOException 
    { 
     Scanner input = new Scanner(System.in); 
     PrintStream output = new PrintStream(System.out); 
     output.print("Enter filename ... "); 
     String fileName = input.nextLine(); 
     Scanner fileInput = new Scanner(new File(fileName)); 
     double totalValue = 0; 
     int count = 00000; 
     String symbol = fileInput.next(); 
     int quantity = fileInput.nextInt(); 
     while (fileInput.hasNext()) 
     { 
      Stock myStock = new Stock(symbol); 
      double total = myStock.getPrice() * quantity; 
      String aFormatCounter = new DecimalFormat("00000").format(count); 
      if (myStock.getName() == null) 
      output.println(aFormatCounter + " Symbol " + symbol + " does not exist!"); 
      else 
      output.printf("%s %.2f%n", aFormatCounter, myStock.getPrice()); 
      totalValue += total; 
      symbol = fileInput.next(); 
      count++; 
      quantity = fileInput.nextInt(); 
      count++; 
     } 
     output.printf("Total value = %.2f%n", totalValue); 
     fileInput.close(); 
    } 
} 

有谁请帮助?我怎样才能让它读取所有的行?谢谢!!

+0

你需要包括在你的问题了'Stock'类的代码。 – EJP 2014-10-22 00:07:53

回答

2

您需要读取symbolquantity循环的顶部。

考虑

while (fileInput.hasNext()) 
    { 
     String symbol = fileInput.next(); 
     if (fileInput.hasNextInt() == false) { 
      System.err.println ("File Format Error - expecting an int"); 
      break; 
     }  
     int quantity = fileInput.nextInt(); 
     Stock myStock = new Stock(symbol); 
     double total = myStock.getPrice() * quantity; 
     String aFormatCounter = new DecimalFormat("00000").format(count); 
     if (myStock.getName() == null) { 
      output.println(aFormatCounter + " Symbol " + symbol + " does not exist!"); 
     } 
     else { 
      output.printf("%s %.2f%n", aFormatCounter, myStock.getPrice()); 
     } 
     totalValue += total; 
     count = count + 2; 
    } 
+0

是的,解决了它!非常感谢!! :) 我会“竖起大拇指”您的帖子,但我没有足够的声望点呢!再次感谢!! – RYS221 2014-10-22 00:26:37

+0

你会考虑一个类似'while(hasNext){if(hasNextInt){...'或者只是大量挑剔并且超出问题范围的东西)的双重检查吗? – MadProgrammer 2014-10-22 00:37:52

+0

@MadProgrammer'not nit挑剔的,但超出了问题的范围。但是,我会加上它。 – 2014-10-22 00:40:03