Question:
How to validate an input is a positive number?
Code:
import java.util.*; public class ReadInt { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(true) { try { System.out.print("Enter Positive Number: "); int i = sc.nextInt(); if(i > 0){ System.out.println("You entered: " + i); System.out.println("Thank you"); break; } else { System.out.println("Negative Number"); } } catch (InputMismatchException e) { System.out.println("You did not enter a Number."); sc.nextLine(); } } } }
Output:
$ java ReadInt Enter Positive Number: hello You did not enter a Number. Enter Positive Number: -222 Negative Number Enter Positive Number: 100 You entered: 100 Thank you