随机字符串程序

时间:2016-01-05 07:21:27

标签: java netbeans

我正在尝试创建一个程序,从a-z运行5-10行随机文本。我已经尝试过运行这个程序,但总是得到一个空白的控制台。

public static void main(String[] args) {
    // TODO code application logic here
     int numberLines = (int) (Math.random() * 5 + 5);
    for (int b = 0; b <= numberLines; b++) {
         int length = (int) Math.random() * 80;
for (int i = 1; i <= length; i++) {
    int randChar = (int) Math.random() * 26;
    if (randChar == 0) {
        System.out.print("a");
    }
    else if (randChar == 1) {
        System.out.print("b");
    }
    else if (randChar == 2) {
        System.out.print("c");
    }
    else if (randChar == 3) {
        System.out.print("d");
    }
    else if (randChar == 4) {
        System.out.print("e");
    }
    else if (randChar == 5) {
        System.out.print("f");
    }
    else if (randChar == 6) {
        System.out.print("g");
    }
    else if (randChar == 7) {
        System.out.print("h");
    }
    else if (randChar == 8) {
        System.out.print("i");
    }
    else if (randChar == 9) {
        System.out.print("j");
    }
    else if (randChar == 10) {
        System.out.print("k");
    }
    else if (randChar == 11) {
        System.out.print("l");
    }
    else if (randChar == 12) {
        System.out.print("m");
    }
    else if (randChar == 13) {
        System.out.print("n");
    }
    else if (randChar == 14) {
        System.out.print("o");
    }
    else if (randChar == 15) {
        System.out.print("p");
    }
    else if (randChar == 16) {
        System.out.print("q");
    }
    else if (randChar == 17) {
        System.out.print("r");
    }
    else if (randChar == 18) {
        System.out.print("s");
    }
    else if (randChar == 19) {
        System.out.print("t");
    }
    else if (randChar == 20) {
        System.out.print("u");
    }
    else if (randChar == 21) {
        System.out.print("v");
    }
    else if (randChar == 22) {
        System.out.print("w");
    }
    else if (randChar == 23) {
        System.out.print("x");
    }
    else if (randChar == 24) {
        System.out.print("y");
    }
    else if (randChar == 25) {
        System.out.print("z");
    }
    System.out.println();
 }    
}

我知道有一种更简单的方法可以做到这一点,但就我的目的而言,我想知道为什么这不起作用。

帮助?

2 个答案:

答案 0 :(得分:4)

我认为您的问题来自length行。 这使得始终Math.random()等于0,因为double返回0.0到1.0之间的int,将int length = (int) (Math.random() * 80); 强制转换为0。

你可以尝试添加像这样的括号

<title>

    Title | Brand name

</title>

答案 1 :(得分:1)

来自Math#Random

的文档
  

返回带有正号的double值,大于或等于0.0且小于1.0。

基本上,length的计算总是产生0。返回的double总是少于1。以下转换为int将生成0,因此您的第二个循环不会被执行。

计算randchar时会发生同样的情况。

要更改它,您可以使用Random类。

Random r = new Random();
...
...
int randChar = r.nextInt(26);