ich ein Kartenobjekt mit Keys haben/Werte definiert als US State/Kapital (zB Texas/Austin)Finden Schlüssel/Wert in einem Map-Objekt und zurück jeweiligen Wert/Schlüssel
Wenn der Benutzer einen Staat geben Ich brauche um das Kapital zurückzugeben und wenn der Benutzertyp ein Kapital gibt ich den Zustand zurück
Ich habe Folgendes codiert, aber es funktioniert nur im Kapital -> Staaten Vergleich.
Irgendeine Idee, was ist los?
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);}
}
}
}
Wie sehen die Daten in der Datei aus? Können Sie uns ein Beispiel geben? –
Erstellen Sie zwei Karten, eine für jede Richtung, oder google "[Java Bidirectional Map] (https://www.google.com/search?q=Java+Bidirektional+Map)". – Andreas
Alabama: Montgomery: Alaska: Juneau: Arizona: Phoenix: Arkansas: Little Rock: Kalifornien: Sacramento: Colorado: Denver: Connecticut: Hartford: Delaware Dover: Florida: Tallahassee: Georgia: Atlanta : – christopheUS