Java 用sentinel填充字符串数组

Java 用sentinel填充字符串数组,java,file-io,while-loop,java.util.scanner,Java,File Io,While Loop,Java.util.scanner,因此,我尝试使用Scanner=newscanner(新文件(“list.txt”))从一个文件中用30个名称填充100个项目的数组。它需要使用的sentinel“DONE”来结束在文件底部找到的循环 我该怎么做数组[arraySize]=value()给我一个类型不匹配 public class List { public static void main(String[] args) throws FileNotFoundException { double array[]

因此,我尝试使用
Scanner=newscanner(新文件(“list.txt”))
从一个文件中用30个名称填充100个项目的数组。它需要使用
的sentinel“DONE”
来结束在文件底部找到的循环

我该怎么做<代码>数组[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();
    }
  }
}

哦……这些错误太可耻了,哈哈。谢谢大家让它起作用了=]

一些问题,您需要将这些行从以下内容更改为:

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
致:


注意:此外,作为良好实践,您可能需要添加一些防御性编程检查,以增强
while
循环终止条件。(考虑当输入文件不包含sentinel时会发生什么情况)

有几个问题,您需要更改以下行:

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
致:

注意:此外,作为良好实践,您可能需要添加一些防御性编程检查,以增强
while
循环终止条件。(考虑输入文件不包含sentinel时会发生什么情况)