Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

Hi, I am trying to print the name of an item of integer array, where item is a name given to math expression(sum etc) [closed]

Writer Matthew Barrera

System.out.println("Enter two numbers (aa,bb): ");

 int aa = sc.nextInt(); int bb = sc.nextInt(); int sum = aa + bb, sub = aa - bb, mult = aa * bb, div = aa / bb, mod = aa % bb; int[] operation = { sum, sub, mult, div, mod }; for (int arr : operation) { System.out.println( arr+" of " + aa + " and " + bb + " is : " + arr); }
0

1 Answer

Items in the array have no name. Only indices. Which you don't have with a for-each loop. Option 1 (and my prefence) use a Map instead. Like,

Map<String, Integer> operMap = new HashMap<>();
operMap.put("sum", sum);
operMap.put("sub", sub);
operMap.put("mult", mult);
operMap.put("div", div);
operMap.put("mod", mod);
for (Map.Entry<String, Integer> e : operMap.entrySet()) { System.out.println(e.getKey() + " of " + aa + " and " + bb + " is : " + e.getValue());
}

Option 2 use parallel arrays. Like,

String[] operName = { "sum", "sub", "mult", "div", "mod" };
int[] operation = { sum, sub, mult, div, mod };
for (int i = 0; i < operation.length; i++) { System.out.println(operName[i] + " of " + aa + " and " + bb + " is : " + operation[i]);
}
1