2017-03-03 71 views
-4

我试图得到随机状态和首都的输出,但我的输出总是问“什么是阿拉巴马州的首府?然后显示下一行的错误。我怎样才能让它正确地询问赎金状态和资本?国家和资本猜测游戏并行数组

public static void main (String args [])throws FileNotFoundException { 
    Scanner input= null; 
    Scanner file=null; 
    try 
    { input= new Scanner(System.in); 
     file= new Scanner (new File ("capitals.txt")); 

     while (file.hasNext()){ 
      String[] myString = file.next().split (","); 
      System.out.println(String.format ("What is the capital of %s?", myString[0])); 
      System.out.println(input.next().equals(myString[1])); 

     } 
    } 
    catch (FileNotFoundException fe){ 
    } 
    finally { 
     file.close(); 
     input.close(); 
    } 

} 
+0

顺便说一句,我的进口和类是进口java.util.Scanner的; import java.io. *; import java.io.FileNotFoundException; public class StateCapitalLookup { –

+0

哪里有随机数?您没有生成索引 –

回答

0

我在代码中看不到任何随机性。这些步骤(根据您目前的情况):

  1. 从您的文本文件中读取状态和首字母。
  2. 将它们存储在字符串数组中。
  3. 生成一个从0到array-1大小的随机数。
  4. 使用该随机数作为String数组的索引。

一个简单的例子:

Random rnd = new Random(); 
String[] capitals = readFromFile(); 
int x = rnd.nextInt(capitals.length); 
System.out.println(String.format ("What is the capital of %s?", capitals[x]));