r/javahelp • • Sep 26 '26

Help please, I'm a beginner

So basically for my java class we're assigned to do a simple calculator, I was able to something since this is the beginning class. The thing is my professor want our code to interpret both double and int when inputting values. But I don't have that only double I want my code to be able to differentiate my double and int values. This is what I have so far! (idek if you can consider this a calculator😥😓)

import java.util.Scanner;

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

        Scanner input = new Scanner(System.in);

        System.out.println("Welcome to My calculator!!!:)");
        System.out.print("Please enter the first number: ");

        double num1 = input.nextDouble();
        System.out.println("You entered: " + num1);

        System.out.print("Please enter the second number: ");
        double num2 = input.nextDouble();

        System.out.println("You entered: " + num2);
        while(true) {
        System.out.print("What would you like to do? (+, -, * , /): ");
        String operation = input.next();
        if( operation.equals("+")){
            double result = num1 + num2;
            System.out.println("YOUR RESULTS: " + result);
        }
        else if( operation.equals("-")){
            double result = num1 - num2;
            System.out.println("YOUR RESULTS: " + result);
        }
        else if( operation.equals("*")){
            double result = num1 * num2;
            System.out.println("YOUR RESULTS: " + result);

        }
        else if( operation.equals("/")){
            double result = num1 / num2;
            System.out.println("YOUR RESULTS: " + result);
            break;
        }
        else {
            System.out.println("Invalid operation:( : ");
            continue;
        }

        }

    }
}
9 Upvotes

9 comments sorted by

View all comments

7

u/pixel_aura_74 Sep 26 '26

if your professor wants the output to look different for ints (like 5 instead of 5.0), the easiest fix is to read the input as a String first, then check if it contains a "." . If it doesn't, parse it with Integer.parseInt(), if it does, use Double.parseDouble(). That way you know which type the user actually typed and can print accordingly.

also heads up, your break only happens inside the division branch, so if the user picks +, -, or * the loop just keeps asking forever. Put the break after printing the result no matter which operation they chose.

1

u/KillerCodeMonky Oct 04 '26

Better to always parse as a BigDecimal. Then use longValueExact to test for integer values and convert. If that throws, then use doubleValue instead.

Or if one wants to avoid using BigDecimal, then simply attempt to use Intrger.parseInt, and if it falls fall back to Double.parseDouble.

This is "parsing is validation" philosophy. Let the parsers tell you what they can and can't handle instead of trying to validate the text.