Hello guys,
I wrote a code from thomas wu book (OOP java, 5 edition).
But I got an error in scanner statement like this
debug: Your Age : Exception in thread "main" java.lang.NullPointerException at ProgrammerDefinedException.AgeInput5.getAge(AgeInput5.java:41) at ProgrammerDefinedException.Ch8TestAgeInput5.main(Ch8TestAgeInput5.java:11) Java Result: 1 BUILD SUCCESSFUL (total time: 3 seconds)
there's my code (I have given a mark where the error)/* * Buku Thomas Wu, Bab Programmer Defined Exception * Self Independent Declaration Modified Class */ package ProgrammerDefinedException; import java.util.Scanner; import java.util.InputMismatchException; public class AgeInput5 { private static final String DEFAULT_MESSAGE = "Your Age : "; private static final int DEFAULT_TEPI_BAWAH = 0; private static final int DEFAULT_TEPI_ATAS = 99; private int tepiBawah; private int tepiAtas; private Scanner scanner; /***Constractor***/ public AgeInput5(int low,int high) { init(DEFAULT_TEPI_BAWAH,DEFAULT_TEPI_ATAS); } public AgeInput5(String msg,int low,int high) throws IllegalArgumentException{ //Throwing Exception if(low>high) throw new IllegalArgumentException("tepi bawah "+low+" lebih besar dari tepi atas "+high); else init(low,high); } /***Methode***/ public int getAge() throws AgeInputException{ return getAge(DEFAULT_MESSAGE); } public int getAge(String msg) throws AgeInputException{ int umur; while(true){ System.out.println(msg); try{ umur = scanner.nextInt(); <=========================================THIS IS AN ERRROR if(umur<tepiBawah||umur>tepiAtas) throw new AgeInputException(tepiBawah,tepiAtas,umur); return umur; } catch(InputMismatchException e){ scanner.next(); System.out.println("Input is invalid \n" + "Please enter digit Only"); } } } private void init(int low,int high){ tepiBawah=low; tepiAtas=high; } }
Are you guys know where's my mistake?
thanks btw.