2012-12-07 125 views
1

所以我想要做的是從文件中使用Scanner = new Scanner(new File("list.txt"))填充一個包含30個名字的100個項目的數組。它需要使用"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 ....那些錯誤是可恥的大聲笑。感謝所有得到它的工作=]

回答

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; 

注:此外,好做法,您可能需要添加一些防禦性編程檢查來增加您的循環終止條件。 (考慮當輸入文件不包含標記時會發生什麼)