[英]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.