2013-11-13 3 views
-8
public class Calculator { 
     Double x; 
     /* 
     * Chops up input on ' ' then decides whether to add or multiply. 
     * If the string does not contain a valid format returns null. 
     */ 
     public Double x(String x){ 
      x.split(" "); 
      return new Double(0); 
     } 

     /* 
     * Adds the parameter x to the instance variable x and returns the answer as a Double. 
     */ 
     public Double x(Double x){ 
       System.out.println("== Adding =="); 
       if (x(1).equals("+")){ 
       x = x(0) + x(2); 
       } 
       return new Double(0); 
     } 

     /* 
     * Multiplies the parameter x by instance variable x and return the value as a Double. 
     */ 
     public Double x(double x){ 
       System.out.println("== Multiplying =="); 
       if(x(1).equals("x")){ 
        x = x(0) * x(2); 
       } 
       return new Double(0); 
     } 

} 

Im пытается разбить двойное введенное («12 + 5») разделить его с помощью «», а затем сделать его + или x на основе второго значения, а затем добавить или раз Результаты. Думал, что я мог бы это сделать, просто раскалываясь, а времена/добавляя, но не работаю.Калькулятор без использования более 1 переменной

+3

Yikes. Что именно вы пытаетесь выполнить, смешивая «двойные» и «двойные», особенно в таком удивительно противоречивом ключе? – Sneftel

+0

что это ... ??? : o – Ravi

+0

Вы видели, что вы тестируете 'Double.equals (String)'? Это компилируется, но не имеет шансов вернуть «true». –

ответ

2

Не похоже, что вы должным образом сохраняете результаты разделения строк.

x.split(" "); 

возвращает строку [] с каждой частью, разделенной на "", например.

String x = "1 x 2"; 
String[] split = x.split(" "); 

split[0] == "1"; 
split[1] == "x"; 
split[2] == "2"; 

Возможно, вам удастся использовать более описательные имена для ваших методов и переменных.

Что-то, как это будет, вероятно, работать:

public class Calculator { 
    public static int result; 

    public static void main(String[] args) 
    { 
     String expression = args[0]; 
     String[] terms = expression.split(" "); 
     int firstNumber = Integer.parseInt(terms[0]); 
     int secondNumber = Integer.parseInt(terms[2]); 
     String operator = terms[1]; 

     switch (operator) 
     { 
      case "*": 
       //multiply them 
       break; 
      case "+": 
       //add them 
       break; 
      case "-": 
       //subtract them 
       break; 
      case "/": 
       //divide them 
       break; 
     } 
    } 
} 
Смежные вопросы