在我的程序中,我允许用户在Scanner中为书店输入信息,并用它来计算。我遇到麻烦的部分是当用户输入图书的费用时,程序崩溃,因为它没有占用“$”,因为成本是双倍的。我想也许我可以抛出异常或什么?或者可能将成本转换为搜索“$”的字符串,然后将成本转回为双倍,因为计算需要它。有什么想法吗?
到目前为止我所拥有的:
public static final String SENTINEL = "N"; // for sentinel
public static void main(String[]args){
Scanner input = new Scanner(System.in); // initializing Scanner
userInput(input);
}
public static void userInput(Scanner input){
// Initializing variables
System.out.print("Do you want to add a book order? (Enter Y for yes/ N for no): ");
String userInput = input.next();
String code = "";
double cost = 0.0; // this is the variable im talking about
int numBooks = 0;
int enroll = 0;
String reqOp = "";
String newUse = "";
int count = 0;
while(!userInput.equals(SENTINEL)){ // while userInput does not equal "quit" continue
System.out.print("Code: ");
code = input.next(); // accepting user input
System.out.print("Cost of single copy: " );
cost = input.nextDouble(); // here is where I am having issues
/* I was thinking of putting in an if statment that would be
if( user inputs a $) then{
throw something
}
But Im not sure what exactly to put in the if statment
or what i should throw */
System.out.print("Current number of books: ");
numBooks = input.nextInt();
System.out.print("Prospective class enrollment: ");
enroll = input.nextInt();
System.out.print("Is this Required or Optional?(Enter R or O): ");
reqOp = input.next();
System.out.print("Is it New or Used?(Enter N or U): ");
newUse = input.next();
答案 0 :(得分:0)
您可以使用正则表达式来过滤next
的值,然后再将其转换为double,而不是使用nextDouble
。
cost = Double.parseDouble(input.next().replaceAll("[^\\d.]+", ""));
这将转换" $ 13,465,398.09"到" 13465398.09"。
答案 1 :(得分:0)
你可以抓住InputMismatchException
并使用消息终止程序,或者你可以给cost
一些其他值:
try {
userExtraPercent = input.nextDouble();
} catch (InputMismatchException e){
System.out.println("Bad input");
return;
}
或者,就像你说的那样,你可以允许一个$,但是你必须进行一些其他解析(例如用next()
读取并过滤掉坏字符),如{{ 1}}不起作用。
答案 2 :(得分:0)
继承我的最终代码
code = input.next(); // accepting user input
System.out.print("Cost of single copy: " );
cost1 = input.next().replaceAll("[^\\d.]+", ""); // Accounting for $
double cost = Double.parseDouble(cost1); // converting cost to double