这是我的要求:
使用2来创建(硬编码)50个州及其首府城市 维数组。
在对话框中:要求用户输入州或城市。
如果输入州,请找到其首府。如果进入城市, 找到它的国家。
如果没有,找到,发出错误消息。
这应该是循环,直到用户不想玩 了。
我真的不知道从哪里开始,到目前为止我所做的就是创建阵列,我真的不知道如何搜索阵列,并吐出相应的州/资本。 / p>
非常感谢任何帮助。
这是我到目前为止编写的代码。
import java.util.Scanner;
public class GuessStates {
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
String[][] statesAndCapitols = {
{"Alabama","Alaska","Arizona","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"},
{"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"}};
System.out.println("Please enter a State or a capitol city.");
String userInput = input.nextLine();
}
}
再次感谢!
答案 0 :(得分:0)
尝试使用for循环搜索数组。
使用for循环,它会跟踪并更新遍历数组的当前位置。
一旦找到正确的状态或资本(通过检查userInput.equalsIgnoreCase(statesAndCapitols [x] [y]),然后获取您所在的当前位置并检索所需的信息。
即
for(int x = 0; x < 2; ++x) //loop through states the first time, capitols the second
for(int y = 0; y < 50; ++y) //always 50, unless new states get added (obviously not a problem in this example, but useful to think about in future problems - YOUR DATA WILL ALMOST ALWAYS CHANGE.
if(userInput.equalsIgnoreCase(statesAndCapitols[x][y])
System.out.println(statesAndCapitols[x == 1 ? 0 : 1][y]);
在数组中,我做了x == 1? 0:1。这是一个三元运算符,它的含义是如果x等于1,则使用值0,否则使用值1.
这是解决这个问题的一种方法。
另一种方法是为城市和州创建自己的类/数据类型,这样您就不需要保持数组同步,这意味着您不需要更新2一个更改的项目(如添加另一个城市/州组合)。
希望这有点帮助! :)
答案 1 :(得分:0)
String entered_state=input.nextLine();
for(int i=0;i<50;i++){
if(statesAndCapitols[0][i].equals(entered_state)){
String searched_city=statesAndCapitols[1][i];
//print the city name
break;
}
}
if(i==50)
//print error
从进入的城市搜索状态也是一样。