Split string calculator

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • zakratcliffe
    New Member
    • Oct 2015
    • 1

    Split string calculator

    I have this code
    Code:
     
    	import java.util.Scanner;
    public class Calculator {
    
    	public static void main(String[] args) {
    		
    	      Scanner scan = new Scanner(System.in) ;
    	      System.out.println("Enter your two numbers and the operation with spaces between e.g 8 9 -");
    	      
    	      String calculation=scan.nextLine();
    	      
    	      String [] parts = calculation.split(" ");
    	      
    	       //Add
    	        if (parts[2].equals("+")) {
    	            String ans = parts[0] + parts[1];
    	        }
    
    	        //Subtract
    	        else if (parts[2].equals("-")) {
    	            String ans = parts[0] - parts[1];
    	        }
    
    	        //Multiply
    	        else if (parts[2].equals("*")) {
    	            String ans = parts[0] * parts[1];
    	        }
    
    	        //Divide
    	        else if (parts[2].equals("/")) {
    	        	String ans = parts[0] / parts[1];
    	        }
    	      
    	}
    
    }
    the error is within the if statements regarding -, * and / operations "The operator / is undefined for the argument type(s) java.lang.Strin g, java.lang.Strin g" can anyone help
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    "parts" is an array of Strings, not numbers!
    You cannot subtract/divide/multiply strings, so you have to convert it to a number before:
    Code:
    String s="12";
    int i = Integer.parseInt(s);
    Remark: you can add strings, but this is the concat operation. So "1"+"2" would give you "12" and not 3!

    Also, the result of dividing an int with another int gives you an int, not a String.
    You can convert the result to a String using the valueOf() method.
    So in your case, change line 31 to:
    Code:
    String ans = String.valueOf(Integer.parseInt(parts[0]) / Integer.parseInt(parts[1]));

    Comment

    Working...