I have to create a calculator application at school and the calculator is working fine, but now I have to create an exception that shows a user friendly message when the user enters a string instead of an integer value.
This is the code I have now with a JFrame and everything:
private void minActionPerformed(java.awt.event.ActionEvent evt) {
String invoerEen = getalEen.getText();
int invoerEenDef = Integer.parseInt(invoerEen);
String invoerTwee = getalTwee.getText();
int invoerTweeDef = Integer.parseInt(invoerTwee);
int resultaatDef = invoerEenDef - invoerTweeDef;
resultaat.setText(Integer.toString(resultaatDef));
}
private void plusActionPerformed(java.awt.event.ActionEvent evt) {
String invoerEen = getalEen.getText();
int invoerEenDef = Integer.parseInt(invoerEen);
String invoerTwee = getalTwee.getText();
int invoerTweeDef = Integer.parseInt(invoerTwee);
int resultaatDef = invoerEenDef + invoerTweeDef;
resultaat.setText(Integer.toString(resultaatDef));
}
private void keerActionPerformed(java.awt.event.ActionEvent evt) {
String invoerEen = getalEen.getText();
int invoerEenDef = Integer.parseInt(invoerEen);
String invoerTwee = getalTwee.getText();
int invoerTweeDef = Integer.parseInt(invoerTwee);
int resultaatDef = invoerEenDef * invoerTweeDef;
resultaat.setText(Integer.toString(resultaatDef));
}
private void delenActionPerformed(java.awt.event.ActionEvent evt) {
String invoerEen = getalEen.getText();
int invoerEenDef = Integer.parseInt(invoerEen);
String invoerTwee = getalTwee.getText();
int invoerTweeDef = Integer.parseInt(invoerTwee);
int resultaatDef = invoerEenDef / invoerTweeDef;
resultaat.setText(Integer.toString(resultaatDef));
}
This code contains all the events and the actions they perform (the first one is for subtraction etc...). I use Netbeans as my development environment and I've tried adding try and catch statements like so:
try {
String invoerEen = getalEen.getText();
int invoerEenDef = Integer.parseInt(invoerEen);
String invoerTwee = getalTwee.getText();
int invoerTweeDef = Integer.parseInt(invoerTwee);
int resultaatDef = invoerEenDef - invoerTweeDef;
resultaat.setText(Integer.toString(resultaatDef));
}
catch(/* what do I put here? */) {
// what do I do here?
}
So my question is, how do I create an exception for when a user enters a value that's not the correct return type (required: Integer, found: String).
Doubles or other return types are not important at the moment, only string.
Thanks in advance!