I'm having a severe brain drain moment and can't figure out how to validate user input? I need to make sure that it is an int and it is greater than 2. And I need it to loop until the user meets those requirements. I tried a try-catch block but it doesn't seem to be doing what I want. Any suggestions??

try {
		System.out.println("Please enter the value for ps");
		ps = sc.nextInt();
		} catch (InputMismatchException e)
		{
			System.out.println("please inter an integer");
		}
		if (ps <= 1) {
			System.out
					.println("The number must be larger than 2.  Please re-enter it");
			ps = sc.nextInt();
		}

Read in string, give it to Integer for parseInt and see if it succeed or throw exception. On success check if bigger then 2

I changed my code, but it still isn't doing what I want. This has to be something simple that I am doing wrong!

System.out.println("Please enter the value for ps");
		tempPs = sc.next();
		try {
		ps = Integer.parseInt(tempPs);
		} catch (NumberFormatException e)
		{
			System.out.println("please inter an integer");
		}
		catch (InputMismatchException e)
		{
			System.out.println("please inter an integer");
		}
		if (ps < 2) {
			System.out
					.println("The number must be larger than 2.  Please re-enter it");
			ps = sc.nextInt();
		}

I figured it out. Thank you for your help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.