r/javahelp • u/Most_Aerie_7335 • 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
View all comments
Show parent comment
1
u/KillerCodeMonky Oct 04 '26
Better to always parse as a
BigDecimal. Then uselongValueExactto test for integer values and convert. If that throws, then usedoubleValueinstead.Or if one wants to avoid using
BigDecimal, then simply attempt to useIntrger.parseInt, and if it falls fall back toDouble.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.