+ 2
How to match the position of two array?
for example I have two arrays... and I want to print if the position of first array matches the position of another array, then the value from that particular array. example: String[] names = {"Oxygen","Nitrogen","Carbon","Hydrogen"}; String[] chemical = {"O2","N2","C","H"); Scanner input = new Scanner(System.in); System.out.println("Enter Your Chemical "); String myChem = input.nextLine(); //for(int i = 0; i < names.length; i++){ //System.out.println(chemical[i]); //} output if oxygen then o2
11 Antworten
+ 6
Thats why Maps exist
-------------
//Creating a Map
Map<KeyType, ValueType> mapName = new HashMap<>();
//Adding data
mapName.put(Key, Value);
//Getting the value
mapName.get(Key); //Returns the value of that key
-------------
Map<String, String> map = new HashMap<>();
map.put("Oxygen", "O2");
map.put("Nitrogen", "N2");
map.put("Carbon", "C");
map.put("Hydrogen", "H");
Scanner input = new Scanner(System.in);
System.out.print("Enter your chemical: ");
String myChem = input.nextLine();
System.out.println(map.get(myChem));
+ 2
yes it will
+ 1
You can do it like this
//Notice the lower case
map.put("oxygen", "o2");
map.put("nitrogen", "n2");
map.put("carbon", "c");
map.put("hydrogen", "h");
Scanner input = new Scanner(System.in);
System.out.print("Enter your chemical: ");
String myChem = input.nextLine();
//Then use a for loop like this, notice toLowerCase()
for (Map.Entry<String, String> m : map.entrySet()){
if (m.getValue().equals(myChem.toLowerCase())){
System.out.println(m.getKey().toUpperCase());
}else if (m.getKey().equals(myChem.toLowerCase())) {
System.out.println(m.getValue().toUpperCase());
}
}
+ 1
Look at the example
https://code.sololearn.com/c8g2iRO27DYg/#java
+ 1
I would also suggest to use o_2 and n_2 because you sometimes things like o^+_2
+ 1
If you don't want to use map you can use this code:
for(int i=0;i<names.length;i++){
if(names[i].equals(myChem))
System.out.println(chemical[i])
}
+ 1
Along with mapping you can also utilize multi-dimensional arrays. Very similar.
0
@uran will this work like if I type o2 or o.. then it will print oxygen??
0
thanx bhaijaan it worked.. love u
0
you don't need to use Hashmap. You can do it with few line of codes. Here http://www.sololearn.com/app/sololearn/playground/c7TZ1iCxxcQq/
0
@MohammadAmin The Code isn't working