lundi 28 septembre 2020

Simple Calculator problem Runtime Error (java)

I'm pretty new to Java coding and I code this Simple Calculator and it works perfectly in my IDE but it shows Runtime Error when I put in the online judge system. Very appreciated If you can provide any helps on this!

import java.util.Scanner;
import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        Scanner calc = new Scanner(System.in);
        String operator1, operator2;
        int firstNum, secondNum;

        ArrayList<String> equation = new ArrayList<>();

        while(true) {

            String temp = calc.nextLine();
            if(temp.equals("0"))
                break;
            equation.add(temp);

        }
        for(String temp:equation) {
            if(temp.contains(" + ")) {
                operator1 = temp.substring(0,temp.indexOf('+'));
                operator2 = temp.substring(temp.indexOf('+')+1);
                firstNum = Integer.parseInt(operator1.trim());
                secondNum = Integer.parseInt(operator2.trim());
                System.out.println(firstNum + secondNum);
            }
            if(temp.contains(" * ")) {
                operator1 = temp.substring(0, temp.indexOf('*'));
                operator2 = temp.substring(temp.indexOf('*') + 1);
                firstNum = Integer.parseInt(operator1.trim());
                secondNum = Integer.parseInt(operator2.trim());
                System.out.println(firstNum * secondNum);
            }
            if(temp.contains(" - ")) {
                operator1 = temp.substring(0,temp.indexOf('-'));
                operator2 = temp.substring(temp.indexOf('-')+1);
                firstNum = Integer.parseInt(operator1.trim());
                secondNum = Integer.parseInt(operator2.trim());
                System.out.println(firstNum - secondNum);
            }
            if(temp.contains(" / ")) {
                operator1 = temp.substring(0,temp.indexOf('/'));
                operator2 = temp.substring(temp.indexOf('/')+1);
                firstNum = Integer.parseInt(operator1.trim());
                secondNum = Integer.parseInt(operator2.trim());
                System.out.println(firstNum / secondNum);
            }
        }
        System.out.println("Bye");
    }

}

Aucun commentaire:

Enregistrer un commentaire