Hello,
I wrote this, it works fine (except for double multiplications like 6 * 6 * 6 but codegym says that it comes from additions so i don't think this is the problem)
thanks :)
package com.codegym.task.task19.task1914;
/*
Problem solving
*/
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
public static TestString testString = new TestString();
public static void main(String[] args) {
PrintStream consoleStream = System.out;
ByteArrayOutputStream results = new ByteArrayOutputStream();
PrintStream stream = new PrintStream(results);
System.setOut(stream);
testString.printSomething();
String result = results.toString();
ArrayList<Object> terms = new ArrayList<>(Arrays.asList(result.split(" ")));
ArrayList<Integer> onlyInt = new ArrayList<>();
for (Object o : terms) {
}
int operationResult = 0;
for (int i = 0; i < terms.size(); i++) {
Object o = terms.get(i);
if (o == null) continue;
if (o.toString().equals("*") && i > 0) {
onlyInt.add(Integer.parseInt(terms.get(i - 1).toString()) * Integer.parseInt(terms.get(i + 1).toString()));
terms.set(i - 1, null);
terms.set(i, null);
terms.set(i + 1, null);
}
}
for (int i = 0; i < terms.size(); i++) {
Object o = terms.get(i);
if (o == null) continue;
Integer term = null;
try {
term = Integer.parseInt(o.toString());
}
catch (Exception ignored) {}
if (o.toString().equals("-") && i < terms.size() - 1) {
onlyInt.add(-Integer.parseInt(terms.get(i + 1).toString()));
terms.set(i, null);
terms.set(i + 1, null);
}
else if (o.toString().equals("+") && i < terms.size() - 1) {
if (terms.get(i + 1) == null) continue;
onlyInt.add(Integer.parseInt(terms.get(i + 1).toString()));
terms.set(i, null);
terms.set(i + 1, null);
}
else if (term != null) {
onlyInt.add(term);
}
}
for (Integer i : onlyInt) {
operationResult += i;
}
System.setOut(consoleStream);
result = result.substring(0, result.length() - 2) + operationResult;
System.out.println(result);
}
public static class TestString {
public void printSomething() {
System.out.println("3 + 6 = ");
}
}
}