【问题标题】:How do I have a user input a boolean phrase and then have my IDE output it in binary form?如何让用户输入一个布尔短语,然后让我的 IDE 以二进制形式输出它?
【发布时间】:2015-11-17 14:37:20
【问题描述】:

我想让用户输入类似:True、False、True、True、False

这将输出 01101

这是我的代码:

 public static void main()
{
    Scanner input = new Scanner(System.in);
    System.out.print("What is the Binary phrase? (True/False)");
    String phrase = input.nextLine();



    if(false)
    {
        System.out.print("0");
    }
    else if (true)           
    {
        System.out.print("1");     
    }
}

但这只会输出单个值 1,而不管输入是真还是假

我希望我的代码具有以下初始输入:

boolean [] binaryValues, Graphics g, int x, int y 但我不知道如何使用它来获得我想要的输出

更新:我的代码现在可以根据输入打印 0 或 1,但我仍然需要帮助将 True、False、True、True、False 转换为 01101

【问题讨论】:

    标签: java input binary boolean bluej


    【解决方案1】:
    if(phrase.toLowerCase().equals("false"))
        {
            System.out.print("0");
        }
        else         
        {
            System.out.print("1");     
        }
    

    你必须检查你的输入..

    【讨论】:

      【解决方案2】:

      这样的事情应该可以工作:

      if (scanner.nextBoolean() {
         // print something
      }
      else {
         // print something else.
      }
      

      注意:在实际读取之前,您必须使用scanner.hasNextBoolean() 检查流中是否存在布尔值。

      【讨论】:

        【解决方案3】:

        如果你输入的是否与布尔值的字符串表示相同,则需要进行比较。

            Scanner input = new Scanner(System.in);
            System.out.print("What is the Binary phrase? (True/False)");
            String phrase = input.nextLine();
        
        
        
            if(phrase.equalsIgnoreCase("false"))
            {
                System.out.print("0");
            }
            else if (phrase.equalsIgnoreCase("true"))           
            {
                System.out.print("1");     
            }
        

        在您的代码中,您将检查始终不会触发的if(false),然后检查始终会触发的else if(true)。这就是为什么总是显示 1。您将直接布尔值传递到您的 if 语句中,而不是完成检查。

        【讨论】:

          【解决方案4】:
             Scanner in = new Scanner(System.in);
          
            for(String x : in.nextLine().split(",\\s?")){
               System.out.print(new Boolean(x).booleanValue() ? "1" : "0");
            }
          

          【讨论】:

            猜你喜欢
            • 2022-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-04-15
            • 1970-01-01
            • 2020-10-01
            • 2021-12-30
            相关资源
            最近更新 更多