tags:

views:

65

answers:

1

This is a school project:

Objective:

Ask the user to input 2 number

A random number will be print to the user.

Must catch if input isn't Integer.

I have check online source, which i copied the code and use it.

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

The code work fine except if I input any integer less than 10. The Program will consider it as a letter and says "ERROR"

My Program:

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 interger's not number
                {
                    System.err.println("ERROR");
                    System.err.println("Type in Interger only");
                }
                catch(Exception E)  //catch Genaral 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();
    }
}
+2  A: 

Look at the GSC code -- if I enter 1 character and then hit enter, what's the length of the InputBuffer when I do hit enter?

Since you want to read a whole line, consider using an InputStreamReader to read System.in, and then a BufferedReader to wrap that reader (so that you can call readLine).

Ben Taitelbaum