我有一个地图对象,键/值定义为美国州/首都(例如德克萨斯/奥斯汀)
当用户键入状态时我需要返回Capital,当用户输入类型时,我会返回状态
我编写了以下代码,但它仅适用于Capital - >国家比较。
对于什么是错误的任何想法?
public class StatesCapitals extends AppCompatActivity {
Map<String, String> capitals = new HashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_states_capitals);
String text = "US_states"; //text file in the assets folder
byte[] buffer = null;
InputStream is;
try {
is = getAssets().open(text);
int size = is.available(); //size of the file in bytes
buffer = new byte[size]; //declare the size of the byte array with size of the file
is.read(buffer); //read file
is.close(); //close file
} catch (IOException e) {
e.printStackTrace();
}
// Store text file data in the string variable
String str_data = new String(buffer);
//Split using the delimiter ":" to the all elements
String[] stateCapsArray = str_data.split(":");
//Iterate over the array
for(int i=0;i<stateCapsArray.length-1;i++) {
//Skip each other element as we are collecting 2 elements at a time
if(i%2 == 0) {
String state = stateCapsArray[i];
String capital = stateCapsArray[i+1];
capitals.put(state, capital);
}
}
Toast.makeText(getBaseContext(), capitals.toString(), Toast.LENGTH_LONG).show();
}
public void doit(View v)
{
TextView result=(TextView)findViewById(R.id.textViewResult);
EditText et=(EditText)findViewById(R.id.editText);
String input=et.getText().toString();
Toast.makeText(getBaseContext(), "Input: "+input, Toast.LENGTH_LONG).show();
Iterator entries = capitals.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
String key = (String)entry.getKey();
String value = (String)entry.getValue();
if (input.equals(key))
{result.setText("The Capital of "+key+" is: "+value);}
else if (input.equals(value)) {result.setText("The State of: "+value+" is: "+key);}
}
}
}
答案 0 :(得分:0)
看起来问题出在循环中:
str_data
如果state1:capital1:state2:capital2:state3:...
包含for (int i = 0; i < stateCapsArray.length; i += 2) {
String state = stateCapsArray[i];
String capital = stateCapsArray[i+1];
capitals.put(state, capital);
}
之类的信息,那么您的循环应该遍历它:
i
主要变化是2
在每次迭代时都会DB[:school_districts].select(:code).group_and_count(:code).reverse_order(:count)
前进。