从文件/数组中读取。没有价值。没有错误

时间:2013-04-26 18:24:06

标签: java

我在这里缺少什么想法?我正在从文件数组中读取。文本文件中的值不会存储,也没有输出。我得到的只是“名字和总数”,但没有价值。

我不知道。

private int[] totals;
private String[] names;
private String[] list;

private int count;


public void readData() throws IOException {

    BufferedReader input = new BufferedReader(new FileReader("cookies.txt"));

    //create the arrays
    totals = new int[count];
    names = new String[count];
    list = new String[count];

    //read in each pair of values
    String quantityString = input.readLine();
    for (int i = 0; i < count; i++) {
        names[i] = input.readLine();
        list[i] = input.readLine();
        quantityString = input.readLine();
        totals[i] = Integer.parseInt(quantityString);
    }

}

public void display() {
    System.out.println("names           totals")
    for (int i = 0; i < count; i++)
        System.out.println(list[i] + "        \t " + names[i] + "        \t" + totals[i]);
}

//called to compute and print the result
public void printResults() {

    //find the best teacher
    int maxIndex = 0;
    int maxValue = 0;

    //for each record stores
    for (int i = 0; i < count; i++) {
        //if we have a new MAX value so far, update variables
        if (maxValue < totals[i]) {
            maxValue = totals[i];
            maxIndex = i;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您永远不会为变量count赋值,因此Java会将其初始化为0。这意味着您的数组大小也为0

所以,因为count为零,所以你永远不会从文件中读取任何内容,这就是为什么数据中没有存储任何内容以及为什么没有打印出来的原因。

示例:逐行阅读文件

// create temporary variable to hold what is being read from the file
String line = "";

// when you don't know how many things you have to read in use a List
// which will dynamically grow in size for you
List<String> names = new ArrayList<String>();
List<Integer> values = new ArrayList<Integer>();

// create a Reader, to read from a file
BufferedReader input = new BufferedReader(new FileReader("cookies.txt"));

// read a full line, this means if you line is 'Smith 36' 
// you read both of these values together
while((line = input.readLine()) != null) 
{
   // break 'Smith 36' into an array ['Smith', '36']
   String[] nameAndValue = line.split("\\s+"); 

   names.add(nameAndValue[0]);                   // names.add('Smith')
   values.add(Integer.parseInt(nameAndValue[1]); // values.add(36);
}