2012-09-27 34 views
0

我到目前为止的代码变量分配到一个文本文件中的行的Java文件是:如何通过线

public class Project4 { 

    public static void main (String[] args) throws IOException { 

     final double OUNCES_PER_POUND = 16.0; 
     double pricePerPound; 
     double weightOunces; 
     double weightPounds; 
     double totalPrice; 
     String itemName; 

     Scanner fileScan = new Scanner(new File(args[0])); 

     NumberFormat money = NumberFormat.getCurrencyInstance(); 
     DecimalFormat fmt = new DecimalFormat("0.00"); 

     // Missing code that reads variables from text file goes here 

     weightPounds = weightOunces/OUNCES_PER_POUND; 
     totalPrice = weightPounds * pricePerPound; 


     System.out.println("Item: " + itemName); 
     System.out.println("Unit Price: " + money.format(pricePerPound)); 
     System.out.println("Weight: " + fmt.format(weightPounds) + " pounds"); 
     System.out.println("TOTAL: " + money.format(totalPrice)); 
    } 

} 

我试图做的是弄清楚如何从拉变量文本文件。该文件必须在命令行中声明为参数,这就是为什么标题按原样设置的原因。文本文件基本上是我需要的三个变量,每个都在一个单独的行上。

我希望有人给我一个提示,或者指点一下我需要做些什么来设置变量,以便我可以从文本文件中声明每行,因为它是自己单独的变量。

+1

看看 http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html –

+0

这是有用的信息,我谢谢你,但我不因为第一行有空白区域,所以认为它对我有用。如果我知道每次使用相同数量的单词并将它们分组时,我实际上可以使用此方法,但我希望能够让代码将所有内容都拉出来。 – User2

+0

你不能只是使用for-loop和http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html#nextLine将整个文件解析为字符串数组)?那么你可以从那里解析字符串数组? –

回答

1

如果变量出现在最简单的格式可能,例如此链接:

3.5 
5.2 
My Item 

,那么你可以在值与阅读:

weightOunces = fileScan.nextDouble(); 
fileScan.nextLine(); 
weightPounds = fileScan.nextDouble(); 
fileScan.nextLine(); 
itemName = fileScan.nextLine(); 

fileScan.nextLine()之后需要nextDouble()语句消耗换行符。

+0

优秀信息,谢谢! – User2