I am trying to make a simple calculator program where a user can opt to do an operation and enter the numbers as long as he/she wishes to.
I just have problem because whenever I would reach inside my loop and ask the user if he/she want to continue and whenever I would run the program, I would have an “Exception in thread “main” java.lang.NullPointerException”
Scanner myInput=new Scanner(System.in);
System.out.print("Do you have numbers to compute?");
ans=myInput.findInLine(".").charAt(0);
while ((ans=='Y')||(ans=='y'))
{
//get the numbers
//provide the menu
//get the user's choice
switch (calc)
{
case 1: out.println("Sum is: " +(num1+num2)); break;
case 2: out.println("Difference is: " +(num1-num2)); break;
case 3: out.println("Product is: " +(num1*num2)); break;
case 4: out.println("Quotient is: " +(num1/num2)); break;
case 5: out.println("Modulo is is: " +(num1%num2)); break;
case 6: out.println("Sum is: " +(num1+num2));
out.println("Difference is: " +(num1-num2));
out.println("Product is: " +(num1*num2));
out.println("Quotient is: " +(num1/num2));
out.println("Modulo is is: " +(num1%num2)); break;
default: out.println("Invalid."); break;
}
out.println("Compute another?");
ans=myInput.findInLine(".").charAt(0);
}
May I humbly ask what can I do with this program so that it will ask again for the user’s input whether to continue or not? Thanks in advance for your help.
The
NullPointerExceptionis being thrown asScanner.findInLine()can return null if it does not find the requested String/Pattern. The code invokes the methodcharAt(0)on the null String. Changing the code to the following will resolve this: