[英]Java skipping over a print statement scanner, specific
所以我的问题是,我想请求使用Scanner的输入,但是根本无法打印出来。 当显示跳过的扫描器的值时, Scanner cheeseType = new Scanner(System.in);
,我得到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
);
}
}
被跳过的是:
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
如您所见,它从比萨大小扫描仪直接跳到配料扫描仪的数量,而不是按顺序排列。 我不知道为什么,或者我应该怎么做才能解决这个问题。
由于您要在下一个问题之后关闭括号,因此仅在使用大披萨
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之后加上右括号,则可以继续。 不过,您仍然必须在其他地方修复缺少的括号。
在同一个输入流(您的情况下为System.in
。)上使用多个扫描仪不是一个好主意。 在方法开始时仅制作一台扫描仪:
Scanner scanner = new Scanner(System.in);
//read input with this here
scanner.close(); //also close it
编辑:斯蒂芬的答案是正确的,但这仍然是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.