如何从文件中读取并添加到对象数据?

时间:2017-03-29 22:48:45

标签: java

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

我正在尝试读取上面输入的input.txt文件,但问题是该程序只读取文本文件的最后一行。

这是我的代码:

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() + " ");
        }
    }

}

感谢您的帮助我被困! 我还附加了我正在尝试使用的Items类

    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;
        }
    }

这是代码的结尾

3 个答案:

答案 0 :(得分:1)

也许这会有用:

<强>更新

您应声明并初始化 j 变量,并在 while 循环中变量 j 每个循环增加1:

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
}

在for循环内的printArray (Items[] x)方法中,你不应该定义它:

x[i] = new Items();

因为在每次迭代中都会创建一个新对象,而在打印时它将是 0 0 0

以下示例:

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() + " ");
        }
    }
}

答案 1 :(得分:0)

我会删除for循环,使用列表而不是数组并读取每个项目并将其添加到列表中:

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();
    //...
}

还有两条评论:

  1. Items应该被称为Item
  2. 您应该考虑将toString()方法添加到课程Item,这样就可以轻松打印

答案 2 :(得分:0)

您的问题出在下面的 for-loop 中。你做一个while循环而不实际更改目标,所以一切都被覆盖,只有最后一个输入占优势。解决这个问题有两种可能性。这两种方法只能在输入文件格式正确的假设下才能最佳地工作。需要调整其他更改以使其失败。

//---------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++;
}