lundi 17 février 2020

How to update output with continuous user inputs until terminated with "."?

New to Java and trying to figure out how to keep a running evaluated expression given by a user continuously until they type in "." to terminate it and then print the output. I need to use methods outside of the main that I have already placed.I don't have to worry about order of operation but I'm confused on how to take on a continuous amount of operations/numbers while keeping track of their outputs and then how to finally print the result when they put ".".

import java.util.Scanner;

public class Evaluator {
public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    int num1;
    char expression;
    int num2;
    String numlist = "";

    System.out.println("Enter the expression: ");
    num1 = scan.nextInt();
    expression = scan.next().charAt(0);
    num2 = scan.nextInt();
    scan.close();

    if (expression == '+') {
        add(num1, num2);
    } else if (expression == '-') {
        subtract(num1, num2);
    } else if (expression == '*') {
        multiply(num1, num2);
}else if (expression == '/') {
        divide(num1, num2);
    } else if (expression == '%') {
        modulus(num1, num2);
    } else if (expression == '.'){

    }
}

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);
}

}

OUTPUT:

Enter the expression:

1 + 26 * 2 % 19 / 5 .

The result is 3

Aucun commentaire:

Enregistrer un commentaire