简体   繁体   English

如何使用构造函数初始化每个数组元素时从文件读取和存储对象数组

[英]How to read from file and store array of objects while initializing each array elements using a constructor

I am trying to create program that shows 2 outputs to the screen. 我正在尝试创建将2个输出显示到屏幕的程序。

The first one being null and the 2nd one, shows values from the input file that was stored in an array of objects. 第一个为空,第二个为空,它显示了输入文件中存储在对象数组中的值。

Here is my code so far: 到目前为止,这是我的代码:

 javax.swing.JOptionPane; import java.util.Scanner; import java.io.File; public class Testing { public static void main(String[] args) { //error checking for commandline input if(args.length != 1){ System.out.println("Please enter at least one input file into the argument."); //terminates the program if more than 1 is entered System.exit(1); } //make an array of bird objects final Integer SIZE = 9; HawaiiNativeForestBirds array[] = new HawaiiNativeForestBirds[SIZE]; //output array of Nature objects to the screen (should be "null" for all elements) System.out.println("Hawai'i Native Forest Birds "); System.out.println("index element "); for (int i = 0; i < SIZE; i++) { System.out.println(" " + i + " " + array[i] ); System.out.println(); //read from file and store data from file in your Nature array of objects //by initializing each array element using the constructor File file = new File(args[0]); Scanner inputFromFile = null; array[0] = new HawaiiNativeForestBirds("'akiapola'au"," hemignathus munroi"," yellow", 800); array[1] = new HawaiiNativeForestBirds("akepa"," loxxops coccineus"," red", 9301); array[2] = new HawaiiNativeForestBirds("hawai'i creeper"," oreomystis mana"," yellow green", 2501); array[3] = new HawaiiNativeForestBirds("i'iwi"," vestiara conccinea"," red green", 2501); array[4] = new HawaiiNativeForestBirds("apapane"," himatione sanguinea"," white red", 5001); array[5] = new HawaiiNativeForestBirds("hawai'ian amakihi"," hemignathus virens"," yellow brown", 3001); array[6] = new HawaiiNativeForestBirds("hawaii'an hawk"," buteo solitarius"," white gray", 1100); array[7] = new HawaiiNativeForestBirds("puaiohi"," myadestes palmeri"," brown", 125); array[8] = new HawaiiNativeForestBirds("anianiau"," magumma parva"," light yellow", 2000); //use toString() to display the array again with data from input file System.out.println("index name Scientific Name Color Population"); for(int x=0;x<SIZE;x++){ System.out.println(" " + i + " " + array[i]); } }//end of main() method }// end of class LastnameFirstname08 /** * Class HawaiianTheme stores and displays the data for each HawaiianTheme object * * */ class HawaiiNativeForestBirds { // data fields that store each object's data private String name; private String scientificname; private String color; private Integer population; //constructor - used to initialize the three data fields /** * Stores the name,scientific name, color and population of the Hawaiian Birds * This is a Constructor, which is used to Create EAch Object & Initialize DAta Fields. * * @param * @param * @param * @param */ public HawaiiNativeForestBirds(String birdName, String scientificName,String birdColor, Integer birdPopulation) { name = birdName; scientificname = scientificName; color = birdColor; population = birdPopulation; }//end of constructor //toString() method - returns a String with the 4 data fields public String toString() { String output = name +" "+ scientificname + " "+ color +" "+ population; return output; }//end of toString() }//end of class HawaiianTheme 

The only thing missing now is the method that reads from file and stores the array of objects by initializing the arrays. 现在唯一缺少的是通过初始化数组从文件读取并存储对象数组的方法。

I'm still no good at combining both of these and as you can see from the code, I don't have the method yet nor I know how the format would look like to combined both. 我仍然不擅长将这两种方式结合起来,正如从代码中可以看到的那样,我还没有方法,也不知道将两者结合在一起的格式。

edit 2: I finally fixed my output . 编辑2:我终于修复了我的输出。 I initiliazed stuff, now how to read from file and store to the array? 我初始化了东西,现在如何从文件读取并存储到数组? ;_; ; _; Output: 输出:

 Hawai'i Native Forest Birds index element 0 null 1 null 2 null 3 null 4 null 5 null 6 null 7 null 8 null 9 null index name Scientific Name Color Population 0 'akiapola'au hemignathus munroi yellow 800 1 akepa loxxops coccineus red 9301 2 hawai'i creeper oreomystis mana yellow green 2501 3 i'iwi vestiara conccinea red green 2501 4 apapane himatione sanguinea white red 5001 5 hawai'ian amakihi hemignathus virens yellow brown 3001 6 oma'o myadester obscurus gray 17001 7 hawaii'an hawk buteo solitarius white gray 1100 8 puaiohi myadestes palmeri brown 125 9 anianiau magumma parva light yellow 2000 

All I want is to show two outputs but I gotta read and store the array of objects for the 2nd output 我只想显示两个输出,但是我必须读取并存储第二个输出的对象数组

1.Display HawaiiNativeForestBirds array array[] without initializing elements: 1.显示HawaiiNativeForestBirds数组array []而不初始化元素:

2.Display HawaiiNativeForestBirds array[] again but shows the array values from the file after initializing elements: 2.再次显示HawaiiNativeForestBirds array [],但在初始化元素后显示文件中的数组值:

edit: 编辑:

My CSV Content: 我的CSV内容:

birds.csv birds.csv

I would solve this problem in following way. 我将以以下方式解决此问题。

Create a HawaiiNativeForestBirds java class 创建一个HawaiiNativeForestBirds Java类

class HawaiiNativeForestBirds {
private String name;
private String scientificname;
private String color;
private Integer population;
public HawaiiNativeForestBirds(){

  }
  public HawaiiNativeForestBirds(String name, String scientificname,
        String color, Integer population) {
    super();
    this.name = name;
    this.scientificname = scientificname;
    this.color = color;
    this.population = population;
  }  


  public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getScientificname() {
    return scientificname;
}
public void setScientificname(String scientificname) {
    this.scientificname = scientificname;
}
public String getColor() {
    return color;
}
public void setColor(String color) {
    this.color = color;
}
public Integer getPopulation() {
    return population;
}
public void setPopulation(Integer population) {
    this.population = population;
}

  public String toString() {
  String output = name +"     "+ scientificname + "     "+ color +"     "+        population;
  return output;
}      
}

Edit: If you want read a csv file then you cans solve it as below: 编辑:如果您想读取一个csv文件,那么您可以如下解决它:

Assuming csv file contains data in following format 假设CSV文件包含以下格式的数据

puaiohi,myadestes palmeri,brown,125
puaiohi,magumma parva,yellow,2000

I have modified Testing class to read the csv file 我修改了测试类以读取csv文件

 public class Testing {

 public static void main(String[] args) {

    String csvFile = "birds.csv";
    String line = "";
    String cvsSplitBy = ",";

    List<HawaiiNativeForestBirds>  listofBirds = new ArrayList<HawaiiNativeForestBirds>();
    try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {

        while ((line = br.readLine()) != null) {

            // use comma as separator
            String[] bird = line.split(cvsSplitBy);
            HawaiiNativeForestBirds Hawaiinbird= new HawaiiNativeForestBirds(bird[0],bird[1],bird[2],Integer.valueOf(bird[3]));
            listofBirds.add(Hawaiinbird);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
// First display null values
 HawaiiNativeForestBirds[]  hbirds=new        HawaiiNativeForestBirds[listofBirds.size()];
    System.out.println("index   " + "element   ");  
    int i=0;
    for (HawaiiNativeForestBirds hbird:hbirds){
        i++;
        System.out.println(i+"   "+hbird);
        }
    // Now display actual values
    hbirds= listofBirds.toArray(new HawaiiNativeForestBirds[listofBirds.size()]);

    System.out.println("index   " + "name   "+ "Scientific Name    "+ "Color   " + "Population   ");        
    i=0;
    for (HawaiiNativeForestBirds hbird:hbirds){
        i++;
        System.out.println(i+"   "+hbird.toString());
        }
 }
 }

Note: HawaiiNativeForestBirds class would remain as it is. 注意:HawaiiNativeForestBirds类将保持不变。

Try reading in each String and storing it into its own index in a array of Strings. 尝试读取每个String并将其存储在String数组中的索引中。 Then check out this algorithm and see if it works. 然后检查该算法,看看它是否有效。 I am sure this is not the best way to handle the situation, but I am in class and thought I would give it a intuitive shot. 我确信这不是解决这种情况的最佳方法,但是我在课堂上并且认为我会给出一个直观的镜头。 I am going off of the base that your constructor takes 4 parameters, and also assuming that the parameters in the txt file are in order of how they would be put into the constructor. 我从您的构造函数采用4个参数的角度出发,并假设txt文件中的参数按将其放入构造函数的顺序排列。 You will also have to cast the 4th parameter into a int so it matches the expected argument type for your constructor. 您还必须将第4个参数强制转换为int,以使其与构造函数的预期参数类型匹配。

//Create String array and use for loop to fill temp array with words from txt file
temp[i] = scan.next()
for(int i = 0; i < temp.length; i++) {
if (i != 0) {
i = i + 3;
HawaiiNativeForestBirds[i - (3*i/4)] = new HawaiiNativeForestBirds(temp[(i-4)+4], temp[(i-4)+5], temp[(i-4)+6], temp[(i-4)+7)];

}
else {
HawaiiNativeForestBirds[i] = new HawaiiNativeForestBirds(temp[i],temp[i+1], temp[i+2], temp[i+3]);
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM