我需要修复什么来打印出一串随机字符?

时间:2010-11-14 07:49:31

标签: java

这是标签所暗示的Java。我无法弄清楚如何让它在代码末尾打印出“key”字符串,同时保持变量的方式。我只是真的使用静态main,我不知道它对程序有什么用,因为我是一个新手。有人能指出我正确的方向吗?我想知道你们的想法!

import java.util.Random;

class Key {

    private String key = new String();
    private void main(String[] args) {
        Random r = new Random();

        for (int i = 10; i > 0; i--) {
            int randomNumber = r.nextInt(10) + 48;
            int randomLetter = r.nextInt(26) + 97;
            int branchSwitch = r.nextInt(2);

            if (branchSwitch == 1) {
                // System.out.print((char)randomNumber);
                key = key + (char) randomNumber;
            } else
                key = key + (char) randomLetter;
            // System.out.print((char)randomLetter);
        }
        System.out.print(key);
    }
}

2 个答案:

答案 0 :(得分:4)

首先,如果要将此作为应用程序运行,则main应为public static。 因此,您可以按照以下方式修改程序(请注意,您的原始main已重命名为generateAndPrint,因为您不能在一个类中使用两个具有相同签名的方法):

class Key {
    private String key = new String();
    private void generateAndPrint() {
        Random r = new Random();

        for (int i = 10; i > 0; i--) {
            int randomNumber = r.nextInt(10) + 48;
            int randomLetter = r.nextInt(26) + 97;
            int branchSwitch = r.nextInt(2);

            if (branchSwitch == 1) {
                // System.out.print((char)randomNumber);
                key = key + (char) randomNumber;
            } else
                key = key + (char) randomLetter;
            // System.out.print((char)randomLetter);
        }
        System.out.print(key);
    }

    public static void main(String[] args) {
        Key key = new Key();
        key.generateAndPrint();
    }
}

答案 1 :(得分:1)

我无法理解为什么main是私有的(非静态的)。

但是,这是一个test-run of your program at ideone.com。它似乎工作正常。

我所做的改变:

  • 制作主要方法public static
  • 将变量设为静态。