java - 我的随机数生成器没有达到我的预期

标签 java

这是一个学校项目:

目标:

要求用户输入2个数字

将向用户打印一个随机数。

如果输入不是整数,则必须捕获。

我检查了在线源,我复制了代码并使用它。

Min + (int)(Math.random() * ((Max - Min) + 1))

代码工作正常,除非我输入任何小于 10 的整数。程序会将其视为字母并显示“错误”

我的程序:

import java.lang.StringBuffer;
import java.io.IOException;
import java.util.Random;


class RandomInput2
{
    public static void main(String args[])
    {
        System.out.println("Programe Begins");


        Random seed = new Random();
        int n1 , n2, rand ;
        System.out.println("What is your name?");
        String InputString = GCS();
            while(true)
            {
                try
                {
                    System.out.println("What is your First number?");
                    n1 = Integer.parseInt(GCS());
                    System.out.println("What is your second number");
                    n2 = Integer.parseInt(GCS());
                    rand = n2+ (int)(seed.nextDouble()*((n1-n2)+1));
                    System.out.println(InputString+" Your number is "+rand);
                }

                catch(NumberFormatException NFE)  //catch if integer's not number
                {
                    System.err.println("ERROR");
                    System.err.println("Type in Integer only");
                }
                catch(Exception E)  //catch General Error
                {
                    System.err.println("ERROR");
                }


;
            }
    }


    public static String GCS() //Get Console String
    {
        int noMoreInput =-1; //set int
        char enterKeyHit= '\n'; //set char

        int InputChar;
        StringBuffer InputBuffer = new StringBuffer(100);

        try
        {
            InputChar=System.in.read();
            while(InputChar != noMoreInput)
            {
                if((char)InputChar!=enterKeyHit)
                {
                    InputBuffer.append((char)InputChar);
                }
                else
                {
                    InputBuffer.setLength(InputBuffer.length()-1);
                    break;
                }
                InputChar = System.in.read();
            }//ends while loop
        }
        catch(IOException IOX)
        {
            System.err.println(IOX);
        }
        return InputBuffer.toString();
    }
}

最佳答案

查看 GSC 代码 - 如果我输入 1 个字符,然后按 Enter 键,那么当我按 Enter 键时,InputBuffer 的长度是多少?

由于您想要读取整行,请考虑使用 InputStreamReader 来读取 System.in,然后使用 BufferedReader 来包装该读取器(以便您可以调用 readLine)。

关于java - 我的随机数生成器没有达到我的预期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4061816/

相关文章:

java - 使用DES在Java中加密和解密文件

java - 在 Java 中生成字母

java - 堆栈溢出异常

java - json对象与java对象不一致时的gson.fromJson

java - 标题不显示在 SlidingTabLayout 中

java - 将 Windows 预期批处理转换为 OSX 批处理

java - Web服务请求执行时间计算

java - 如果在 netbeans 外部运行,则线程 NullPointerException

java - 调用同步方法的线程是否会使用同一对象但以非同步方式抢占另一个线程?

java - 在我们所有商店中按产品类别查找销售明细