2017-03-17 2 views
-1

Ich habe eine Methode, um eine Textdatei von fünf Aktien mit Scanner und Trennzeichen zu lesen. Ich habe auch eine Methode, die einen doppelten Multiplikator und ein Array von Lagerobjekten nehmen und den Preis mit diesem Multiplikator ändern sollte. Die Methode, die die Bestandsdatei liest, funktioniert jedoch richtig, wenn ich versuche, die Bestandsobjekte zu ändern, denen Werte mit der Methode file reading zugewiesen wurden, ändert sich der Preis nicht. Nachdem ich die Methode updateStocks() verwendet habe, teste ich den Bestand [1], um zu sehen, ob sich der Wert geändert hat und was nicht.Warum ändert updateStocks() den Preis nicht?

Nachdem ich laufen diese:

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 . . . 

hier die Methode updateStockPrices ist:

// 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? 


     } 
    } 

und hier ist 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

Ich bin gerade dabei zu beachten, die 'catch (Nullpointer)' Sie lieber mit einem 'list' hier statt der Schaffung eines Käses wie' array' enthält Instanzen von 'arbeiten sollten Stock' und 'null'. – SomeJavaGuy

+0

Ich kann die Liste noch nicht verwenden, aber ich werde dies für zukünftige Aufgaben notieren, wenn ich List verwenden kann ... Ich habe gehört, List macht den Umgang mit Arrays viel einfacher – mark1092

Antwort

1

einfachen Test

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

im Vergleich zu

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

und das war unerwartet einfach ... Wo kann ich den Grund finden, dass das f benötigt wird? Ich würde gerne lernen, so dass ich diesen Fehler nicht wiederholen – mark1092

+0

Suche nach Ganzzahl Division –

+0

Da unsuffixed Fließkomma-Literale Doppel sind, so müssen Sie f angeben. –

Verwandte Themen