-1
を返しますキャピタルを返すために、ユーザがタイプを入力するとキャピタルは状態を返すMapオブジェクトにキー/値を検索し、それぞれの値/キー
私は以下をコード化しましたが、資本 - >州比較でのみ機能します。
何が問題なの?
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);}
}
}
}
ファイル内のデータはどのように見えますか?私たちに例を挙げてもらえますか? –
各方向に1つずつ、またはGoogle [Java双方向地図](https://www.google.com/search?q=Java+Bidirectional+Map)という2つのマップを作成します。 – Andreas
アラバマ:モンゴメリー: アラスカ:ジュノー: アリゾナ州:フェニックス: アーカンソー:リトルロック: カリフォルニア:サクラメント: コロラド州:デンバー: コネチカット:ハートフォード: デラウェア:ドーバー: フロリダ:タラハシー: ジョージア州:アトランタ: – christopheUS