繁体   English   中英

我如何比较包含整数的变量

[英]How do i compare variables containing integers

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!");
   }
  }
}

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

您现在知道问题是什么,但是,如果您决定强制用户提供数字密码(无论数字顺序如何),则将密码 设为String 变量并利用Scanner#nextLine()方法获取用户输入。 获得该输入后,使用String#matches()方法和一个小的正则表达式(regex) 检查它以确保只提供数字,例如:

/* 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+检查以确保现在密码字符串变量中的内容确实是从 0 到 9 的一个或多个数字的字符串表示。将考虑密码0123有效但是,如果您要将其解析为 Integer 或 Long,则省略0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM