为什么我在控制台中变为空?

时间:2015-10-24 03:09:43

标签: java

应根据密码中需要的字符数生成随机密码。它确实创建了一个密码,但显示为密码: null bjkalhmmglmhb。不确定为什么会出现null,但仍会创建密码。

   import java.util.Random;

        //26 letters in alpha
        public class PasswordRandomizer {
            int length, position;
            String password;
            Random random;

            public PasswordRandomizer(int length) {
                this.length = length;
                random = new Random();

                for (int counter = 0; counter < this.length; counter++) {
                    position = random.nextInt(length - 1);
                    char symbol = "abcdefghijklmnopqrstuvwxyz".charAt(position);
                    this.password = "" + this.password + symbol;
                }
            }

            public String createPassword() {
                return this.password;
            }
        }

    public class Main {
        public static void main(String[] args) {
            PasswordRandomizer randomizer = new PasswordRandomizer(13);
            System.out.println("Password: " + randomizer.createPassword());

        }
    }

1 个答案:

答案 0 :(得分:0)

这是null initialy:String password;,然后你将字符串连接到这个空变量 - 不好。使用StringBuilder或首先将String初始化为非null值,然后将字符串连接到它:String password = "";会这样做。