2016-12-08 2 views
0

Я пытаюсь заставить свою программу обработать исключение, если пользователь ничего не вводит, поэтому они получат сообщение об ошибке «Ошибка, введите сумму в долларах больше 0» или «Ошибка, Введите 1, 2 или 3 ". В настоящее время, программа не делает ничего, если пользователь просто нажимает кнопку «войти» без входа ....Обработка исключений без ввода пользователем в Java

import java.util.Scanner; 
import java.util.*; 
import java.text.DecimalFormat; 

public class Candleline 
{ 
    public static void main(String[] args) 
    { 
     //initiate scanner 
     Scanner input = new Scanner(System.in); 

     System.out.println("\tCandleLine - Candles Online"); 
     System.out.println(" "); 

     //declare variables and call methods 
     double candleCost = getCandleCost(); 
     int shippingType = getShippingType(); 
     double shippingCost = getShippingCost(candleCost, shippingType); 


     output(candleCost, shippingCost); 

    } 

public static double getCandleCost() 
    { 
     //get candle cost and error check 
     Scanner input = new Scanner(System.in); 
     boolean done = false; 
     String inputCost; 
     double candleCost = 0; 
     while(!done) 
      { 
       System.out.print("Enter the cost of the candle order: "); 

       try 
       { 

        inputCost = input.next(); 
        candleCost = Double.parseDouble(inputCost); 
        if (inputCost == null) throw new InputMismatchException(); 
        if (candleCost <=0) throw new NumberFormatException(); 
        done = true; 
       } 
       catch(InputMismatchException e) 
       { 
        System.out.println("Error, enter a dollar amount greater than 0"); 
        input.nextLine(); 
       } 
       catch(NumberFormatException nfe) 
       { 
        System.out.println("Error, enter a dollar amount greater than 0"); 
        input.nextLine(); 
       } 

      } 
     return candleCost; 
    } 


    public static int getShippingType() 
     { 
      //get shipping type and error check 
      Scanner input = new Scanner(System.in); 
      boolean done = false; 
      String inputCost; 
      int shippingCost = 0; 
      while(!done) 
       { 
        System.out.println(" "); 
        System.out.print("Enter the type of shipping: \n\t1) Priority(Overnight) \n\t2) Express (2 business days) \n\t3) Standard (3 to 7 business days) \nEnter type number: "); 


        try 
        { 
         inputCost = input.next(); 
         shippingCost = Integer.parseInt(inputCost); 
         if (inputCost == null) throw new InputMismatchException(); 
         if (shippingCost <=0 || shippingCost >= 4) throw new NumberFormatException(); 
         done = true; 
        } 
        catch(InputMismatchException e) 
        { 
         System.out.println("Error, enter a 1, 2 or 3"); 
         input.nextLine(); 
        } 
        catch(NumberFormatException nfe) 
        { 
         System.out.println(" "); 
         System.out.println("Error, enter a 1, 2 or 3"); 
         input.nextLine(); 
        } 

       } 
      return shippingCost; 
    } 

    public static double getShippingCost(double candleCost, int shippingType) 
    { 
     //calculate shipping costs 
     double shippingCost = 0; 


     if (shippingType == 1) 
     { 
      shippingCost = 16.95; 
     } 
     if (shippingType == 2) 
     { 
      shippingCost = 13.95; 
     } 
     if (shippingType == 3) 
     { 
      shippingCost = 7.95; 
     } 
     if (candleCost >= 100 && shippingType == 3) 
     { 
      shippingCost = 0; 
     } 
     return shippingCost; 
} 

public static void output(double fCandleCost, double fShippingCost) 
{ 
     //display the candle cost, shipping cost, and total 
     Scanner input = new Scanner(System.in); 
     DecimalFormat currency = new DecimalFormat("$#,###.00"); 
     System.out.println(""); 
     System.out.println("The candle cost of " + currency.format(fCandleCost) + " plus the shipping cost of " + currency.format(fShippingCost) + " equals " + currency.format(fCandleCost+fShippingCost)); 
} 

} 

ответ

0

Заменить input.next();

с input.nextLine();

+0

Это было сделано! Спасибо!! – ecooper10

0

Вы можете написать method, который проверяет ввод перед продолжением. Он может продолжать запрашивать ввод, если пользователь вводит что-то недопустимое. Например. ниже пример демонстрирует, как подтвердить ввод integer:

private static int getInput(){ 
    System.out.print("Enter amount :"); 
    Scanner scanner = new Scanner(System.in); 
    int amount; 
    while(true){ 
     if(scanner.hasNextInt()){ 
      amount = scanner.nextInt(); 
      break; 
     }else{ 
      System.out.println("Invalid amount, enter again."); 
      scanner.next(); 
     } 
    } 
    scanner.close(); 
    return amount; 
} 
Смежные вопросы