+ 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

28th Dec 2016, 12:32 PM
Shoeb Quraishi
Shoeb Quraishi - avatar
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));
28th Dec 2016, 12:45 PM
Uran Kajtazaj
Uran Kajtazaj - avatar
+ 2
yes it will
28th Dec 2016, 4:58 PM
Uran Kajtazaj
Uran Kajtazaj - avatar
+ 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()); } }
28th Dec 2016, 1:17 PM
Uran Kajtazaj
Uran Kajtazaj - avatar
28th Dec 2016, 1:20 PM
Uran Kajtazaj
Uran Kajtazaj - avatar
+ 1
I would also suggest to use o_2 and n_2 because you sometimes things like o^+_2
30th Dec 2016, 10:20 AM
Roman Gräf
Roman Gräf - avatar
+ 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]) }
8th Jan 2017, 6:58 AM
MohammadAmin Salarkia
MohammadAmin Salarkia - avatar
+ 1
Along with mapping you can also utilize multi-dimensional arrays. Very similar.
9th Jan 2017, 7:43 AM
Spyke Olsen
Spyke Olsen - avatar
0
@uran will this work like if I type o2 or o.. then it will print oxygen??
28th Dec 2016, 1:02 PM
Shoeb Quraishi
Shoeb Quraishi - avatar
0
thanx bhaijaan it worked.. love u
28th Dec 2016, 6:34 PM
Shoeb Quraishi
Shoeb Quraishi - avatar
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/
8th Jan 2017, 4:22 AM
Turtle
0
@MohammadAmin The Code isn't working
8th Jan 2017, 7:40 AM
Shoeb Quraishi
Shoeb Quraishi - avatar