Java 如何将字符串与字符串数组的特定部分进行比较?
我在做一个类似游戏的测验。我有两个数组(一个带州,另一个带首都)。基本上,它会询问用户随机状态下的资本。我想知道,如果用户输入了正确的状态,它会像nice job或其他什么,但我不知道如何将用户输入与特定的数组隔室进行比较。我试过了,但没用。。。 有什么帮助吗 我的错-我正在使用Java 比如说Java 如何将字符串与字符串数组的特定部分进行比较?,java,arrays,string,compare,Java,Arrays,String,Compare,我在做一个类似游戏的测验。我有两个数组(一个带州,另一个带首都)。基本上,它会询问用户随机状态下的资本。我想知道,如果用户输入了正确的状态,它会像nice job或其他什么,但我不知道如何将用户输入与特定的数组隔室进行比较。我试过了,但没用。。。 有什么帮助吗 我的错-我正在使用Java 比如说 if(guess.equals(capitals[random])) 其中guess是字符串,capitals是数组,random是随机数类似的逻辑应该可以工作。您希望将用户输入保存到字符串变量,然后
if(guess.equals(capitals[random]))
其中guess是字符串,capitals是数组,random是随机数类似的逻辑应该可以工作。您希望将用户输入保存到字符串变量,然后将其与n大小的数组进行比较
for(int i=0; i<arrayName.length();i++)
{
if(userinputString.equalsIgnorCase(arrayName[i])
{
System.out.println("HUrray!");
}//end if
}//end for
那就看看
if(capitals[ranNum].equalsIgnoreCase(userInput))
//do something
基本上,您需要一个映射
String->String(State->Capital)
。这可以通过使用Map
或创建一个State
类来实现,该类将包含其名称和大写字母作为属性
但在我看来,最好的选择是使用一个你知道有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()+"?");
}
}
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()+"?");
}
}