Reputation: 23
I'd like to ask a question about my code.
I apologize for the inefficiency and the messiness of it, I am still trying to learn java.
System.out.println("Please choose the number corresponding to the operation: ");
System.out.println("1 for add,2 for subtract,3 for multiply, 4 for divide, 5 for print, and 6 for exit: ");
if (sc.nextInt() == 5) {
System.out.println("Your first fraction is: " + num1 + "/" + denom1 + " or in decimal: " + ((float) num1 / denom1));
System.out.println("Your second fraction is: " + num2 + "/" + denom2 + " or in decimal: " + ((float) num2 / denom2));
} else if (sc.nextInt() == 3) {
System.out.println("Multiply: " + (num1 * num2) + "/" + (denom1 * denom2));
} else if (sc.nextInt() == 4) {
System.out.println("Divide: " + (num1 * denom2) + "/" + (denom1 * num1));
} else if (sc.nextInt() == 1) {
int d = denom1 * denom2;
int n1 = num1 * denom2;
int n2 = num2 * denom1;
System.out.println("Addition: " + (n1 + n2) + "/" + d);
} else if (sc.nextInt() == 2) {
int d = denom1 * denom2;
int n1 = num1 * denom2;
int n2 = num2 * denom1;
System.out.println("Subtract: " + (n1 - n2) + "/" + d);
}
else if (sc.nextInt() == 6 ) {
System.exit(0);
}
}
}
When I run the program, the first if statement gets by fine, as I only have to input the number 5 one time. However as you can see from the second else if statement which is the number 3 requires two inputs, I have to enter it two times before the next line comes up. The third else if statement which is the number 4 requires 3 inputs before the next line shows up, and so on with each successive else if statement. I'm sorry if I am not explaining this properly, Does anyone have any idea why this is happening?
Upvotes: 2
Views: 915
Reputation: 129
Try to use switch statement.
package practice;
import java.util.Scanner;
public class Stack{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("ENTER THE 2 NUMBERS");
int num1=sc.nextInt();
int num2=sc.nextInt();
System.out.println("ENTER THE CHOICE");
int choice='0';
while(choice!=6)
{
choice=sc.nextInt();
System.out.println(choice);
switch(choice)
{
case 1:
int add=num1+num2;
System.out.println("Addition:"+add);
break;
case 2:
System.out.println("Subtract:");
break;
case 3:
System.out.println("Multiply:");
break;
case 4:
System.out.println("Divide:");
break;
case 5:
System.out.println("Your first fraction is:");
System.out.println("Your second fraction is:");
break;
case 6:
System.exit(0);
break;
default:
System.out.println("LOSER");
break;
}
}
sc.close();
}
}
Upvotes: 0
Reputation: 69440
Change your code to:
int input = sc.nextInt();
sc.nextLine();
if (input == 5) {
and all other if (sc.nextInt()...)
also.
nextInt
will consume your input. So if you come to the second if
the input is alredy consumed by the first if
.
nextLine
is nessesary to consume the <ENTER>
after the int value.
Upvotes: 3