prices.java

来自「Java 入门书的源码」· Java 代码 · 共 46 行

JAVA
46
字号
//Copyright (c) 1998, Arthur Gittleman
//This example is provided WITHOUT ANY WARRANTY either expressed or implied.

/* Reads records from a file, each containing an item, a 
 * quantity, and a price.  Computes the total cost of each item,
 * uses a decimal format object to write a double to a file, and
 * a number format object to write in currency fromat to the
 * screen.
 */

import java.io.*;
import java.text.*;
import java.util.StringTokenizer;
public class Prices {
  public static void main(String [] args) {
    String line;
    String item;
    int quantity;
    double price; 
    double cost;
    StringTokenizer strings;
    DecimalFormat df = new DecimalFormat("##0.00");
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    try {
      BufferedReader f = new BufferedReader(new FileReader("prices.data"));
      PrintWriter p = new PrintWriter(new BufferedWriter 
                                     (new FileWriter("totalCost.data")));
      while ((line=f.readLine())!= null){
        strings = new StringTokenizer(line);
        if (strings.countTokens() == 3) {
          item = strings.nextToken();
          quantity = new Integer(strings.nextToken()).intValue();
          price = new Double(strings.nextToken()).doubleValue(); 
          cost = price*quantity; 
          System.out.println("Total cost of "+ item + " is " + nf.format(cost));
          p.print(item + " ");
          p.println(df.format(cost));
        }
      }
      f.close();
      p.close();
    }catch(IOException e) {
       e.printStackTrace();
     }
  }
}    

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?