enheldel enheldel - 1 month ago 14
Java Question

Java - Advanced non-GUI calculator

I'm trying to make a pretty advanced non-GUI calculator in java, I'm able to type for example 5+5 on the same line and 10-5 etc by using string.split, however when I type for example -5-5 it crashes. How can I solve this? I'm pretty new to java.

else if(tal.contains("-") && !tal.contains("rand")){
delar = tal.split("\\-");
tal1 = Double.parseDouble(delar[0]);
tal2 = Double.parseDouble(delar[1]);
svar = tal1 - tal2;
System.out.println("Differensen är: " + svar);
}

Answer
else if(tal.contains("-") && !tal.contains("rand")){
        delar = tal.split("\\-");
        if (delar[0].equals("")) {
            tal1 = -1*Double.parseDouble(delar[1]);
            tal2 = Double.parseDouble(delar[2]);
        } else {
            tal1 = Double.parseDouble(delar[0]);
            tal2 = Double.parseDouble(delar[1]);
        }
        svar = tal1 - tal2;
        System.out.println("Differensen är: " + svar);
}

Will work. When you split on - you receive empty String in delar[0] when the String startsWith -.

Your problem is which is described by me here. Have a look on it. You'll learn how to solve such problems on your own.

Well, someone has suggested that the solution should accept multiple minuses. The following do:

else if(tal.contains("-") && !tal.contains("rand")){
        delar = tal.split("\\-");
        int i = 0;
        boolean firstMinus = false;
        while (delar[i].equals("")) {
            firstMinus = !firstMinus;
            i++;
        }
        if (firstMinus) {
            tal1 = -1*Double.parseDouble(delar[i]);
            tal2 = Double.parseDouble(delar[i+1]);
        } else {
            tal1 = Double.parseDouble(delar[i]);
            tal2 = Double.parseDouble(delar[i+1]);
        }
        svar = tal1 - tal2;
        System.out.println("Differensen är: " + svar);
}