There are two ways to write a program in Java
1.Look before you leap - check all the conditions before hand. i.e check conditions like map is not null or number is not 0 etc etc so that no exception is thrown.
2 Easy to ask for forgive and permissions - second method is to use exceptions.
Examples of Look Before you Leap(LBYL)
public static int divLBLY(int x,int y){
if(y!=0){
return x/y;
}
return 0;
}
public static int getIntLBYP() {
Scanner s = new Scanner(System.in);
boolean isValid = true;
System.out.println("Please enter your integer");
String input = s.next();
for (int i = 0; i < input.length(); i++) {
System.out.println("The character is " + input.charAt(i));
if (!Character.isDigit(input.charAt(i))) {
System.out.println("in the inner if");
isValid = false;
break;
}
}
if (isValid) {
return Integer.parseInt(input);
}
return 0;
}
Examples of Easy to ask for forgiveness and permissions
public static int divEAFP(int x,int y){
try {
return x / y;
}
catch(ArithmeticException e) {
return 0;
}
}
public static int getIntEAFP() {
Scanner s = new Scanner(System.in);
boolean isValid = true;
System.out.println("Please enter your integer");
try {
int input = s.nextInt();
return input;
}
catch(InputMismatchException e){
return 0;
}
}
}