【问题标题】:Duplicate scanner band-aid for do-while? (Java)重复扫描仪创可贴吗? (爪哇)
【发布时间】:2019-04-25 19:45:05
【问题描述】:

所以我有点困惑为什么会这样,这是我的代码:

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 循环内的条件创建一个布尔值,我错过了什么吗?

【问题讨论】:

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


    【解决方案1】:

    只需在循环前声明一个boolean 而不是额外的Scanner,然后在循环内更新这个boolean

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-13
      • 1970-01-01
      • 2023-04-11
      • 2015-09-06
      • 2014-03-13
      • 2019-10-22
      • 1970-01-01
      • 2018-05-03
      相关资源
      最近更新 更多