Reputation: 7
So my problem is that I want to ask for input for using Scanner, but it just doesn't print out at all. And when it displays the value for the skipped Scanner, Scanner cheeseType = new Scanner(System.in);
, I get null.
package classesProject;
import java.util.Scanner;
class Pizza {
String size;
String cheese;
int numToppings;
double price = 0;
}
public class pizzaTime {
public static void main(String[] args) {
Pizza order1 = new Pizza();
double priceOfSize = 0;
double priceOfCheese = 0;
double priceOfToppings = 0;
System.out.println("Pizza size small, medium or large: ");
Scanner sizeAsker = new Scanner(System.in);
order1.size = sizeAsker.nextLine();
if(order1.size == "small") {
priceOfSize = 3.0;
} else if(order1.size == "medium") {
priceOfSize = 5.0;
} else if(order1.size == "large") {
priceOfSize = 7.0;
System.out.println("Cheese type: normal, xtra, or thic: ");
Scanner cheeseType = new Scanner(System.in);
order1.cheese = cheeseType.nextLine();
}if(order1.cheese == "normal") {
priceOfCheese = 0.0;
} else if(order1.cheese == "xtra") {
priceOfCheese = 0.5;
} else if(order1.cheese == "thic") {
priceOfCheese = 1.0;
}
System.out.println("Number of toppings: ");
Scanner toppingAsker = new Scanner(System.in);
order1.numToppings = toppingAsker.nextInt();
priceOfToppings = order1.numToppings * 0.25;
double orderTotalPrice = priceOfSize + priceOfCheese;
System.out.println("Pizza size: " + order1.size + "\n"
+ "Cheese type: " + order1.cheese + "\n"
+ "Number of toppings: " + order1.numToppings + "\n"
+ "Order total: " + orderTotalPrice
);
}
}
The one that gets skipped is:
System.out.println("Cheese type: normal, xtra, or thic: ");
Scanner cheeseType = new Scanner(System.in);
order1.cheese = cheeseType.nextLine();
Upon running, the console displays:
Pizza size small, medium or large:
small
Number of toppings:
2
Pizza size: small
Cheese type: null
Number of toppings: 2
Order total: 0.0
So as you can see, it jumps straight from the pizza size Scanner to the number of toppings Scanner, rather than going in the sequential order. I don't have any idea why, or what I should do to fix this.
Upvotes: 0
Views: 393
Reputation: 885
It's not a good idea to use multiple scanners on the same input stream (System.in
in your case). Make only one scanner in the beginning of the method:
Scanner scanner = new Scanner(System.in);
//read input with this here
scanner.close(); //also close it
Edit: Stefan's answer is the correct one, but this is still a good idea.
Upvotes: 0
Reputation: 2178
Since you are closing the bracket after the next question, this one is only asked with large pizza's
else if(order1.size == "large") {
priceOfSize = 7.0;
System.out.println("Cheese type: normal, xtra, or thic: ");
Scanner cheeseType = new Scanner(System.in);
order1.cheese = cheeseType.nextLine();
}
If you would put a closing bracket after priceOfSize = 7, you can continue. You will still have to fix the missing bracket elsewhere though.
Upvotes: 1