重复使用扫描仪创可贴吗? (Java)

时间:2018-11-23 07:48:49

标签: java boolean java.util.scanner conditional-statements do-while

所以我对为什么发生这种情况有些困惑,这是我的代码:

public static void main (String[] args)
{
    Scanner kb = new Scanner(System.in);

    do
    {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a time in 24-hour notation: ");
        String time = in.nextLine();

        int colonIndex = time.indexOf(":");
        int hours = Integer.parseInt(time.substring(0, colonIndex));
        int minutes = Integer.parseInt(time.substring(colonIndex + 1));

        boolean legalTime = ((hours < 24 && hours > 0) && (minutes < 60 && minutes >= 0));
        boolean addZero = minutes < 10;
        boolean pm = hours > 12;

        if(legalTime)
        {
            if(pm && addZero)
            {
                int newHour = hours - 12;
                System.out.printf("That is the same as"
                        + "\n%d:0%d PM\n", newHour, minutes);
            }
            else if(pm && !addZero)
            {
                hours = hours - 12;
                System.out.printf("That is the same as"
                        + "\n%d:%d PM\n", hours, minutes);
            }
            else if (!pm && addZero)
            {
                System.out.printf("That is the same as"
                        + "\n%d:0%d AM\n", hours, minutes);
            }
            else
            {
                System.out.printf("That is the same as"
                        + "\n%d:%d AM\n", hours, minutes);
            }
        }
        try
        {
            if(!legalTime)
            {
                throw new Exception("Exception: there is no such time as " + time);
            }
        }
        catch(Exception e)
        {
            System.out.println(e.getMessage()
                    + "\nAgain? (y/n)");
            continue;
        }

        System.out.println("Again? (y/n)");

    }while(Character.toUpperCase(kb.next().charAt(0)) == 'Y');

}

我的代码本身不是问题,因为do-while循环的条件只能识别do-while之外的布尔值,这使我很沮丧地使条件受到内部条件的影响。块。我想做的是让我的代码运行,然后询问用户是否要再次运行它,用“ y”或“ n”表示。我不能放

!time.charAt(0) == 'y'

因为条件是因为字符串“ time”是在do-while循环内定义的,所以我通过在do-while开始之前仅使用一台扫描仪作为条件输入,然后在其中使用另一台扫描仪,做了一些奇怪的创可贴身体。我知道这很不好,但是我想不出一种简单的方法来为不在do-while循环内的这种条件创建一个布尔值,我是否缺少某些东西?

1 个答案:

答案 0 :(得分:1)

只需在循环前声明一个boolean,而不是多余的Scanner,然后在循环内更新此boolean

boolean again = true;
do {
    ...
    System.out.println("Again? (y/n)");
    again = Character.toUpperCase(in.next().charAt(0)) == 'Y';
} while (again);