java - 检查输入的字符串是否仅包含 1's and 0' s

标签 java

我正在编写一个将二进制数转换为十进制数的程序,我只是一个新手程序员。我一直在尝试确定输入的字符串是二进制数,这意味着它只包含 1 和 0。到目前为止我的代码是:

  String num;
  char n;

  Scanner in = new Scanner(System.in);
  System.out.println("Please enter a binary number or enter 'quit' to quit: ");
  num = in.nextLine();
  n = num.charAt(0);
  if (num.equals("quit")){
    System.out.println("You chose to exit the program.");
    return;
  }

  if (n != 1 || n != 0){
    System.out.println("You did not enter a binary number.");
  }

照原样,无论输入什么(除了退出),即使输入了二进制数,程序也会输出“您没有输入二进制数”。我确信我的 if 语句是错误的或者我的角色声明是错误的,但是我已经尝试了我个人所知道的一切来纠正这个问题,但我在网上找到的任何帮助都没有。任何帮助将不胜感激。

最佳答案

你可以只使用正则表达式:

num.matches("[01]+")

如果字符串 num 仅包含 01 个字符,并且 ,这将为 true false 否则。

关于java - 检查输入的字符串是否仅包含 1's and 0' s,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12809914/

相关文章:

java - 使用选择排序方法对二维数组进行排序并将结果写入文件

java - 如何创建一个总体 if 语句?如, "if this happens at any point in the program..."

java - 升级 Spring Integration 版本后出现类转换异常

java - 大小为 n 的 TreeMap 和 HashMap 中 get() 方法的运行时性能是多少

java - 如何创建用于 Web 服务的密码摘要?

java - 扫描仪类没有这样的元素异常(exception)

java - readObject() 方法不打印对象

java - GWT-EXT:Component.setId 生成随机前缀

java - 在 Servlet 中检索单选按钮

java - 我需要什么背景?