forked from aneez9n/Basic-Projects
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AgeInputVer3.java
58 lines (51 loc) · 1.39 KB
/
AgeInputVer3.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package exceptionhandling;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
*
* @author admin
*/
public class AgeInputVer3
{
private static final String DEFAULT_MESSAGE = "Your age: ";
private Scanner scanner;
public AgeInputVer3()
{
scanner = new Scanner(System.in);
}
public int getAge()
{
return getAge(DEFAULT_MESSAGE);
}
public int getAge(String prompt)
{
int age=0;
while (true)
{
System.out.print(prompt);
try
{
age = scanner.nextInt();
if (age < 0)
{
throw new Exception("Negative age is invalid");
}
return age; //input okay so return the value & exit
}
catch (InputMismatchException e)
{
scanner.next();
System.out.println("Input is invalid.\n"+"Please enter digits only");
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
}
}
}
}