状态和资本猜猜游戏的并行数组

时间:2017-03-03 19:11:08

标签: java arrays

我试图得到随机状态和大写字母的输出,但我的输出总是问“阿拉巴马州的首都是什么?”然后显示下一行的错误。我怎样才能正确地询问赎金州和资本呢?

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();
    }

} 

1 个答案:

答案 0 :(得分:0)

我的代码中没有任何随机性。这些是步骤(根据您目前的情况):

  1. 从文本文件中读取状态和大写字母。
  2. 将它们存储在String数组中。
  3. 生成从0到size-1大小的随机数。
  4. 使用该随机数作为String数组的索引。
  5. 简化示例:

    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]));