2017-03-03 5 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. 文字列配列のインデックスとして乱数を使用します。

簡単な例:ところで

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])); 
関連する問題