而& do-while循环,用户决定再次运行程序

时间:2016-03-04 21:38:01

标签: java while-loop do-while

我的餐厅分配有问题 - 我需要

  1. 创建一个while循环,其中包含用户购买的所需数量,介于1到15之间。用户有3次尝试,如果在第三次之后他没有输入正确的数量1

    < / LI>
  2. 使用do-while循环用户必须回答是否要再次运行程序。如果他回答“Y&#39; (是的)它再次运行,如果答案是'N&#39; N&#39; (不)它终止。

  3. 我不断收到错误:while循环只执行2次尝试,而do while根本不起作用。

        import java.text.DecimalFormat;
        import java.util.Scanner;
    
        public class newone {
           public static void main (String[] args){
             char repeat;             
             // To hold 'y' or 'n'      
             String input;      
    
            DecimalFormat df = new DecimalFormat("$0.00");
            //to use: df.format(doubleVariable)
    
            //Display any welcome message at the top of the output screen
            System.out.println("Welcome!");
    
            double price = 5.0;
            System.out.println("Burger is " + df.format(price));
    
            Scanner keyboard = new Scanner(System.in); 
    
                int attempts = 0;
                int maxAttempts = 3;
                int quantity;
    
                System.out.print("Enter amount of burgers: ");
    
                quantity = keyboard.nextInt();
            //LESS THAN OR EQUAL TO 3... 
            while(quantity <1 || quantity >=15 && attempts<=maxAttempts){
    
                if(quantity < 1 || quantity >= 15){
    
                    System.out.println("That is an invalid amount, please try  again");
                        quantity= keyboard.nextInt();
                        ++attempts;
                        }
                        else if(quantity>1 && quantity<15){
    
                    //user entered a valid amount  
                    System.out.println("The amount is valid. You ordered: "+ quantity);
                    double subTotal = quantity * price;
                }
    
                while (attempts>=maxAttempts){
                    System.out.println("Too many attempts, you can't order");
                    break;
                    }
                }
    
             do{ 
         System.out.println("Would you like to run the program again?");        
         System.out.print("Enter Y for yes or N for no: "); 
         input = keyboard.nextLine();    // Read a line.     
         repeat = input.charAt(0);       // Get the first char.   
         } 
    //it gives me an error Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
        at java.lang.String.charAt(Unknown Source)
    
         while (repeat == 'Y' || repeat == 'y'); 
    
    
    
                }
            }}
    

2 个答案:

答案 0 :(得分:0)

下面的行会导致错误:

repeat = input.charAt(0);

也许用户没有提供任何输入(即当程序要求输入时用户只是输入),因此string没有任何字符。从空白字符串中提取第一个字符会引发此错误。

解决方案是在执行length()之前检查空字符串(使用charAt(0)方法)。

答案 1 :(得分:-2)

这里有很多问题。

以下是我的表现。了解分解和编写干净,可读的代码永远不会太早:

/**
 * Created by Michael
 * Creation date 3/4/2016.
 * @link https://stackoverflow.com/questions/35806509/java-while-do-while-loop-with-users-decision-to-run-program-again/35806638?noredirect=1#comment59284245_35806638
 */

import java.text.NumberFormat;
import java.util.Scanner;

public class BurgerKing {

    public static final int MAX_ATTEMPTS = 3;
    public static final int MIN_QUANTITY = 1;
    public static final int MAX_QUANTITY = 15;
    public static final NumberFormat PRICE_FORMAT = NumberFormat.getCurrencyInstance();

    public static void main (String[] args){

        Scanner keyboard = new Scanner(System.in);
        String answer;
        do {
            System.out.println("Welcome!  Please place your order");
            int quantity = getBurgerQuantity(keyboard);
            double price = getBurgerPrice(keyboard);
            System.out.println(String.format("Your total is: %s", PRICE_FORMAT.format(quantity*price)));
            System.out.print("Another order? [Y/N]: ");
            answer = keyboard.nextLine();
        } while ("Y".equalsIgnoreCase(answer));
    }

    public static boolean isValidQuantity(int quantity) {
        return (quantity >= MIN_QUANTITY && quantity =< MAX_QUANTITY);
    }

    public static int getBurgerQuantity(Scanner scanner) {
        int numBurgers;
        int attempts = 0;
        do {
            System.out.print("How many burgers would you like? ");
            numBurgers = Integer.parseInt(scanner.nextLine());
        } while (!isValidQuantity(numBurgers) && (++attempts < MAX_ATTEMPTS));
        if (attempts == MAX_ATTEMPTS) throw new IllegalArgumentException(String.format("%d attempts is too many", attempts));
        return numBurgers;
    }

    public static double getBurgerPrice(Scanner scanner) {
        String price;
        System.out.print("Name your burger price: ");
        price = scanner.nextLine();
        return Double.parseDouble(price);
    }
}