getNumber method

Is there a more efficient way to do this?

Page 1 of 1

1 Replies - 3053 Views - Last Post: 26 March 2010 - 11:49 PM Rate Topic: -----

#1 ShoSho_1489  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 07-November 09

getNumber method

Posted 26 March 2010 - 11:20 PM

Below is my getNumber method. It's used to get a number from the user, it checks if the value is a number using the isNumber method, which returns a true if it's a number and false if it is not. And if the value is less than the Maximum number passed to the method. What I have works, I just think there's probably a more efficient way to do it. Any suggestions on a way to make this more efficient?

	public static int getNumber(int MAXNUM)throws IOException
	{
		BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
		String userNum;
		int intUserNum;
		
		while (true) {
			
			System.out.println("Please enter a number: ");
			userNum = input.readLine();
		
			if (isNumber(userNum) != true) {
				System.out.println("Invalid Entry. Please enter a whole number: ");
				continue;
			}
			
			intUserNum = Integer.parseInt(userNum);
			
			if (intUserNum > MAXNUM) {
				System.out.println("Invalid Entry. Number too large.");
				continue;
			}
			else {
				return intUserNum;
			}
		}
	}


Is This A Good Question/Topic? 0
  • +

Replies To: getNumber method

#2 mostyfriedman  Icon User is offline

  • The Algorithmi
  • member icon

Reputation: 727
  • View blog
  • Posts: 4,473
  • Joined: 24-October 08

Re: getNumber method

Posted 26 March 2010 - 11:49 PM

this should do it
public static int getNumber(int MAXNUM)
        {
                BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
                String userNum;
                int intUserNum=0;
                boolean keepGoing = true;
                while (keepGoing) {
                        try{
				System.out.println("Please enter a number: ");
                        	userNum = input.readLine();
                        	intUserNum = Integer.parseInt(userNum);
				if(intUserNum <= MAXNUM)
					keepGoing = false;
                      	}
			catch(Exception e){
				System.out.println("invalid number");
			}
		}       
                        return intUserNum;

                        
        }


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1