用户输入和计时器

时间:2018-04-12 18:57:31

标签: java

我正在制定一项计划,看看你是否列出了美国所有州的资本和州名。我想要的是,我有一个计时器,用户输入所有状态和大写作为State - capital映射。但是当我创造它时。我看到用户可以输入相同的状态和资金50次,他/她将获得50/50的分数。我在美国和首都使用过数组。

import java.util.Scanner;

public class Exam {

public void exam() {

    String state[] = {"alabama", "alaska", "arkansas", "california", "colorado", "connecticut", "delaware", "florida", 
        "Georgia","Hawaii", "Idaho",  "illinois", "indiana", "iowa", "kansas", "Kentucky", "louisiana", "maine", "maryland", 
        "massachusetts", "michigan", "minnesota", "mississippi", "missouri", "montana", "nebraska", "nevada", "new Hampshire",
        "new Jersey", "new mexico", "new york","north carolina", "north dakota", "ohio", "oklahoma", "oregon", "pennsylvania", 
        "Rhode island", "South carolina", "south dakota", "tennessee", "Texas", "utah", "vermont", "virginia", "washington",
        "west Virginia", "wisconsin", "wyoming"};
    String capital[] = {"montgomery", "juneau", "phoenix", "little Rock", "sacramento", "denver", "hartford", "dover", "tallahassee",
        "atlanta", "honolulu", "boise", "springfield", "indianapolis", "des moines", "topeka", "frankfort", "baton rouge",
        "augusta", "annapolis", "boston", "lansing", "st. paul", "jackson", "jefferson city", "Helena", "lincoln",
        "carson city", "concord", "trenton", "santa Fe", "albany", "raleigh", "bismarck", "Columbus", "Oklahoma city",
        "salem", "harrisburg", "providence", "columbia", "pierre", "nashville", "austin", "salt lake city", "montpelier",
        "richmond", "olympia", "charleston", "madison", "cheyenne"};

    int y = 0;

    String ad = " - ";

    String input;
    Scanner s = new Scanner(System.in);
    System.out.println("Start writing states and capitals [State - capital] (type stop to stop)");

    input = s.next().toLowerCase();

    for(int x = 0; x < 50; x++) {
        input = s.next().toLowerCase();
        if(input == state[0] + ad + capital[0]) {
            System.out.println("Correct");
            y++;
        } else { 
            System.out.println("wrong");
        }
    }

}
}

2 个答案:

答案 0 :(得分:1)

使用HashMap而不是数组。关键可能是国家,价值可以是该州的资本。

HashMap<String,String> map=new HashMap<>();  
map.put("Texas","Austin");

用户输入正确的状态和资金后,从HashMap中删除该条目。

map.remove("Texas");

如果您之前从未实施过HashMaps,请参阅https://www.javatpoint.com/java-hashmap

答案 1 :(得分:0)

另一种方法是将正确的x值添加到Set(无重复项),并查看其大小是否为50.