java中将字符串解析为布尔值的变量
我有以下简单的销售计划,但在围绕该计划创建重启循环时遇到了困难。我的主要问题是将布尔值从字符串转换为布尔值类型,我在Eclipse中遇到了一个错误,错误是“对于布尔值类型,parseBoolean(string)方法未定义”
然而,我在顶部定义了一个布尔变量,boolean tryAgain=false
由于某些原因,我无法设置用户输入扫描仪,使其在没有错误的情况下获取真值或假值。当我试图将下一行从用户强制转换为布尔值时,最后一行出现了错误
import java.util.Scanner;
public class Sales {
public static void main(String args[]) {
String item1, item2, item3; //Three vars for items
double price1, price2, price3; //Three vars for price
int quantity1, quantity2, quantity3; //Three vars for quantity
Scanner userInput = new Scanner(System.in); //Creates scanner for user input
double sum; //var for total before tax
double tax; //var for tax
double total; //var for total with tax
double tax_total; //var to calculate tax
boolean tryAgain = true; //boolean for try again loop to restart program
// First set of inputs
while (tryAgain) {
System.out.println("Please enter the first item: ");
item1 = userInput.nextLine();
System.out.println("Please enter the price of the first item: ");
price1 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity1 = userInput.nextInt();
// Second set of inputs
System.out.println("Please enter the second item: ");
item2 = userInput.next();
System.out.println("Please enter the price of the second item: ");
price2 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity2 = userInput.nextInt();
// Third set of inputs
System.out.println("Please enter the third item: ");
item3 = userInput.next(); //skipping over item 2. Why?
System.out.println("Please enter the price of the third item: ");
price3 = userInput.nextDouble();
System.out.println("Please enter the quantity purchased: ");
quantity3 = userInput.nextInt();
System.out.println("Please enter the sales tax rate: "); //Prompt user for tax rate
tax = userInput.nextDouble();
//Print line item totals
System.out.println("Line item totals");
System.out.println("____________________");
System.out.println("Item 1: " + item1 + "\t" + "$" + price1);
System.out.println("Item 2: " + item2 + "\t" + "$" + price2);
System.out.println("Item 3: " + item3 + "\t" + "$" + price3);
System.out.println();
//Process final output for display
sum = price1 + price2 + price3;
total = (sum * tax) + sum;
tax_total = tax * sum;
System.out.println("Total cost(no tax):\t" + "$" + sum); //display total cost witout tax
System.out.println("Total tax(" + tax + " rate): \t" + "$" + tax_total); //display total tax
System.out.println("Total cost(with tax):\t" + "$" + total); //display total with tax
System.out.println();
System.out.println("Program created by James Bellamy");
System.out.println("Do you want to run the program again? (True or False)");
tryAgain = Boolean.parseBoolean(userInput.nextLine());
}
}
}
# 1 楼答案
它给您带来麻烦的原因是,当用户输入一个double,然后点击enter时,两个东西刚刚被输入——double和一个“换行符”,即\n
您正在调用的方法“nextDouble()”只读取double,这将在输入流中保留换行符。但是调用nextLine()确实会读取换行符,这就是为什么在代码运行之前必须调用nextLine()
将这一行添加到最后一行之前
# 2 楼答案
Scanner
支持nextBoolean()
。只要使用它: