为什么updateStocks()没有改变价格?

时间:2017-03-17 06:51:33

标签: java

我有一种使用Scanner和delimiter读取五种股票的文本文件的方法。我还有一个方法,它应该采用双倍乘数和一组库存对象,并用该乘数改变价格。读取库存文件的方法正常运行,但是,当我尝试使用文件阅读方法更改已分配值的库存对象时,它不会更改价格。在我使用方法updateStocks()之后,我测试stock [1]以查看该值是否已更改且未更改。

我跑完后:

public class Main {

    public static void main (String args[]) {
        // stock object with which to call methods
        Stock theStock = new Stock("", "", 0);
        // this array holds the stocks to be read
        Stock[] stocks = new Stock[100];
        // here is the multiplier I am attempting to use
        double multiplier = 1/3;
        // first I read in the stocks file
        theStock.readStocksWithScanner(stocks);
        // then I call the updateStockPrices method
        theStock.updateStockPrices(multiplier,stocks);
        // lastly, I test to see if the method has functioned correctly
        System.out.println(stocks[1]);

    }
}




This is my output:
Apple      AAPLE        152.70
Alphabet  GOOGLE        873.96
IBM          IBM        194.37
Microsoft   MSFT        65.67
Oracle     ORCLE        62.82
Company name: Apple Stock symbol: AAPLE Stock Price: 152.7
Press any key to continue . . .

这是方法updateStockPrices:

// this is the method which does not seem to function as intended
    public void updateStockPrices(double multiplier, Stock[] objects)
    {

        // I loop to the length of the array in the parameter
        for(int i = 1; i < objects.length; i++)
        {
                // try to manipulate the stock
                try{
                    double subtractThis = stocks[i].getPrice() * multiplier;
                    objects[i].setPrice(stocks[i].getPrice() - subtractThis);

                    }// and catch any null objects
                    catch(NullPointerException e){
                        // if null I then increment the counter
                        i++;}
                    // Is code missing in order for this to function as intended? or have I made a mistake?


        }
    }

这里是stocks.java:

import java.util.Scanner ;
 import java.util.InputMismatchException ;  
 import java.io.FileInputStream ;
 import java.io.IOException ;
 import java.io.FileNotFoundException ;
 import java.io.PrintWriter ;
public class Stock {
    private static final double MULTIPLIER = (1/3);
    public static final String FILE_NAME = "stocks1.txt";
    public String newFile = "stocks2.txt";
    public static final String FORMAT = "%-10s%6s\t%.2f%n";
    private PrintWriter writer = null;
    private String name = "";
    private String symbol = ""; 
    private double price = 0;
    protected Stock stocks[] = new Stock[100];

        FileInputStream inputStream = null;
        String workingDirectory = System.getProperty("user.dir");
        String absolutePath = workingDirectory + "\\" + FILE_NAME;
   public Stock(String aName, String aSymbol, double aPrice)
    {
        this.name = aName;
        this.symbol = aSymbol;
        this.price = aPrice;
    }
    // the fileReading method reads the stocks in
    public void readStocksWithScanner(Stock[] stocks)
    {
        this.stocks = stocks;

        String workingDirectory = System.getProperty("user.dir");
        String absolutePath = workingDirectory + "\\" + FILE_NAME;

        FileInputStream inputStream = null;

try{
    inputStream = new FileInputStream(absolutePath);
    }
    catch (FileNotFoundException e)
    {
        System.out.println("File not found: " + FILE_NAME);
        System.out.println("Exiting program.");
        System.exit(0) ;
    }
    Scanner inputFile = new Scanner(inputStream);
    int lineNumber = 1;
    try{
        while(inputFile.hasNextLine())
        {
            inputFile.useDelimiter(",");
            String name = inputFile.next();
            inputFile.useDelimiter(",");
            String symbol = inputFile.next();
            inputFile.useDelimiter("[,\\s]") ;
            Double thePrice = inputFile.nextDouble();
            inputFile.nextLine();
            // here the stocks are given the values found in the text file and initialized above
            stocks[lineNumber] = new Stock(name, symbol, thePrice);
            // I print them out using a format constant, in order to ensure the method has functioned correcly
            System.out.printf(FORMAT, name, symbol, thePrice);
            // then I increment the lineNumber 
            lineNumber++;
        }
        // I close the stream and should be left with a partially filled array of stock items
        inputStream.close();
    }catch (IOException e) {
            System.out.println("Error reading line " + lineNumber + " from file " + FILE_NAME) ;
            System.exit(0) ;
        }
        catch(InputMismatchException e) {
            System.out.println("Couldn't convert price to a number on line " + lineNumber) ;
            System.exit(0) ;}

        }



    public void setName(String name)
    {
        this.name = name;
    }
    public void setSymbol(String symbol)
    {
        this.symbol = symbol;
    }
    public void setPrice(double aPrice)
    {
        this.price = aPrice;
    }
    public String getName()
    {
        return name;
    }
    public String getSymbol()
    {
        return symbol;
    }
    public double getPrice()
    {
        return price;
    }
    public boolean equals(Object other)
    {
        if(other.getClass() != getClass() || other == null )
        {
            return false;
        }
        Stock stock = (Stock) other;
        {
            if(stock.getName() == getName() && stock.getSymbol() == getSymbol() && stock.getPrice() == getPrice())
            {
                return true;
            }
            return false;
        }

    }
    public String toString()
    {
        return "Company name: " + getName() + " Stock symbol: " + getSymbol() + " Stock Price: " + getPrice();
    }
    // this is the method which does not seem to function as intended
    public void updateStockPrices(double multiplier, Stock[] objects)
    {

        // I loop to the length of the array in the parameter
        for(int i = 1; i < objects.length; i++)
        {
                // try to manipulate the stock
                try{
                    double subtractThis = stocks[i].getPrice() * multiplier;
                    objects[i].setPrice(stocks[i].getPrice() - subtractThis);

                    }// and catch any null objects
                    catch(NullPointerException e){
                        // if null I then increment the counter
                        i++;}
                    // Is code missing in order for this to function as intended? or have I made a mistake?


        }
    }










    public void createStocks(int stockAmount)
    {
        Stock[] stocks = new Stock[stockAmount];
    }
    public void writeStocks(String fileName, Stock[] objects)
    {

        try{
            writer = new PrintWriter(fileName);
        }
        catch(FileNotFoundException e){
            System.out.println("Couldn't create file " + fileName);
            System.exit(0);
        }
        for(Stock s: objects)
        {

            writer.printf(FORMAT, getName(), getSymbol(), getPrice());
            if(objects == null)
            writer.close() ;
        }
    }
    public Stock[] getStocks()
    {
        return stocks;
    }

}

1 个答案:

答案 0 :(得分:1)

简单测试

    double multiplier = 1/3;
    System.out.println(multiplier);

相比
    double multiplier = 1/3f;
    System.out.println(multiplier);