2015-10-20 42 views
0

在我的程序中,我允许用户将信息输入到扫描仪中供书店使用,并用它来计算事物。我遇到的问题是,当用户输入本书的成本时,程序崩溃,因为它不包含“$”,因为成本是双倍。我想也许我可以抛出异常或什么?或者可能将成本转换为搜索“$”的字符串,然后将成本转换为双倍,因为它是计算所需的。有任何想法吗?抛出异常?忽略双重内容

继承人是我到目前为止有:

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

你也可以使用正则表达式将其转换成翻倍,而不是使用nextDouble之前过滤的next值。

cost = Double.parseDouble(input.next().replaceAll("[^\\d.]+", "")); 

这将转换 “13,465,398.09 $” 为 “13465398.09”。

+0

这个工作!谢谢,绝对是超越它! – thatsnifty

0

你可以赶上InputMismatchException,要么与消息终止程序,或者你可以给cost一些其他的价值:

try { 
    userExtraPercent = input.nextDouble(); 
} catch (InputMismatchException e){ 
    System.out.println("Bad input"); 
    return; 
} 

或者,就像你说的,你可以让一个$,但你” d必须在其他解析中(如使用next()读取并过滤出错误字符),因为nextDouble()不起作用。

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