String out of Range, Help please
I am unsure what to do as I am quite new to Java. I want to repeat this program again but it keeps giving me the error of my string being out of range. How do I approach this?
import java.util.Scanner;
import java.io.*;
public class LoanReport {
public static void main(String[] args) throws IOException {
double loanBalance;
double interestRate;
int loanYears;
String answer;
char again;
// boolean again;
Scanner keyboard = new Scanner(System.in);
// while(again)
// do{
System.out.print(&qu开发者_如何学Pythonot;Enter the " + "loan amount.");
loanBalance = keyboard.nextDouble();
System.out.print("Enter the " + "annual interest rate.");
interestRate = keyboard.nextDouble();
System.out.print("Enter the " + "years of the loan.");
loanYears = keyboard.nextInt();
Amortization am = new Amortization(loanBalance, interestRate, loanYears);
am.saveReport("LoanAmortization.txt");
System.out.println("Report saved to " + "the file LoanAmortization.txt.");
System.out.print("Would you like " + "to run another report? Enter Y for " + "yes or N for no: ");
//answer = keyboard.next();
// again = answer.charAt(0);
//}
//while(answer == 'Y' || answer == 'y');
answer = keyboard.nextLine();
again = answer.charAt(0);
if (again == 'N' || again == 'n') {
System.exit(0);
}
}
}
I tried doing a boolean method but I'm unsure if I did that correctly.
String out of range error occurs when you are trying to access a position in a string, in this case answer.charAt(0)
, that does not exist.
nextLine():
Advances this scanner past the current line and returns the input that was skipped.
next():
Finds and returns the next complete token from this scanner.
See more here
Try using:
answer = keyboard.next()
instead of:
answer = keyboard.nextLine();
Also, use answer.equals("N")
instead of if (answer == "N")
, the later one is comparing the reference of the value.
精彩评论