計算器詢問用戶兩個數字,但如果用戶選擇階乘運算符(!),我需要它僅向用戶請求一個數字。有人可以幫我弄這個嗎?Java計算器程序階乘
public static void main(String[] args) throws IOException {
Scanner in;
in = new Scanner(System.in);
char nextChar;
char oper;
int num1 = 0;
int num2 = 0;
int base = 2;
int exp = 10;
System.out.println("Please enter operator");
oper = in.nextLine().charAt(0);
System.out.println("The operator is " + oper);
System.out.println("Please enter the first number");
num1 = in.nextInt();
System.out.println("The first number is " + num1);
if (oper =='!')
{
System.out.println("Please enter the first number");
num1 = in.nextInt();
System.out.println("The first number is " + num1);
} else {
System.out.println("Please enter the second number");
num2 = in.nextInt();
System.out.println("The second number is " + num2);
}
switch (oper) {
case '+':
System.out.println("The answer is " + (num1 + num2));//addition
break;
case '-':
System.out.println("The answer is " + (num1 - num2));//subtraction
break;
case '*':
System.out.println("The answer is " + (num1 * num2));//multiplication
break;
case '/':
System.out.println("The answer is " + (num1/num2));//division
break;
case '%':
System.out.println("The answer is " + (num1 % num2));//remainder
break;
case 'p':
System.out.println("The answer is " + exponent(num1,num2));//exponent
break;
case '!':
System.out.println("The answer is "); //factorial
break;
case 'n':
System.out.println("The answer is "); //previous answer
break;
}
}
您是否自己嘗試過任何方法,或者您只是要求我們爲您編碼? – nhouser9
是的,上面的代碼是我嘗試過的,而不是隻要求用戶輸入一個數字,它仍然要求兩個 –
在上面的代碼中,你要求輸入,然後如果運算符是!你要求另一個輸入。 – nhouser9