In: Computer Science
Question for Java
String[] tokens = expression.split(" ");
for (String token : tokens) {
if (token.equals("+") || token.equals("-")) {
while (!ops.isEmpty() && (ops.peek() == '+' || ops.peek() == '-' || ops.peek() == '*' || ops.peek() == '/')) {
applyOp(values, ops);
}
What does the for (String tokens : token) mean?
What are the different ways to write this for loop?
String[] tokens = expression.split(" "); for (String token : tokens) { if (token.equals("+") || token.equals("-")) { while (!ops.isEmpty() && (ops.peek() == '+' || ops.peek() == '-' || ops.peek() == '*' || ops.peek() == '/')) { applyOp(values, ops); } What does the for (String tokens : tokens) mean? Answer: -------- tokens is an array so, with "for (String tokens : tokens)" we iterate through all Strings in tokens array and variable token contains the string in tokens array What are the different ways to write this for loop? Answer: --------- String token; for (int i = 0; i < tokens.length; i++) { token = tokens[i]; if (token.equals("+") || token.equals("-")) { while (!ops.isEmpty() && (ops.peek() == '+' || ops.peek() == '-' || ops.peek() == '*' || ops.peek() == '/')) { applyOp(values, ops); } } // This code is exactly as same as given code but uses a traditional for loop.