2014-03-30 46 views
0

我試圖創建一個程序,從文件中選擇一個隨機單詞,並根據單詞的長度輸出正確數量的空格。例如,如果這個詞很聰明,程序會輸出_ _ _ _ _。這是程序:錯誤:無法找到符號顯示Java初學者

import java.util.*; 
    import java.io.*; 
    public class Selection { 
     public static void main(String[] args) throws IOException { 
     String[] words = new String[100]; 
     Scanner in = new Scanner(new FileReader("words.txt")); 
     for (int i = 0; i < 100; i++) 
       words[i] = in.next(); 
     Random r = new Random(); 
     int selected = r.nextInt[100]; 
     String sWord = words[selected]; 

     for (int j = 0; j < sWord.length(); j++) 
       System.out.printf("_"); 

     in.close(); 
} 
} 

這是錯誤:

java:18: error: cannot find symbol 
    int selected = r.nextInt[100]; 
        ^
    symbol: variable nextInt 
    location: variable r of type Random 
    1 error 

瞭解什麼,我沒有正確地做任何幫助將不勝感激。

+2

只需將您的代碼改成這樣:'選擇的int = r.nextInt(100);' – FoggyDay

回答

3
int selected = r.nextInt[100];// use() r.nextInt(num); 
+0

請讓OP知道爲什麼。 – BitNinja

+0

基本的java語法? –

+0

就像因爲它不是一個數組的方法。 – BitNinja

1
int selected = r.nextInt[100]; 

你的問題是在這裏,您試圖訪問變量nextInt就像一個數組,但它是一個功能。

正確的方式做,這就是:

int selected = r.nextInt(100); 

您使用括號,因爲你是傳遞值100作爲參數。

0

對不起因爲某些原因這裏的格式不工作對我來說

你有

int selected = r.nextInt[100]; 

的代碼應該是

int selected = r.nextInt(100); 

的原因是,這是你使用[]數組,()在對象上調用方法。

例如,
如果你想創建一個數組,你怎麼做,如果你做

int[] arr = new int[100]; // created an array with enough storage to hold 100 int

下會失敗

int() arr = new int(arr); // fail! 

在另一方面,

Random r = new Random(); // it works! 

但是下面會失敗

Random r = new Random[]; // fail!