2017-01-09 25 views
-3

这是我的代码片段。这个if语句允许我从文件中读取数据,然后从文件中选择一个随机单词并使用print语句,并将其打印出来。使用print语句在Java中返回变量?

我面临的问题是我需要能够获得它选择的单词,然后才能够在下面的String []猜测语句中使用它。我知道我在“{}”中所拥有的是错误的,但它只是为了更好地了解我正在尝试做什么。

if (choose==1) { 
    System.out.println("you choose easy\n"); 

    FileReader file = new FileReader("file1.txt");//first file 
    BufferedReader reader = new BufferedReader(file); 

    while((reader.readLine()) != null) 
     array.add(reader.readLine()); 

    int randomIndex = random.nextInt(array.size());//randomly pick a word 
    System.out.println(array.get(randomIndex));// randomly print a word 
    reader.close(); 
} 

String[] guess = {array.get(randomIndex)}; 
+0

你的ArrayList的定义在哪里? –

+1

您的'randomIndex'变量被限制在您想要使用的语句的块外。通过将它放在相同或父块中,使其可访问。 –

+0

为什么'guess'被声明为一个String数组,当它真的只是一个'String'时,即猜测的单词呢? – Andreas

回答

1
String word = null; 
if (choose==1) { 
    System.out.println("you choose easy\n"); 

    // Use try-with-resources so it auto closes 
    try (
     FileReader file = new FileReader("file1.txt"); 
     BufferedReader reader = new BufferedReader(file);) { 

     while((reader.readLine()) != null) 
     array.add(reader.readLine()); 

     // randomly pick a word 
     int randomIndex = random.nextInt(array.size()); 
     word = array.get(randomIndex); 

     // print the word 
     System.out.println(word); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } 
} 

String[] guess = new String[] { word }; 

你可能会是一个列表,而不是一个数组更好,但是这取决于你在做什么。

+0

这段代码也是错的! –

+0

@TedTrippin你是一个传奇,它正在做我现在需要的东西,现在我非常感谢你 –