public static void main(String[] args) {
try {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your calculation");
String text = scanner.nextLine();
for(int i = 0; i < text.length();i++) {
if(text.substring(i,i+1).equals("+")) {
String behind = text.substring(i-i,i);
String ahead = text.substring(i+1,text.length());
System.out.println(behind);
System.out.println(ahead);
}
if(text.substring(i,i+1).equals("-")) {
String behind = text.substring(i-i,i);
String ahead = text.substring(i+1,text.length());
}
}
} catch(Exception e) {
System.out.println(e.getMessage());
main(args);
}
}
I'm making a calculator that will take many inputs and operators. As illustrated above, the code is setup so that you can only type in two numbers, if I program it so that it will heck for the next operator, like 5+7-3, then it will work, but if I just type in 5+7, then I'll get an error.
What I have tried:
if(text.substring(i,i+1).equals("+")) {
String behind = text.substring(i-i,i);
String ahead = text.substring(i+1,text.indexOf("+"));
System.out.println(behind);
System.out.println(ahead);
}
if(text.substring(i,i+1).equals("-")) {
String behind = text.substring(i-i,i);
String ahead = text.substring(i+1,text.indexOf("-"));
}
If I tried this, then I'll have errors if I type in two numbers after. The other thing I'm confused about is what if the next operator is a + not a -, then I can't use the indexOf(); method.