【问题标题】:How do i compare variables containing integers如何比较包含整数的变量
【发布时间】:2021-07-19 20:42:02
【问题描述】:
package Tutorial;
import java.util.Scanner;
public class Tutorial {

  public static void main(String[] args) {
  Scanner sc=new Scanner(System.in);
   String name="revolt";
   int password=0123;
   String Name;
   int Password;
   System.out.println("enter name;");
   Name=sc.nextLine();
   if (Name.equals(name)){
   System.out.println("enter password");
   }
   else{
     System.out.println("wrong Name");
   }
   Password=sc.nextInt();
   if (password==Password){
     System.out.println("access granted...");
   }
   else{
     System.out.println("wrong 
Password!");
   }
  }
}

代码没有显示任何错误,但是当我输入密码时,即使密码正确,它也会告诉我密码错误。

【问题讨论】:

  • 不用详细介绍您的代码,您知道数字0123是对应于83decimal 的八进制数,对吗?
  • 请不要使用同名的变量。这是一个非常糟糕的做法,你不应该从它开始。而是为您的变量提供描述性名称 - 因此您可以使用 passwordInput 或类似的东西,而不是 Password。
  • @EdithStark 嗯,很明显的推断是密码是 83,而不是 123 或 0123。我相信这可能是你的问题,对吧?
  • 你为什么使用 int 作为你的密码?鉴于整数不能以 0 开头,您应该改用 String。确保您记得使用str.equals() 来比较字符串。
  • @EdithStark 在我的第一条评论中进行了解释。以前缀 0 开头的字面整数被 Java 解释为八进制数(例如 0123),就像任何以 0x 开头的数字都是十六进制数而 0b 是二进制数一样。但是,当您从命令行提供整数时,您会提供一个以 10 为底的数字。

标签: java


【解决方案1】:

您现在知道问题出在哪里,但是,如果您决定强制用户提供数字密码(无论数字顺序如何),则将密码设置为字符串变量并利用 Scanner#nextLine() 方法获取用户输入.获得该输入后,请使用 String#matches() 方法和一个小的 Regular Expression(正则表达式)对其进行检查,以确保仅提供数字,例如:

/* User must enter an all numerical password that is a 
   minimum of 4 digits to a maximum of 18 digits.  */  
String password = "";
while(password.isEmpty()) {
    System.out.println();
    System.out.println("Enter your numerical Password: --> ");
    System.out.print  ("(enter 'q' to quit): --> ");
    password = sc.nextLine().trim();
    if (password.equalsIgnoreCase("Q")) {
        System.out.println("Quitting ... Bye-Bye");
        System.exit(0);
    }
    // Password must be all numerical, 
    // be a minimum of 4 digits in length, 
    // and be a maximum of 18 digits in length.
    if (!password.matches("\\d+") || password.length() < 4 || password.length() > 18) {
        System.err.println("Invalid Password Supplied (" + password + ")!\n"
                + "A password must contain a 'minimum' of at least four (4)\n"
                + "all numerical digits to a 'maximum' of 18 digits! No alpha\n"
                + "characters or whitespaces are allowed!");
        password = "";
    }
}

String#matches() 方法中的正则表达式 \\d+ 会检查以确保现在在 password 字符串变量中的内容确实是一个或多个从 0 到 9 的数字的字符串表示. 0123 的密码会被认为是有效的,但是如果您将其解析为 Integer 或 Long,例如,0 将被省略。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-01
    • 2019-12-28
    • 2015-06-15
    • 1970-01-01
    相关资源
    最近更新 更多