生成器在预期输出之前打印null

时间:2016-10-07 20:06:27

标签: java random initialization concatenation

我已经创建了一个随机字生成器,它似乎工作得非常好,除了在所需输出之前,在同一行中,它打印" null"。

这是我的代码:

import java.util.Random;

public class wordGenerator {

private static String r,s;

public static void randChar(int x) {

    Random rand = new Random();
    x = rand.nextInt((26 - 1) + 1) + 1;

    switch(x) {
    case 1: r = "a"; break;
    case 2: r = "b"; break;
    case 3: r = "c"; break;
    case 4: r = "d"; break;
    case 5: r = "e"; break;
    case 6: r = "f"; break;
    case 7: r = "g"; break;
    case 8: r = "h"; break; 
    case 9: r = "i"; break;
    case 10: r = "j"; break;
    case 11: r = "k"; break;
    case 12: r = "l"; break;
    case 13: r = "m"; break;
    case 14: r = "n"; break;
    case 15: r = "o"; break;
    case 16: r = "p"; break;
    case 17: r = "q"; break;
    case 18: r = "r"; break;
    case 19: r = "s"; break;
    case 20: r = "t"; break;
    case 21: r = "u"; break;
    case 22: r = "v"; break;
    case 23: r = "w"; break;
    case 24: r = "x"; break;
    case 25: r = "y"; break;
    case 26: r = "z"; break;
    default: r = "|null|";
    }

    if(x != 1 && x != 5 && x != 9 && x != 15 && x != 21) {
        int h = rand.nextInt(4 - 0);
        if(h == 2) {
            int k = rand.nextInt(6 - 0);
            switch(k) {
            case 1: r = "a"; break;
            case 2: r = "e"; break;
            case 3: r = "i"; break;
            case 4: r = "o"; break;
            case 5: r = "u"; break;
            }
        }
    }

}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Random rand = new Random();
    int y = rand.nextInt((10 - 4) + 1) + 4;

    for(int z = 1; z < y; z++) {
        randChar(0);
        s = s + r;
    }

    System.out.println(s);
}

对我来说似乎很好,但是当我认为它应该输出像

这样的东西时
  

opfruvme

打印

  

nullopfruvme

问题是什么?

2 个答案:

答案 0 :(得分:3)

您没有初始化s

private static String r,s="";

当您在循环中启动应用程序时,语句s = s + r;在第一个循环中与null连接之前需要r值。使用空字符串初始化变量将为您提供您期望的结果。

答案 1 :(得分:1)

您没有初始化s,因此第一次s = s + r;行执行当前值snull)时会被强制转换为String,因此,您需要将"null" + r分配给s