2013-10-29 26 views
-1

我需要一個Java程序,它在命令提示符下充當計算器。我可以想出這個,但我必須一次輸入一個問題(輸入「2」,按回車,輸入「+」,按回車,輸入「2」,按回車),我想要知道我是否可以將它放在「2 + 2」的位置。預先感謝任何幫助!Java命令提示符計算器 - 作業

import java.util.*; 

public class memCalc 
{ 
    public static void main (String args[]) 
    { 
     Scanner input = new Scanner(System.in); 
     String op; 
     int numberOne, numberTwo, result = 0; 
     numberOne = input.nextInt(); 
     op = input.next(); 
     numberTwo = input.nextInt(); 
     if (op.equals("+")) 
     { 
      result = numberOne + numberTwo; 
      System.out.print("The answer is: " + result + " .\n"); 
     } 
     else if (op.equals("-")) 
     { 
      result = numberOne - numberTwo; 
      System.out.print("The answer is: " + result + " .\n"); 
     } 
     else if (op.equals("*")) 
     { 
      result = numberOne * numberTwo; 
      System.out.print("The answer is: " + result + " .\n"); 
     } 
     else if (op.equals("/")) 
     { 
      result = numberOne/numberTwo; 
      System.out.print("The answer is: " + result + " .\n"); 
     } 
    } 
} 
+0

我不認爲這個問題一定值得向下票,只是更多的解釋。你已經說明了你正在努力達到的目標,並且你發佈了一些我認爲你想修改的代碼,以便匹配。有人說,你有沒有嘗試過任何東西?這裏真正需要的只是一些簡單的解析。 –

+0

@JoshM我真的不知道該怎麼嘗試。即使有人告訴我,我需要研究什麼會有所幫助:) – gdhc21

+2

只要嘗試一些對您有意義的事情。做一些實驗。提示用戶輸入表達式,然後使用空格分隔符調用'Scanner#nextLine()'和'String#split(String)'。 'split [0]'是第一個數字,'split [1]'是操作,'split [2]'是第二個數字。 –

回答

0

這不是最好的解決方案......但它的工作原理。基本上我只是把用戶輸入的全部內容放到一個字符串中,然後找到運算符的位置,然後使用操作的位置找到2個數字並將它們放入一個int。之後,我使用子字符串將運算符放入字符串中。然後,這就是你得到的。

這是不是最好的代碼...但跳這有助於

public static void main (String args[]) 
{ 
    Scanner input = new Scanner(System.in); 
    String equation = input.nextLine(); 
    int opLocation = equation.indexOf("+"); 
    if(opLocation == -1) 
    { 
     opLocation = equation.indexOf("-"); 
    } 
    if(opLocation == -1) 
    { 
     opLocation = equation.indexOf("*"); 
    } 
    if(opLocation == -1) 
    { 
     opLocation = equation.indexOf("/"); 
    } 
    String number = equation.substring(0,opLocation); 
    int numberOne = Integer.parseInt(number); 
    number = equation.substring(opLocation + 1); 
    int numberTwo = Integer.parseInt(number); 
    String op = equation.substring(opLocation,opLocation+1); 
    int result; 
    if (op.equals("+")) 
    { 
     result = numberOne + numberTwo; 
     System.out.print("The answer is: " + result + " .\n"); 
    } 
    else if (op.equals("-")) 
    { 
     result = numberOne - numberTwo; 
     System.out.print("The answer is: " + result + " .\n"); 
    } 
    else if (op.equals("*")) 
    { 
     result = numberOne * numberTwo; 
     System.out.print("The answer is: " + result + " .\n"); 
    } 
    else if (op.equals("/")) 
    { 
     result = numberOne/numberTwo; 
     System.out.print("The answer is: " + result + " .\n"); 
    } 
}