My program seems to be working fine except that when it is supposed to loop back at the part asking user for operator the message shows but the is no room for user to input operator and it jumps directly to ask for first number, I do not know what I am doing wrong or not doing. I need help, please!
here is what I have so far:
import java.util.Scanner;
public class LabTresFinal
{
public static void main (String [] arguments)
{
Scanner Keyboard = new Scanner ( System.in );
//Declared Variables
String operator;
double more;
double number1;
double number2;
double ans;
boolean flag= true;
do
{
//Prompt user for operation and numbers
//Had to prompt for operation first otherwise my program was not runing correctly
System.out.println( "Please choose an operation to be performed: + , - , * , / , or % .");
operator = Keyboard.nextLine();
System.out.println("Enter first number");
number1 = Keyboard.nextDouble ();
System.out.println("Enter second number");
number2 = Keyboard.nextDouble ();
switch (operator)
{
case ("+"):
ans = number1 + number2;
System.out.println(number1 + " + " + number2 + " = " + ans);
break;
case ("-"):
ans = number1 - number2;
System.out.println(number1 + " - " + number2 + " = " + ans);
break;
case ("*"):
ans = number1 * number2;
System.out.println(number1 + " * " + number2 + " = " + ans);
break;
case ("/"):
if (number2 >= 1)
{
ans = number1 / number2;
System.out.println(number1 + " / " + number2 + " = " + ans);
}else if (number2 ==0)
{
System.out.println("Error: Operation cannot be performed with second number as zero, please try again");
while(flag)
{
System.out.println("Enter second number");
number2 = Keyboard.nextDouble ();
if(number2>=1)
{
ans = number1 / number2;
System.out.println(number1 + " / " + number2 + " = " + ans);
flag=false;
}else if(number2 ==0)
{
System.out.println("Error: Operation cannot be performed with second number as zero, please try again");
}
}
}
break;
case ("%"):
ans = number1 % number2;
System.out.println(number1 + " % " + number2 + " = " + ans);
break;
}
//setting loop for program to restart if user wants to
System.out.println("Again?"
+ "\n" + "enter 1 for yes"
+ "\n" + "enter 2 for no");
more = Keyboard.nextDouble();
}while (more== 1);
} }
this is what my program is supposed to do :
It must:
- CLI based
- Keep running totals for each operator (How many additions, how many multiplications, …)
- Prompt user for 2 numbers
- Prompt user for operator
- Handle the case of divide by zero
- Perform the operation
- Display the result on the screen to the user
- Loop until the user uses a sentinel value
- Display statistics: count for each operation, minimum value, maximum value.
I know i still need to work a lot on it but i just need help on solving this problem for now so i can work on the rest.
Thank you so much.