在Java中,有没有一种方法可以控制用户使用do给出的字符串?
在我的例子中,用户只需给出两个字符串“AM”或“PM”。我已经写了do while();循环来做那个。但是当你在里面的时候,();我有两个表达式,循环变为无限。当我只有一个时,不管是哪一个,程序运行都很完美。提前感谢您提供的任何解决方案在Java中,有没有一种方法可以控制用户使用do给出的字符串?,java,Java,在我的例子中,用户只需给出两个字符串“AM”或“PM”。我已经写了do while();循环来做那个。但是当你在里面的时候,();我有两个表达式,循环变为无限。当我只有一个时,不管是哪一个,程序运行都很完美。提前感谢您提供的任何解决方案 import java.util.Scanner; class Time{ public static void main(String[] args){ int hours, minutes, sec; String period, x
import java.util.Scanner;
class Time{
public static void main(String[] args){
int hours, minutes, sec;
String period, x, y;
x = "AM";
y = "PM";
Scanner reader = new Scanner(System.in);
System.out.println("");
System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------");
System.out.println("Give the values you will be asked. Those values form the time give them in such a way that they would appear in a digital clock. (ex.: 2pm = 14)");
System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------");
System.out.println("");
System.out.println("..............................................");
do{
System.out.print("Chooce the current time period (AM or PM) : ");
period = reader.nextLine();
if(!period.equals(x) || !period.equals(y)){
System.out.println("Your input should be AM or PM");
}
}while(!period.equals(x) || !period.equals(y));
当(!period.equals(x)| |!period.equals(y))代码>
在:while(!period.equals(x)和&!period.equals(y))代码>
您必须输入条件,否则它总是被评估为true
“AM”不等于“AM”是假的吗
“AM”不等于“PM”是真的吗
真或假=真|(1+0=1)你的情况表明
while(!period.equals(x) || !period.equals(y));
所以这意味着,当时段不是“上午”或“下午”时,我们应该继续
假设我们将句点设置为“AM”。这是需要的,但根据您的逻辑,我们必须继续,即使period
是“AM”,也不是“PM”。看到问题了吗
试试这个
while(!period.equals(x) && !period.equals(y));
我的IDE告诉我这个表达式总是返回“true”:
让我们分析一下原因。通过使用来简化逻辑,我们得到了这个表达式
!(period.equals(x) && period.equals(y))
因此,即使period
等于“AM”,它也不会等于“PM”,并且会使表达式失败,从而使语句始终为真
如果翻转表达式以使用&&
:
!period.equals(x) && !period.equals(y)
DeMorgan的法律规定:
!(period.equals(x) || period.equals(y))
…这正是我们想要的。它不是“AM”也不是“PM”。代码的问题是,您在while循环中给出的终止条件是:
如果用户输入不等于X或Y,则继续旋转(不要退出循环)
该条件应更改为:
while(!period.equals(x) && !period.equals(y));
在while()
循环中,首先检查该循环的条件。因此,如果为该循环输入的条件为true,则将执行其中的代码。如果条件为假,则代码将不会执行
在do-while()
循环中,代码将先执行,,然后检查条件,因为x
不等于y
,!周期。等于(x)| |!period.equals(y)
永远不会为假。您可能是指&&
。要将问题标记为已解决,您应该为德摩根定律+1。我试图让解释保持简单,但如果逻辑更复杂,使用这种方法会有很大帮助。
while(!period.equals(x) && !period.equals(y));