如何在计算中使用用户输入字符?

时间:2014-11-24 06:00:22

标签: java input char

如何接受符号(*,+或 - )并在java中进行计算?示例:

int n = 10;
int f = 10;
//sign is the user input for the character to be used in the calculation.

/* Insert something along the lines of int r = f sign n;
   if sign is equal to '-', then the result should be 0, 
   if sign is '+', result should be 20. 
   etc. */

2 个答案:

答案 0 :(得分:1)

您可以使用java.util.Scanner类来读取用户的输入,然后使用if..else if.. else条件或switch语句来执行算术。

Scanner scanner = new Scanner(System.in);
String operator = scanner.nextLine();
switch (operator) {
  case "+":
    r = f + n;
    break;
  case "-": 
    r = f - n;
    break;
  case "*":
    r = f * n;
    break;
  case "/":
    r = f / n;
    break;
  default:
    throw new IllegalArgumentException("Unknown operators.");
}

答案 1 :(得分:0)

提示用户输入符号并将其存储到变量中。例如,可变符号。使用条件语句。像:

if (sign=='+')
  r=n+f;
else if (sign=='e')
  r=n-f;
else if (sign=='*')
  r=n*f;

或使用开关盒。