2017-03-17 85 views
-1

我有一種方法可以使用掃描器和分隔符來讀取五種股票的文本文件。我也有一種方法,它應該採用雙乘法器和一系列庫存對象,並用該乘數來改變價格。讀取庫存文件的方法正常工作,但是,當我試圖通過文件讀取方法更改已分配值的庫存對象時,它不會更改價格。在我使用方法updateStocks()之後,我測試了股票[1],看看這個值是否已經改變,但沒有。爲什麼updateStocks()不改變價格?

後,我運行此:

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; 
    } 

} 
+0

i'm只是要注意,'抓(空指針異常)',你倒是應該用'List'在這裏工作,而不是創造一個像'包含的實例array'奶酪的' Stock'和'null'。 – SomeJavaGuy

+0

我目前還不能使用List,但是當我能夠使用List的時候,我會記錄下這些內容......我聽說List使得處理數組更容易 – mark1092

回答

1

簡單的測試

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

相比

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

好得出乎意料...我在哪裏可以找到f是必需的原因?我想學習以便我不重複這個錯誤 – mark1092

+0

搜索整數除法 –

+0

因爲沒有添加的浮點文字是雙精度的,所以您必須指定f。 –