0

I get Scanner errors when running the following code: How can that be?

import java.util.Scanner;

public class ComputeLoan {
    public static void main(String[] args) {
    // Create a Scanner
    Scanner input = new Scanner(System.in);

    //Enter annual interest rate in percentage e.g., 7.25%
    System.out.print("Enter annual interest rate in, e.g., 7.25%: ");
    double annualInterestRate = input.nextDouble();

    // Obtain monthly interest rate
    double monthlyInterestRate = annualInterestRate / 1200;

    //Enter number of years
    System.out.print(
      "Enter number of years as an integer, e.g., 5: ");
    int numberOfYears = input.nextInt();

    // Enter loan amount
    double loanAmount = input.nextDouble();

    // Calculate payment
    double monthlyPayment = loanAmount * monthlyInterestRate / (1 - 1 / Math.pow(1 +     
    monthlyInterestRate, numberOfYears * 12));

    double totalPayment = monthlyPayment * numberOfYears * 12;


    // Display results
    System.out.println("The monthly payment is $" + (int) (monthlyPayment * 100) / 100.0);
    System.out.println("The total payment is $" + (int) (totalPayment * 100) / 100.0);

    }
}

Console:

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:864)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at ComputeLoan.main(ComputeLoan.java:10)
Infinite Recursion
  • 6,315
  • 28
  • 36
  • 51
Morten Falk
  • 69
  • 2
  • 8

3 Answers3

4

Here :

 System.out.print("Enter annual interest rate in, e.g., 7.25%: ");
 double annualInterestRate = input.nextDouble();

When you are entering value on the console, enter it as 7.25 and NOT as 7.25%

A good practice to follow : When accepting values from the user on the command line, always accept them in the form of String i.e. input.nextLine() and then parse it to appropriate type using parse method. If an exception occurs while parsing, it means that input was not properly entered by the user, notify the user about it and continue.

Example :

while(true) {
      try {
            System.out.print("Enter annual interest rate in, e.g., 7.25%: ");
            double annualInterestRate = Double.parseDouble(input.nextLine());
            break;
          } 
     catch(NumberFormatException nfe) {
                System.out.print("Wrong input,enter again");
            }
       }
Sagar D
  • 3,016
  • 1
  • 15
  • 32
3

Cause:

InputMismatchException is

Thrown by a Scanner to indicate that the token retrieved does not match the pattern for the expected type, or that the token is out of range for the expected type.

The exception occurs because you are entering String "7.25%" and trying to retrieve Double and int from the Scanner using input.nextInt() and input.nextDouble().

Solution:

You can read line from the Scanner and then parse the values from the String using

Read String from user and parse double value:

    // Enter annual interest rate in percentage e.g., 7.25%
    System.out.print("Enter annual interest rate in, e.g., 7.25%: ");
     //read the line
    String inputStr = input.nextLine();

    //parse the double value after removing the % sign
    double annualInterestRate = Double.parseDouble(inputStr.replace("%", "")); 

Similarly:

    // Enter number of years
    System.out.print("Enter number of years as an integer, e.g., 5: ");
     //read the line
    inputStr = input.nextLine();
    //parse the int value from the input String
    int numberOfYears = Integer.parseInt(inputStr);
Community
  • 1
  • 1
Infinite Recursion
  • 6,315
  • 28
  • 36
  • 51
  • 2
    nice answer if everyone took this much time to properly format their answers the site would be unbelievable! –  Sep 13 '15 at 06:33
2

When I type in the following I do get the output:

Enter annual interest rate in, e.g., 7.25%: 7.25

Enter number of years as an integer, e.g., 5: 7

3

The monthly payment is $0.04

The total payment is $3.83

Process finished with exit code 0

I hope you know what exit code 0 is :)

However, the problem with your code is,

  1. I had to type in some random integer, here in my case, '3' for the monthly payment and total payment processes to take place.

  2. Like it had been pointed out, you don't type in 7.25%. input.nextDouble() placeholder doesn't expect that kind of data to hold, simply put. Type in any 'double' number and it will work.

Thank you