Question

My goal is to read in a text file and add each element to a simple array (the elements are separated by a comma). The last method readData() is the one I can't figure out.

My code so far :

public class VersionChooser {

private Scanner scan;
private StockManager aManager = new StockManager("StockManager");

public VersionChooser() {
    this.scan = new Scanner(System.in);
}

public void chooseVersion() {
    this.readData();
    this.runTextOption();
}

private void runTextOption() {
    StockTUI tui = new StockTUI(this.aManager);
}

public StockManager readData() {
    String fileName;
    System.out.println("Enter the name of the file to be used");
    fileName = this.scan.nextLine();
    System.out.println(fileName);
    try (final BufferedReader br = Files.newBufferedReader(new File("fileName").toPath(),
            StandardCharsets.UTF_16)) {
        for (String line; (line = br.readLine()) != null;) {
            final String[] data = line.split(","); 
            StockRecord record = new StockRecord(data[0], Double.valueOf(data[4])); 
            this.aManager.getStockList().add(record);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }   


    return null;
}
}

StockRecord :

public class StockRecord {
private String date;
private double closingPrice;

public StockRecord(String date, double closingPrice) {
    this.date = date;
    this.closingPrice = closingPrice;
}

public String getDate() {
    return this.date;
}

public double getClosingPrice() {
    return this.closingPrice;
}
public String toString() {
    return "On " + this.date + " this stock had a closing price of $" 
            + this.closingPrice;
}
}
Was it helpful?

Solution

Step1 : Read the file line by line.

Step2: Split the line by ","

Step3 : Construct the String[] to StockRecord.

try (final BufferedReader br = Files.newBufferedReader(new File("stock.txt").toPath(),
            StandardCharsets.UTF_8)) {
        List<StockRecord> stocks = new ArrayList<StockRecord>();
                    br.readLine() ; // to avoid first line
        for (String line; (line = br.readLine()) != null;) { // first step
            final String[] data = line.split(",");       // second step
            StockRecord record = new StockRecord(data[0], Double.valueOf(data[1]));
            stocks.add(record);    // third step
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

Your stockRecord doesn't has all records. and for demo purpose i did assumed 2 element is closing price . change accordingly

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top