Я бы порекомендовал начать с «0 +», за которым следуют все введенные пользователем. Потому что тогда вам не нужна специальная обработка первого числа.
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the expression: ");
// Start with "0 +"
int value = 0;
String operator = "+";
while (true) // loop
{
int operand = scan.nextInt();
switch (operator)
{
case "+": value += operand; break;
case "-": value -= operand; break;
case "*": value *= operand; break;
case "/": value /= operand; break;
case "%": value %= operand; break;
default: throw new UnsupportedOperationException(operator);
}
operator = scan.next();
if (".".equals(operator))
{
break; // exit the loop
}
}
System.out.println("result=" + value);
scan.close();
}
}
Однако этот алгоритм не заботится о математических правилах порядка операторов. он просто обрабатывает ввод слева направо, как дешевый карманный калькулятор за 3 €.
Другой пример, основанный на вашей конструкции и методах if-else:
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the expression: ");
// Start with "0 +"
int value = 0;
char operator = '+';
while (true) // loop
{
int operand = scan.nextInt();
if (operator == '+') {
value=add(value, operand);
} else if (operator == '-') {
value=subtract(value, operand);
} else if (operator == '*') {
value=multiply(value, operand);
} else if (operator == '/') {
value=divide(value, operand);
} else if (operator == '%') {
value=modulus(value, operand);
} else {
throw new UnsupportedOperationException(String.valueOf(operator));
}
operator = scan.next().charAt(0);
if (operator=='.')
{
break; // exit the loop
}
}
System.out.println("result=" + value);
scan.close();
}
static int add(int num1, int num2) {
return (num1 + num2);
}
static int subtract(int num1, int num2) {
return (num1 - num2);
}
static int divide(int num1, int num2) {
return (num1/num2);
}
static int multiply(int num1, int num2) {
return (num1*num2);
}
static int modulus(int num1, int num2) {
return (num1%num2);
}
}