所以我有点困惑为什么会发生这种情况,这是我的代码:
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 之外的 boolean 值,在我看来,这使得使条件受到 do-while 内部任何内容的影响非常令人沮丧堵塞。我想做的是让我的代码运行,然后询问用户是否要再次运行它,用“y”或“n”表示。我不能放
!time.charAt(0) == 'y'
作为条件,因为字符串“time”是在 do-while 循环内定义的,所以我做了一些奇怪的创可贴,使用一个扫描仪仅用于 do-while 开始之前的条件输入,并在内部使用另一个扫描仪 body 。我知道这很糟糕,但我想不出一种简单的方法来为不在 do-while 循环内的这种条件创建 boolean 值,我是否遗漏了一些东西?
最佳答案
只需在循环之前声明一个 boolean
而不是额外的 Scanner
,并在循环内更新此 boolean
:
boolean again = true;
do {
...
System.out.println("Again? (y/n)");
again = Character.toUpperCase(in.next().charAt(0)) == 'Y';
} while (again);
关于java - 重复扫描仪临时创可贴? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53442568/