为什么这段代码使用随机字符串打印“hello world"? [英] Why does this code using random strings print "hello world"?

查看:25
本文介绍了为什么这段代码使用随机字符串打印“hello world"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下打印语句将打印hello world".谁能解释一下?

The following print statement would print "hello world". Could anyone explain this?

System.out.println(randomString(-229985452) + " " + randomString(-147909649));

randomString() 看起来像这样:

public static String randomString(int i)
{
    Random ran = new Random(i);
    StringBuilder sb = new StringBuilder();
    while (true)
    {
        int k = ran.nextInt(27);
        if (k == 0)
            break;

        sb.append((char)('`' + k));
    }

    return sb.toString();
}

推荐答案

java.util.Random 的实例使用特定的种子参数(在本例中为 -229985452-147909649),它遵循随机数生成算法从该种子值开始.

When an instance of java.util.Random is constructed with a specific seed parameter (in this case -229985452 or -147909649), it follows the random number generation algorithm beginning with that seed value.

用相同的种子构造的每个Random每次都会生成相同的数字模式.

Every Random constructed with the same seed will generate the same pattern of numbers every time.

这篇关于为什么这段代码使用随机字符串打印“hello world"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆