I need an int value for both inputs. Either the user write 1 or 01 for January.
So it does work for 1 - 12 but if I write 01 it does give me my own error Text.
For me its importent that it is a int Value, I know that String is perfectly work.
private static BufferedReader input= new BufferedReader(new InputStreamReader(System.in));
private Output output = new Output();
public static String inputText() throws Exception {
return input.readLine();
}
public int monatInput(String text){
String monthNumber= "";
boolean again = true;
while (again) {
System.out.print(text);
again = false;
try {
monthNumber = inputText();
int number= Integer.parseInt(monatZahl);
int monthLength = String.valueOf(monatZahl).length();
if (number<=1 || number>=12) {
again = true;
throw new Exception();
} else if (monthLength> 3) {
again = true;
throw new Exception();
}
} catch (Exception e) {
this.output.monatWrongInput;
}
}
int converter = Integer.parseInt(monatZahl);
return converter;
}
I hope you guys can help me to validate this problem. I seen many post about a for-loop to generate 01 digit but that's a bit different then validate as user input.
You get your own error because you don't use the right input :
monthNumber = inputText();
int number = Integer.parseInt(monatZahl);
//-----------------------------^^-----------this should be monthNumber
Another thing, to validate your input you need just to check if your number is between 1 and 12, you don't need to check the lenght
Your month is wrong if it is > 12
or < 1
because the 1 and 12 is a valide month(don't check with <=
or >=
).
int number = Integer.parseInt(monthNumber);
if (number < 1 || number > 12) {
again = true;
throw new Exception();
}
EDIT
Note both :
int i1 = Integer.parseInt("01");
int i2 = Integer.parseInt("1");
Give 1 a valide number