Java跳过特定的打印语句扫描程序

时间:2019-01-23 08:08:02

标签: java output java.util.scanner

所以我的问题是我想请求使用Scanner的输入,但根本无法打印出来。当它显示跳过的扫描器Scanner cheeseType = new Scanner(System.in);的值时,我为空。

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
                );

    }

}

被跳过的是:

System.out.println("Cheese type: normal, xtra, or thic: ");
Scanner cheeseType = new Scanner(System.in);
order1.cheese = cheeseType.nextLine();

运行时,控制台显示:

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

因此,如您所见,它从比萨大小扫描仪直接跳到配料扫描仪的数量,而不是按顺序排列。 我不知道为什么,或者要解决这个问题。

2 个答案:

答案 0 :(得分:1)

由于您在下一个问题之后关闭了括号,因此仅在大披萨的情况下才会询问该问题。

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();

    }

如果您要在priceOfSize = 7之后加上右括​​号,则可以继续。不过,您仍然必须在其他地方修复缺少的括号。

答案 1 :(得分:0)

在同一输入流(您的情况下为System.in)上使用多个扫描仪不是一个好主意。在方法开始时仅制作一台扫描仪:

Scanner scanner = new Scanner(System.in);
//read input with this here

scanner.close(); //also close it

编辑:斯蒂芬的答案是正确的,但这仍然是一个好主意。