My program asks for 3 inputs, num1, num2 and math operator in this order. All of those are strings. My If statement is checking if the input for num1 or num2 was not a math operator.
import java.text.DecimalFormat;
import java.util.*; public class assignment {
public static void main (String[] args) {
Scanner scan = new Scanner (System.in);
int sum, HighRes, LowRes, Agg, Ave, Amount, Wrong, Right;
String operator, another = "y", num1, num2;
HighRes = 0;
LowRes = 0;
Agg = 0;
Amount = 0;
DecimalFormat df = new DecimalFormat("#.00");
Wrong = 0;
Right = 0;
while (another.equalsIgnoreCase("y"))
{
System.out.println("Enter the first number, second number and the operator (+, -, * or /)");
num1 = scan.next();
num2 = scan.next();
operator =scan.next();
System.out.println( "Expression is " + num1 + " " +num2 + " " +operator);
if (num1 == "-" || num1 == "+" || num1 == "*" || num1 == "/" || num2 == "+" || num2 == "+" || num2 == "+" || num2 == "+"){
System.out.println("Invalid expression");
System.out.print ("Test another expression (Type Y if yes and leave empty if no?) ");
another = scan.nextLine();
Wrong++;
}
else {
int num3 = Integer.parseInt(num1);
int num4 = Integer.parseInt(num2);
I'm not advanced in programming so, I am sorry if my code makes you cringe. For me it seems that if the entered string for num1 and num2 is either -,+,* or /, it should print "Invalid expression" but what it does is giving me "java.lang.NumberFormatException" error
Line 35 and 36 are when I am converting the string to integer, and to me that should work since it's in the else statement and the If does not trigger
Aucun commentaire:
Enregistrer un commentaire