The while loop keeps evaluating to false immediately. I do not know or understand what is wrong with the do...while statement, saying that the index is out of bounds for a length of 0, I am confused, but I will keep trying to work on a solution in the mean time.
import java.util.Scanner; //Importing Scanner
import java.io.*;
public class AmortDemo
{
public static void main(String[] args) throws IOException
{
double inputLoan;
int inputYear;
double inputRate;
String input;
char again;
Scanner kb = new Scanner(System.in);
do
{
System.out.print("Please enter loan amount: ");
inputLoan = kb.nextDouble();
while (inputLoan <= 0)
{
System.out.println("Invalid input. Please try again: ");
inputLoan = kb.nextDouble();
}
System.out.print("Please enter annual interest rate: ");
inputRate = kb.nextDouble();
while (inputRate <= 0)
{
System.out.println("Invalid input. Please try again: ");
inputRate = kb.nextDouble();
}
System.out.print("Please enter years of the loan: ");
inputYear = kb.nextInt();
while (inputYear <= 0)
{
System.out.println("Invalid input. Please try again: ");
inputYear = kb.nextInt();
}
Amortization james = new Amortization(inputLoan, inputYear, inputRate);
james.createReport("LoanAmortization.txt");
System.out.println();
System.out.println("Report saved to the file LoanAmortization.txt.");
System.out.print("Run another report? Y for yes and N for no. ");
input = kb.nextLine();
again = input.charAt(0);
} while(again == 'y' || again == 'Y');
}
}
Yeah it is known behavior of the scanner. If you have nextInt()
and then nextLine()
, somehow Scanner does not read new line character. So when you pressed there new line when entering number, it will stay in the buffer, and will be consumed by next method that uses it. In your case nextLine()
.
Solution would be to change code to:
System.out.print("Run another report? Y for yes and N for no. ");
kb.nextLine();
input = kb.nextLine();
again = input.charAt(0);
so simply adding just before reading nextLine to input, yet another kb.nextLine().