2013-08-20 150 views
0

我有一個程序在我的項目文件夾中打開一個.txt文件並讀取其中的行。我知道文件讀取工作,所以它不是一個I/O問題(或擺動,因爲我也使用),但是當我設置nim(我的變量)= anArray [num](也是一個變量)它不工作。注意:當我運行程序時,它會到達println(「First Declaration」),所以它只是數組的設置不起作用。謝謝:)如何設置一個字符串數組等於另一個字符串(Java)(NB:我正在使用I/O)?

import java.io.File; 
import java.util.Scanner; 

import javax.swing.JFrame; 


public class SpanishSetOne extends JFrame { 

    private static Scanner s; 
    public String[] anArray; 
    public String nim; 

    public SpanishSetOne() { 
     super("Spanish Set 1"); 

     initFile("spanish"); 
     setSize(500,500); 
     setVisible(true); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 

    public void initFile(String name) { 
     try{ 
      s = new Scanner(new File(name + ".txt")); 
      System.out.println("setScanner"); 
     }catch(Exception e) { 
      System.out.println("ERROR - Could not read file"); 
     } 
     int num = 0; 
     while(s.hasNext()) { 
      System.out.println(("Made it into the loop")); 
      nim = s.nextLine(); 
      System.out.println("First declaration"); 
      anArray[num] = nim; 
      System.out.println(anArray[num]); 
      num++; 
     } 
    } 
} 
+0

和大小「不起作用「是指什麼?發生了什麼,你期望會發生什麼? – Henry

+0

當然,這一定是拋出了一個例外。這個例外應該被審查,因爲它會有很多有用的信息。 – pamphlet

+0

謝謝你們。我不願意爲字符串添加一個數字,以便證明我自己。所有非常有幫助:) – user2700472

回答

2

你需要初始化數組是這樣的:

String[] array = new String[10]; 

我也將考慮使用一個ArrayList,所以你不必擔心你的陣列

0

您還沒有初始化數組。 public String[] anArray;它的一個字符串數組,分配了零個內存位置來存儲任何字符串。

Use String[] anArray = new String[numberOfElements]; 
// Here anArray will be a String Array with 'numberOfElements' memory location. 

強烈推薦使用

List<String> anArrayList = new ArrayList<String>(); 

希望這有助於。

+0

你需要通過列表中的數字:) – user2700472

+0

http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html這應該會幫助您瞭解詳情。 – JNL

+0

謝謝你,我想我知道了:) – user2700472

0

您必須初始化數組,然後才能使用它。

anArray = new String[count]; 
//count being the number of elements you want to store in the array 
相關問題