【问题标题】:length of a String字符串的长度
【发布时间】:2012-11-06 04:41:09
【问题描述】:

会员ID由一个唯一的字母和数字序列组成,长度最多为10,密码由四位数字组成,我写了两个方法checkId和checkPassword来比较长度,然后我打电话给他们在构造函数中。但代码似乎无法正常工作

public class Test
    {

    private String yourName;
    private String yourId;
    private int password;

    /**
     * Constructor for objects of class Test
     */
    public Test(String yourName, String yourId, int password)
    {
        // initialise instance variables
        this.yourName = yourName;
        this.yourId = yourId;
        this.password = password;
        checkPassword();
        checkId();
    }

    private void checkId()
    {
       int length; 
       length = yourId.length();
       if (length >= 10){
           System.out.print("the length must be less than 10, please change it");
        }
    }

    private void checkPassword()
    {
        int length;
        length = password.length();
        if (length != 4 ){
            System.out.println("must be at 4");
        }
    }
}

【问题讨论】:

  • 哪一部分不起作用?
  • 制作你的密码字符串,它被声明为一个 int 原语:P

标签: java methods if-statement invoke bluej


【解决方案1】:

变量password 的类型为int。诸如此类的类型称为原语,因此它们没有诸如length() 之类的方法。你可以改用Integer.toString(password).length()。

【讨论】:

  • 或者只是将密码声明为字符串,密码为 int——对我来说真的没有意义:P
  • 是的,尽管他可能会发现将其作为 int 操作更容易;他说这是一个 4 位数的密码。
  • 好的,现在我明白了,如果 (length != 4 ) 怎么样,但问题是在这两种情况下都会创建对象
  • 我可以声明为一个字符串,但它只有四位数字,只有数字
  • 一个 int 将保证您的密码实际上是数字。如果您希望允许使用 0000 或 0101 等密码,则可以改为使用 if (password >= 0 && password < 10000)
猜你喜欢
  • 1970-01-01
  • 2017-08-19
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 1970-01-01
  • 2017-10-11
  • 2015-01-13
  • 1970-01-01
相关资源
最近更新 更多