008:Why does this code using random strings print “hello world”?

Posted 氵冫丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了008:Why does this code using random strings print “hello world”?相关的知识,希望对你有一定的参考价值。

题目:为什么输出hello word?

import java.util.*;



public class stackoverFlow 

    public static void main(String[] args) 
        System.out.println(randomString(-229985452) + " " + randomString(-147909649));

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


程序中加入下面一行代码:

            System.out.println(k+" + "+ Integer.valueOf('`') +" = "+ (k+ Integer.valueOf('`'))  + " ,toChar = " + (char)('`' + k));

输出结果

8 + 96 = 104 ,toChar = h
5 + 96 = 101 ,toChar = e
12 + 96 = 108 ,toChar = l
12 + 96 = 108 ,toChar = l
15 + 96 = 111 ,toChar = o
23 + 96 = 119 ,toChar = w
15 + 96 = 111 ,toChar = o
18 + 96 = 114 ,toChar = r
12 + 96 = 108 ,toChar = l
4 + 96 = 100 ,toChar = d

发现正好是hello word
这说明两个问题:
1.随机数是如何产生的?
其实是已经产生好的随机数表,根据输入的随机数种子,确定选取的随机数的起始位置开始取出随机数。这样根据输入的随机数种子,每次参数的随机数就是固定的。在小学还是初中数学书上都有个随机数表,当需要用的时候就自己随机确定位置产生随机数。

2.整型转化成对应的 char类型
这样恰好形成hello word

这个更强大

        int[] arrInt = -2146926310, -1885533740, -274140519, 
                -2145247212, -1845077092, -2143584283,
                -2147483454, -2138225126, -2147375969;

        for(int seed : arrInt)
            System.out.print(randomString(seed) + " ");
        

输出

the quick browny fox jumps over a lazy dog 

本专题来源stackoverflow 标签是java的投票数比较高的问题以及回答,我只对上面的回答根据自己的理解做下总结。

以上是关于008:Why does this code using random strings print “hello world”?的主要内容,如果未能解决你的问题,请参考以下文章

clion中cpp文件显示This file does not belong to any project ,code insight features might not work解决方案

clion中cpp文件显示This file does not belong to any project ,code insight features might not work解决方案

How does a single thread handle asynchronous code in JavaScript?

License server system does not support this version of this feature

App installation failed This application does not support this device’s CPU type.

This cache store does not support tagging.