具有最低和最高价格的产品(从文本文件中读取数据)

时间:2014-04-13 10:14:46

标签: java arrays io inputstream filestream

输入文件: 糖; 1.2; 30

乳; 4.5; 100

粒; 3.2; 200

在输出文件中,我必须以最低和最高价格(牛奶和糖)打印产品 我的程序以最高价格打印产品,但是以最低价格打印谷物。

主要课程:

public class Lab3 
{ 
    public static void main (String[ ] args) throws IOException
    { 
        double max=0, min=10000000;

        Product p_min=new Product("",0.0,0);
        Product p_max=new Product("",0.0,0);
        BufferedReader in=new BufferedReader (new InputStreamReader(new      FileInputStream("C:\\Users\\Timotei\\Desktop\\in.txt")));
        PrintStream out=new PrintStream(new  FileOutputStream("C://Users//Timotei//Desktop//out.txt"));
        String line;          
        while((line=in.readLine())!=null)
        {

            String[] array=line.split(";");
            String name=array[0];
            double price=Double.valueOf(array[1]);
            int quantity=Integer.valueOf(array[2]);
            if(price>max)
            {
                max=price;
                p_max=new Product(name,price,quantity); 
            }
            if(price<min)
            {
                min=price;
                p_min=new Product(name,price,quantity);
            }
        }
        out.println("Product with maximum price is:"+p_max);
        System.out.println("Product with maximum price is:"+p_max); 
        System.out.println("Product with minimum price is:"+p_min);
        out.println("Product with minimum price is:"+p_min);
        in.close();
        out.close();
    }
}

产品类别:

public class Product 
{
    private String name;
    private double price;
    private int quantity;     
    public Product(String name, double price, int quantity)
    {
        this.name=name;
        this.price=price;
        this.quantity=quantity;
    }
    public Product(Product p)
    {
        p.name=name;
        p.price=price;
        p.quantity=quantity;
    }
    public String toString()
    {
        return name+" which has the price "+price+" and is present in a quantity of "+quantity;
    }
}

1 个答案:

答案 0 :(得分:0)

你应该替换它:

if(price<max)
    min=price;

通过

if(price<min)
    min=price;