Click here to Skip to main content
15,884,869 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
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:

Java
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.
Posted
Updated 11-Feb-18 8:18am
v2
Comments
PIEBALDconsult 11-Feb-18 18:18pm    
I recommend looking into the Shunting Yard algorithm or simply using a Regular Expression.
https://en.wikipedia.org/wiki/Shunting-yard_algorithm
Ziee-M 12-Feb-18 5:45am    
HI, you have few errors, String behind = text.substring(i-i,i) =>text.substring(i-1,i) otherwise you will get many characters instead of 1.
You have to make a trim() to your main text before you start working with it.
In addition, you have to start your analyse from index 1 not index 0 => you can add
if(i == 0)
{
continue; //ignore first loop. => now you have to add a validation to not allow user to insert an operator in the first element !
}
Otherwise you will have an error when an operator is inserted in the begining.
Finally, your work seems intressting, but you have to create methods instead of writing your code in the main, try to organise and your code will be much clearer and easier to modifiy and maintain.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900