简体   繁体   中英

how to read from file and add to object data?

17  5
12  8
15  22
17  11
33  21
43  15
15  4
44  35
23  19
10  23
55  39
8   6
21  9
20  28
20  13
45  29
18  16
21  19
68  55
10  16
33  54
3   1
5   9

I am trying to read in input.txt file that looks like input above but the problem is that the program only reads in the last line from the text file.

Here is my code:

import java.io.FileNotFoundException;
import java.io.*;
import java.io.IOException;
import java.util.*;
import java.util.Scanner;

/**
 * 
 */
public class ReadIn {


public static void main(String[] args) throws IOException {

    //List<Integer> value = new ArrayList<Integer>();
    //List<Integer> weight = new ArrayList<Integer>();
    FileReader readFile = new FileReader ("C:\\Users\\owner\\IdeaProjects\\knapsack\\src\\input");
    BufferedReader br = new BufferedReader(readFile);
    Scanner input = new Scanner(br);
    Scanner keyboard = new Scanner(System.in);
    //List<Items> items = new ArrayList<Items>();


    Items[] items= new Items[23];//this only creates references that are set to their default value null which throws a null exception
    for(int i =0 ; i <items.length; i++) {//fixes null exception

        items[i] = new Items();//fully creates the objects

        while (input.hasNext()) {//read in file input to object data
            items[i].setValue(input.nextInt());
            items[i].setWeight(input.nextInt());
            items[i].setId(i);
        }
    }
    input.close();
    input.reset();
    System.out.println("What is the max capacity for the knapsack? ");
    Integer maxCapacity = keyboard.nextInt();
    System.out.println(maxCapacity);
    int[] maxWeight = new int[maxCapacity];//creates int array so we can use the index as the maxWeight as the number of fields
    printArray(items);

}
    public static void printArray(Items[] x) {

        for (int i = 0; i < x.length; i++) {
            x[i] = new Items();
            System.out.println(x[i].getValue() + " " + x[i].getWeight() + " " + x[i].getId() + " ");
        }
    }

}

Thanks for the help I am stuck!! I have also attached the Items class that i am trying to use

    public class Items {
        private Integer value ;
        private Integer weight;
        private Integer Id;

        public Items(){
            this.value = 0;
            this.weight = 0;
            this.Id =0;
        }

        public Items(Integer v, Integer w, Integer ID){
            this.value = v;
            this.weight = w;
            this.Id = ID;
        }


        public Integer getValue() {
            return value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public Integer getWeight() {
            return weight;
        }

        public void setWeight(Integer weight) {
            this.weight = weight;
        }

        public Integer getId() {
            return Id;
        }

        public void setId(Integer id) {//sets id
            Id = id;
        }
    }

This is the end of the code

Maybe this will be useful:

UPDATE:

You should declare and initialize the j variable and within the while loop the variable j increases by 1 in each loop:

int j=0; // ----> initialize j variable
while (input.hasNext()) {
    items[j].setValue(input.nextInt());
    items[j].setWeight(input.nextInt());
    items[j].setId(j);
    j++; // ----> increment 1 y each loop
}

In the printArray (Items[] x) method inside the for loop you should not define this:

x[i] = new Items();

because in each iteration create a new object and when print it will be 0 0 0


Here the example:

public class MyTree {
    public static void main(String[] args) throws IOException {

        FileReader readFile = new FileReader("C:\\Users\\owner\\IdeaProjects\\knapsack\\src\\input");
        BufferedReader br = new BufferedReader(readFile);
        Scanner input = new Scanner(br);
        Scanner keyboard = new Scanner(System.in);

        Items[] items = new Items[23];//this only creates references that are set to their default value null which throws a null exception
        for (int i = 0; i < items.length; i++) {//fixes null exception
            items[i] = new Items();//fully creates the objects
        }

        int j=0; // ----> initialize j variable
        while (input.hasNext()) {
            items[j].setValue(input.nextInt());
            items[j].setWeight(input.nextInt());
            items[j].setId(j);
            j++; // ----> increment 1 y each loop
        }

        input.close();
        input.reset();
        System.out.println("What is the max capacity for the knapsack? ");
        Integer maxCapacity = keyboard.nextInt();
        System.out.println(maxCapacity);
        int[] maxWeight = new int[maxCapacity];//creates int array so we can use the index as the maxWeight as the number of fields
        printArray(items);

    }

    public static void printArray(Items[] x) {

        for (int i = 0; i < x.length; i++) {
            //x[i] = new Items();  //It shouldn't be here, because in each iteration create a new object
            System.out.println(x[i].getValue() + " " + x[i].getWeight() + " " + x[i].getId() + " ");
        }
    }
}

I would remove the for-loop, use a list instead of an array and read each item and add it to the list:

public static void main(String[] args) throws FileNotFoundException {
    FileReader readFile = new FileReader("C:\\Users\\owner\\IdeaProjects\\knapsack\\src\\input");
    BufferedReader br = new BufferedReader(readFile);
    Scanner input = new Scanner(br);

    List<Item> items= new LinkedList<>();
    int i = 0;
    while (input.hasNext()) {
        Item item = new Item();
        item.setValue(input.nextInt());
        item.setWeight(input.nextInt());
        item.setId(i);
        items.add(item);
        i++;
    }
    input.close();
    input.reset();
    //...
}

Two more comments:

  1. class Items should be called Item
  2. you should consider adding a toString() method to class Item this way it'll be easy to print

Your problem lies in the for-loop below. You do a while-loop without actually changing the destination, so everything gets overwritten and only the last input prevails. There are two possibilities to fix this. Both of those only work optimally under the assumption that the input file is correctly formatted. Other changes would need to be adjusted to make it fail proof.

//---------Option 1: Remove the While-loop----
for(int i =0 ; i <items.length; i++) {//fixes null exception

    items[i] = new Items();//fully creates the objects
    items[i].setValue(input.nextInt());
    items[i].setWeight(input.nextInt());
    items[i].setId(i);
}


//---------Option 2: Let the for-loop finish before the while-loop ------
for(int i =0 ; i <items.length; i++) { //fixes null exception
    items[i] = new Items(); //fully creates the objects
}

int k=0; //Need a variable for count
while (input.hasNext()) {
    items[k].setValue(input.nextInt());
    items[k].setWeight(input.nextInt());
    items[k].setId(k);
    k++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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