-1

I have a text file containing 15 lines with 3 different Computers with their manufacturer, model, processor, Ram and price. I have this code to read the text file via URL:

    URL file_url = new URL(urlfile);
    Scanner fsc = new Scanner(file_url.openStream());

    //Computer object to store each computer manufacturer, model, processor, Ram and price
    Computer pc1 = new Computer();
    Computer pc2 = new Computer();
    Computer pc3 = new Computer();

    //Created the array called arrayCom
    Computer [] arrayCom = new Computer[15];
    int counter = 0;

    //I am stuck here. Need to stored them in an array 
    while (fsc.hasNext())
    {

    }

Here is the Computer class with the manufacturer, model, processor, Ram and price with setter and getter:

public class Computer {
private String manufacturer;
private String model;
private String processor;
private int ram;
private double price;

public Computer(){

}
public Computer(String manufacturer, String model, String processor, int ram, double price){
    this.manufacturer = manufacturer;
    this.model = model;
    this.processor = processor;
    this.ram = ram;
    this.price = price;
}
public String getManufacturer(){
    return manufacturer;
}
public void setManufacturer(){
    this.manufacturer = manufacturer;
}
public String getModel(){
    return model;
}
public void setModel(){
    this.model = model;
}
public String getProcessor(){
    return processor;
}
public void setProcessor(){
    this.processor = processor;
}
public int getRam(){
    return ram;
}
public void setRam(){
    this.ram = ram;
}
public double getPrice(){
    return price;
}
public void setPrice(){
    this.price = price;
}

My question is How to stored them in the object I created PC1, PC2 and PC3 in an array, also getting their price average and the RAM average for the PC1, PC2, PC3? any advice? Thanks

MohanKumar
  • 494
  • 3
  • 20
  • 1
    Possible duplicate of [Reading a plain text file in Java](https://stackoverflow.com/questions/4716503/reading-a-plain-text-file-in-java) – FailingCoder Oct 04 '19 at 00:39

1 Answers1

0

It is better to create extra class with method that reads file to string. Example: Java source file ... TextReader.java

import java.io.File;
import java.nio.file.Files;


public class TextReader{

  //Get data from file
  public static String getDataFromFile(String file){ 
     String data="";
     try{
         File f=new File(file);
         data=new String(Files.readAllBytes(f.toPath()));
     }catch(Exception e){e.printStackTrace();}
   return data;
  }

}

For example in your method "getModel()" you can do like:

   public String getModel(){
      return TextReader.getDataFromFile("modeldata.txt");
   }

Note: This method reads entire file text into String assuming that each piece of data is in specific file, otherwise you need to know each line with specific data if everything is in single file for all data, then use "readAllLines()" instead.

WailenB
  • 71
  • 7