1

所以我想要做的是使用Scanner = new Scanner(new File("list.txt")). 它需要使用标记"DONE"来结束文件底部的循环。

我该怎么做?array[arraySize] = value();给我一个类型不匹配

public class List
{
  public static void main(String[] args) throws FileNotFoundException
  {
    double array[] = new double[100];
    int arraySize = 0;
    String value;
    String sentinel = "DONE";

    Scanner inFile = new Scanner(new File("list.txt"));
    value = inFile.next();
    while (value != sentinel) 
    {
      array[arraySize] = value();
      arraySize++;
      value = inFile.next();
    }
  }
}

D'oh....那些错误是可耻的,哈哈。谢谢大家让它工作=]

4

1 回答 1

1

一些问题,您需要将这些行从:

double array[] = new double[100]; // can't assign string to double
                                  // (since you said "30 names", I assume
                                  //  you aren't trying to get numbers from
                                  //  the file)
...
while (value != sentinel) // this performs pointer comparison, whereas you want
                          // string comparison
...
    array[arraySize] = value(); // value is a variable, not a function

到:

String array[] = new String[100];
...
while (!value.equals(sentinel))
...
    array[arraySize] = value;

注意:此外,作为一种好的做法,您可能希望添加一些防御性编程检查以增强while循环终止条件。(考虑当输入文件不包含哨兵时会发生什么)

于 2012-12-07T19:26:35.723 回答