[英]How to compare a string to a specific compartment of an array of strings?
我正在做类似游戏的测验。 我有两个数组(一个带有状态,另一个带有大写)。 基本上,它询问用户随机状态下的资本是多少。 我希望用户输入正确的状态,就像做一项好工作一样,但是我不知道如何将用户输入与特定的阵列隔室进行比较。 我尝试了.contains但无济于事...有帮助吗?
不好-我正在使用Java
例如
if(guess.equals(capitals[random]))
其中guess是字符串,大写字母是数组,random是随机数
基本上,您需要一个映射String -> String (State -> Capital)
。 这可以使用Map<String, String>
或通过创建一个State
类来完成Map<String, String>
该类将包含其名称和大写字母作为属性。
但是我认为,最好的选择是使用一个枚举,因为您知道有50个州。 这是一个小例子。
public class Test {
static final State[] states = State.values();
static Random r = new Random();
static Scanner sc = new Scanner(System.in);
public static void main (String[] args){
State random = states[r.nextInt(states.length)];
random.askQuestion();
String answer = sc.nextLine();
if(answer.equals(random.getCapital())){
System.out.println("Congrats");
} else {
System.out.println("Not really");
}
}
}
enum State {
//Some states, add the other ones
ALABAMA("Montgomery"),
ALASKA("Juneau");
private final String capital;
private State(String capital){
this.capital = capital;
}
public String getCapital(){
return this.capital;
}
public void askQuestion(){
System.out.println("What capital goes with "+this.name()+"?");
}
}
与此类似的逻辑应该起作用。 您想要将用户输入保存到String变量,然后将其与n大小的数组进行比较。
for(int i=0; i<arrayName.length();i++)
{
if(userinputString.equalsIgnorCase(arrayName[i])
{
System.out.println("HUrray!");
}//end if
}//end for
好的,所以您正在以某种方式生成一个随机数,然后需要将输入与该随机数的大写数组中的字符串进行比较/
我假设数组是有序的,以大写[10]为州提供大写[10]。
如果是这样,只需将索引保存到变量中即可。
int ranNum=RandomNumFunction();
然后看看
if(capitals[ranNum].equalsIgnoreCase(userInput))
//do something
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.