2010-10-31 45 views
1

这是一所学校的项目:我的随机数发生器没有做什么,我想要它是

目的:

要求用户输入2号

随机数将打印给用户。

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

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

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

,除非我输入任何整数比10少该计划将它视为一个字母的代码,做工精细说:“ERROR”

我的计划:

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(); 
    } 
} 
+0

我运行你的代码,输入'Mark',然后是'2',然后是'5',每次运行它时产生一个2到5之间的随机数,并且它没有错误地成功。 – 2010-10-31 04:19:41

+0

@Mark谢谢 – Blackiey 2010-10-31 04:22:31

回答

2

看GSC代码 - 如果我输入1个字符然后回车,输入缓冲区的长度是多少?

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

相关问题