在我的例子中,用户只需给出两个字符串“AM”或“PM”。我已经写了 do while();循环来做到这一点。但是当在 while(); 里面时我有两种表达循环变得无限。当我只有一个时,无论哪一个,程序都运行完美。预先感谢您提供任何解决方案!
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));
最佳答案
你的病情说明
while(!period.equals(x) || !period.equals(y));
这意味着当时间段不是“AM”或“PM”时,我们应该继续。
假设我们将时段设置为“AM”。这是所希望的,但根据您的逻辑,我们必须继续,即使 period
是“AM”,它也不是“PM”。看到问题了吗?
试试这个
while(!period.equals(x) && !period.equals(y));
关于java - 有没有办法在Java中控制用户使用do给出的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54095794/