Java - 在循环中读取多字符行的第一个字母。

时间:2017-11-01 22:07:36

标签: java

我正在编写一个程序,允许用户购买"购买"巧克力棒,然后用优惠券奖励用户,其中七个可以免费购买另一个巧克力棒。在程序的几个点上,将提示用户做出选择。

这些选择是:

是否购买巧克力棒或关闭程序。

是否使用优惠券购买免费的巧克力棒。

如果不使用优惠券,可以购买多少块巧克力棒。

我不必担心这个程序的巧克力棒的价格。我坚持的部分是用户的输入必须能够是一个字符,一个字或几个字长,并且第一个字母是作为用户读取的内容。响应。因此,例如,如果用户输入"是,我做"然后输入读数为“' Y'

我的问题是,keyboard.nextLine()。charAt(0)和keyboard.next()。charAt(0)似乎都不起作用。在后一种情况下,如果用户输入是几个字长,则第二个字用作输入。对此的一般回应当然是使用nextLine()而不是next()。当我使用nextLine()时,循环的第一次迭代执行没有任何问题。但循环的下一次迭代会立即产生以下错误:

线程中的异常" main" java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0     at java.lang.String.charAt(String.java:658)     在ChocolateCoupons.main(ChocolateCoupons.java:47)

所以看起来next()和nextLine()都不起作用。我该怎么办?这是我的代码:

import java.util.Scanner;

public class ChocolateCoupons 
{
    public static void main(String[] args) 
    {
        //Number of coupons that can be traded for one free chocolate
        final int COUPONS_PER_CHOCOLATE = 7;

        //So that the scanner reads only the first letter when user inputs a string
        final int START_OF_INPUT = 0;

        //Number of coupons the user has and how many chocolates to purchase.
        int couponCount = 0, purchase;

        //Choices whether to continue running the program
        //and whether to trades coupons for chocolates.
        char run = 'P', freeChocolate = 'N';

        //If true, all remaining portions of the main loop will be ignored. 
        //Resets to false at the end of every loop
        boolean end = false; 

        //Scans user input
        Scanner keyboard = new Scanner(System.in);

        while(run != 'S' && run != 's')
        {
            //Asks user whether to shut down or process a transaction
            System.out.println("Menu:");
            System.out.println("  P (process Purchase)");
            System.out.println("  S (Shut down)");
            System.out.println();
            System.out.print("  Your choice: ");

            //User's choice
            run = keyboard.nextLine().charAt(START_OF_INPUT);

            //Checks for invalid input. Ends iteration of loop if input is invalid
            if(run != 'p' && run != 'P' && run != 's' && run != 'S')
            {
              System.out.println("Invalid input!");
              end = true;
            }

            //Ends loop if user selects shutdown
            if(run == 's' || run == 'S')
                end = true;

            //Check if customer qualifies for free chocolate
            if(couponCount >= COUPONS_PER_CHOCOLATE && end != true)
            {
                //Choose whether to claim free chocolate or not
                System.out.println("Use credits to claim free chocolate bar? (Y or N)");
                freeChocolate = keyboard.next().charAt(START_OF_INPUT);

                //Subtracts coupons if user chooses yes. Ends iterations of loop if yes.
                if(freeChocolate == 'Y' || freeChocolate == 'y')
                {
                    System.out.println("Enjoy your free chocolate!");
                    end = true;
                    couponCount -= COUPONS_PER_CHOCOLATE;

                    //Displays new amount of coupons held by user
                    System.out.println("You used " + COUPONS_PER_CHOCOLATE
                      + " coupons and have " + couponCount + " left.");
                }

                //Continues program if user selects no
                else if(freeChocolate == 'N' || freeChocolate == 'n');

                //Checks for invalid input. Ends iteration of loop if Y or N are not input.
                else
                {
                    System.out.println("Invalid response!");
                    end = true;
                }
            }

            if(end != true)
            {
                //How many chocolates to buy. Gives coupons equal to number of chocolates
                System.out.println("How many chocolate bars will you purchase?");
                purchase = keyboard.nextInt();

                //Checks for invalid input
                if(purchase >= 0)
                {
                    couponCount += purchase;
                    System.out.println();
                    System.out.println(" You earned " + purchase + " coupons. You now have a total of " + couponCount + " coupons.");
                } 
                else
                    System.out.println("You can't purchase negative chocolate bars!");
            }
            end = false;
        }
        System.out.println("Thank you, and goodbye!");
        keyboard.close();
    }
}

关于我的节目格式的任何其他反馈也会受到赞赏,但我最初的问题是我最担心的。提前谢谢!

0 个答案:

没有答案