2013-10-08 66 views
1
import java.util.Scanner; 

public class Improvedd { 
    public static void main (String[] args) { 

     Scanner input = new Scanner (System.in); 

     int operand1 = Integer.parseInt (input.nextLine()); 
     char expo1 = input.next().charAt (0); 
     int operand2 = Integer.parseInt (input.nextLine()); 
     String expression = "operand1 + expo1 + operand2"; 

     // how would I make it so the program ask for a math function 
     // Like just let them enter 1/2 and get the printed result 
     // I don't understand how I could just get the string to equal 
     // what I've placed 

     System.out.println ("Enter expression: "); 
     String expression = input.nextLine(); 

     System.out.println (operand1 + expo1 + operand2 + "="); 

     // if (expo1 == '/' && operand2 == '0') { 
     // System.out.println ("Cannot divide by zero"); } 
     // how could I fix this expression 

     if (expo1 == '-') { 
      System.out.println (operand1-operand2); 
     } else 
     if (expo1 == '+') { 
      System.out.println (operand1+operand2); 
     } else 
     if (expo1 == '/') { 
      System.out.println (operand1/operand2); 
     } else 
     if (expo1 == '%') { 
      System.out.println (operand1%operand2); 
     } 
     else{ 
      System.out.println ("Error.Invalid operator."); 
     } 
    } 
} 

我想要做的几乎是进入数学运算出现,只是让他们进入操作是它,%等,但我希望他们输入它像2/2或3%2,打印结果为2/2 = 1或3%2 = 1。我遇到的真正麻烦是设置字符串,我不知道如何设置它。与字符串丢失

+0

你在出操作数注释块是一个int,所以它与0的比较,而不是与“0”这是个字符。 –

回答

0

根据操作拆分输入。使用正则表达式来拆分所有opeartions % * + - /

String regex = "(?<=op)|(?=op)".replace("op", "[-+*/()]"); 
String[] tokens = expression.split(regex); 

//The equation 
System.out.println (tokens[0] + tokens[1] + tokens[2] + "="); 

int operand1 = Integer.parseInt(tokens[0]); 
int expo1 = tokens[1] 
int operand2 = Integer.parseInt(tokens[2]); 

//If-else ladder or the switch-case to evaluate the operation and results.