2017-03-03 72 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]));