Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

java - 为什么这段代码使用随机字符串打印“hello world”?(Why does this code using random strings print “hello world”?)

The following print statement would print "hello world".

(以下print语句将打印“hello world”。)

Could anyone explain this?

(有人能解释一下吗?)

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

And randomString() looks like this:

(而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();
}
  ask by 0x56794E translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The other answers explain why, but here is how.

(其他答案解释了原因,但这里是如何。)

Given an instance of Random :

(给定一个Random实例:)

Random r = new Random(-229985452)

The first 6 numbers that r.nextInt(27) generates are:

(r.nextInt(27)生成的前6个数字是:)

8
5
12
12
15
0

and the first 6 numbers that r.nextInt(27) generates given Random r = new Random(-147909649) are:

(r.nextInt(27)生成给定的Random r = new Random(-147909649)的前6个数字是:)

23
15
18
12
4
0

Then just add those numbers to the integer representation of the character ` (which is 96):

(然后只需将这些数字添加到字符`的整数表示中(即96):)

8  + 96 = 104 --> h
5  + 96 = 101 --> e
12 + 96 = 108 --> l
12 + 96 = 108 --> l
15 + 96 = 111 --> o

23 + 96 = 119 --> w
15 + 96 = 111 --> o
18 + 96 = 114 --> r
12 + 96 = 108 --> l
4  + 96 = 100 --> d

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...