开发者

What do I need to fix to get this to print out a string of random characters?

This is in Java as the tag 开发者_开发技巧implies. I can't figure out how to get it to print out the "key" string at the end of the code while keeping my variables the way they are. I've only really worked with static main, and I have no idea what that does for programs as I'm a total novice. Can someone point me in the right direction? I'd like to know what you all think!

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


First, main should be public static if you want to run this as an application. So you can fix your program as follows (note that your original main is renamed to generateAndPrint because you can't have two methods with the same signature in one class):

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();
    }
}


I can't understand why your main is private (and non-static).

However, here is a test-run of your program at ideone.com. It seems to work ok.

Changes I made:

  • Made the main-method public static
  • Made the variable static.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜