2013-10-08 4 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. Реальная проблема, с которой я столкнулась, - это установить строку, которая не поняла, как я могу ее установить.Lost with Strings

+0

Ваш operand2 в неработающей комментировал блок является ИНТ, поэтому сравнивать его с 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.