java - 有没有办法在Java中控制用户使用do给出的字符串?

标签 java

在我的例子中,用户只需给出两个字符串“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/

相关文章:

java - GWT DockLayoutPanel 子控件大小调整

java - 如何通过在 Try-Catch While 循环中输入特定字母来退出程序?

java - 如何使用 Java 中的 FTP 在大型机上创建数据集

java - IntelliJ : Getting Spring+Gradle+JUnit project to work within IDE

java - 如何在 Android 中比较 AM/PM 时间

java - 获取 ClassCastException : java. lang.Integer cannot be cast to java.lang.String 错误而无需强制转换

Java - 在 x y 坐标集中查找线

java - 使用java连接外部数据库

java - 如何对对象数组的特定元素进行排序

java - 使用之前的答案,无法通过同时击键同时获取两张图片到 "move"