【问题标题】:Base 10 - Base 2 Converter in Java using a StackBase 10 - 使用堆栈的 Java 中的 Base 2 转换器
【发布时间】:2015-02-05 00:08:56
【问题描述】:

我不确定我离结束还有多远,但我必须使用堆栈在 Java 中创建一个程序。我已经完成了 Stack 类,现在唯一给我带来问题的是 Converter 类。我在编译时得到以下信息:

Base10Converter.java:13: cannot find symbol
symbol  : variable rand
location: class Base10Converter

System.out.println(outputInBinary());
                                                      ^
1 error

我知道它不应该是“rand”,所以它只是一个占位符。需要帮助!

import java.util.Scanner;
public class Base10Converter
{
    public  static void Main(String args[])
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter your base10 number: ");
        String in = scan.nextLine(); //read the value
        for (int x = 0; x < in.length(); x++)
        {
                if (in.charAt(x) >= 0 && in.charAt(x) <= 9)
                {
                        System.out.println(outputInBinary(rand));
                }
                else
                {
                System.out.println("Invalid Number! 0 - 9. No letters.");
                }
        }
    }//main

    public static void outputInBinary(int in)
    {
        CharStack cStack = new CharStack();
        while(in > 0)
        {
            int bit = in % 2;
            cStack.push((char)(bit + 48));
            if (cStack.isFull())
            {
                System.out.println("Stack is full!");
            }
            in = in/2;
        }
        while (!cStack.isEmpty())
        {
            System.out.println(cStack.pop());
        }
    }//ouputInBinary

}

编辑:我把“rand”去掉,因为这不是我想要的(我有一个白痴时刻)。我要打印的是第二种方法中弹出的结果。我希望能够打印用户输入的数字的二进制。

【问题讨论】:

  • 你想要的随机数的范围是多少?
  • 你为什么不用nextInt

标签: java binary stack base


【解决方案1】:

您正在尝试做的是打印出一个 void 声明。 而不是System.out.print(outputInBinary(int in));

outputInBinary((int)(Math.random()*100));

【讨论】:

    【解决方案2】:

    使用随机对象从 1 到 100 生成一个随机数,例如:

    Random random = new Random();
    rand = random.nextInt(100) + 1;
    

    【讨论】:

      【解决方案3】:

      您无需阅读下一行,nextInt 更适合这里:

      private static int readInt(Scanner scan) {
          while (!scan.hasNextInt()) {
              scan.next();
              System.out.println("Invalid Number! 0 - 9. No letters.");
          }
          return scan.nextInt();
      }
      
      public  static void main(String args[])
      {
          Scanner scan = new Scanner(System.in);
          System.out.println("Please enter your base10 number: ");
          outputInBinary(readInt(scan));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-11
        • 1970-01-01
        • 2021-10-12
        • 2022-10-23
        • 2012-03-22
        • 2011-01-24
        • 1970-01-01
        • 2013-03-05
        相关资源
        最近更新 更多