I’m new to java so forgive the noob question.
I have created a swing application that basically has three input strings in JTextFields:
loanAmount, interestRate and loanYears and a single submit button with the EventAction.
I’m trying to use the java.util.Scanner to parse the input to primitive types that I can use in calculations.
I’m getting an error in NetBeans indicating that my variables are not recognized?
should I not be calling System.in?
private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {
Scanner keyInput = new Scanner(System.in);
while (true)
try{
double amount = keyInput.nextDouble(loanAmount.getText());
double interest = keyInput.nextDouble(interestRate.getText());
int years = keyInput.nextInt(loanYears.getText());
} catch (NumberFormatException nfe){
}
}
Don’t worry about asking easier questions, we get them all the time. If it wasn’t for easy questions, actually, I’d never get to answer anything.
I can see three problems with your code straight away:
You’re catching an exception but then discarding it. There are times when you want to take no action in response to an exception, from a user’s perspective, but as a programmer you’ll want to know. Try saying
nfe.printStackTrace(System.err);Scanner isn’t what you’re looking for. Double.valueOf(..) would be more direct.
Now, as for your actual problem: Your three variables go out of scope at the end of the
tryblock. Try declaring them up where you declare KeyInput.