Throw new exception - java

I have a problem in my code regarding throw new exception.
In one of the JTextField I enter number 0 but it is incorrect and after I click "ENTER" botton in this moment there is thrown new exception message:
throw new Exception("Wrong number of express lanes range beginnig!! \n Please enter positive number!");
The box message appear with error message I can only click "OK". After I click "Ok" I want that the program stop because I want to correct wrong data in the JTextField. I can't do that because after I click "OK the program continues process. How can I stop the program and correct the data?
Here is important part of the code where I see I have a problem.
public class UILayer
{
private JTextField text1, text2, text3, text4, text5, text6;
private void validateNumbers() throws Exception
{
if(!text1.getText().equals("") &&
Integer.parseInt(text1.getText()) <= 0 )
throw new Exception("Wrong number of lanes!! \n Please enter positive number!");
if(!text2.getText().equals("") &&
Integer.parseInt(text2.getText()) <= 0 )
throw new Exception("Wrong number of express lanes!! \n Please enter positive number!");
if(!text3.getText().equals("") &&
Integer.parseInt(text3.getText()) <= 0 )
throw new Exception("Wrong number of express lanes range beginnig!! \n Please enter positive number!");
if(!text4.getText().equals("") &&
Integer.parseInt(text4.getText()) <= 0 )
throw new Exception("Wrong number of express lanes range ending!! \n Please enter positive number!");
if(!text5.getText().equals("") &&
Integer.parseInt(text5.getText()) <= 0 )
throw new Exception("Wrong number of customers!! \n Please enter positive number!");
if(!text6.getText().equals("") &&
Integer.parseInt(text6.getText()) <= 0 )
throw new Exception("Wrong number of max items!! \n Please enter positive number!");
}
protected class EnterClickListener implements ActionListener
{
private SimulationConfig info;
EnterClickListener( )
{
info = new SimulationConfig();
}
#Override
public void actionPerformed( ActionEvent event )
{
try
{
if(!(event.getActionCommand().equals(null )))
{
validateForm();
validateNumbers();
}
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog( null, "Error.\nPlease enter number.",
"Message", JOptionPane.INFORMATION_MESSAGE );
}
catch (Exception e)
{
JOptionPane.showMessageDialog( null, "Error.\n" + e.getMessage() ,
"Message", JOptionPane.INFORMATION_MESSAGE );
}
info.setCustomerRestriction(Integer.parseInt(text5.getText()), Integer.parseInt(text6.getText()));
info.setExpressRange(Integer.parseInt(text3.getText()), Integer.parseInt(text4.getText()));
info.setLanesNum(Integer.parseInt(text1.getText()), Integer.parseInt(text2.getText()));
showProgressBar();
task = blayer.startSimulation(info);
task.addPropertyChangeListener(new PropertyChangeListener());
task.execute();
}
}

put your code
info.setCustomerRestriction(Integer.parseInt(text5.getText())....
......
task.execute();
inside try, after if. like this:
#Override
public void actionPerformed( ActionEvent event )
{
try
{
if(!(event.getActionCommand().equals(null )))
{
validateForm();
validateNumbers();
info.setCustomerRestriction(Integer.parseInt(text5.getText()), Integer.parseInt(text6.getText()));
info.setExpressRange(Integer.parseInt(text3.getText()), Integer.parseInt(text4.getText()));
info.setLanesNum(Integer.parseInt(text1.getText()), Integer.parseInt(text2.getText()));
showProgressBar();
task = blayer.startSimulation(info);
task.addPropertyChangeListener(new PropertyChangeListener());
task.execute();
}
}
catch(NumberFormatException e)
{
JOptionPane.showMessageDialog( null, "Error.\nPlease enter number.",
"Message", JOptionPane.INFORMATION_MESSAGE );
}
catch (Exception e)
{
JOptionPane.showMessageDialog( null, "Error.\n" + e.getMessage() ,
"Message", JOptionPane.INFORMATION_MESSAGE );
}
}

Solution provided by PC is quite better an alternate is just write a user defined Exception class that has the ability to abort the further program execution, as you can reuse it and thus no need of writing same code again(In case if you are going to handle the same Exception in multiple places or java classes).
What you need to do is:
Take a public class extending to RuntimeException, Exception or
Throwable according to your requirement
Take a public constructor with a String parameter
Call to super(your_String_parameter_here); form inside of your
constructor(So that if you are skipping to handle this Exception and
direct handle to Super class Exception the appropriate message can
be passed up to there)
override toString() method to provide proper string message for your
Exception class object
Now you can reuse this Exception class any where in your code.

Related

String data still remains? (Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string)

I am trying out to code a simple arithmetic game in Java but I faced an error like: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string. This happens when I clicked on number buttons and cleared them to enter a new number but it seems that the string still contains the previous number I clicked. (For example, I clicked 5 and deleted it so I could enter 9 instead and now the string seems to register it as 59 instead of just 9.) I used .setText('') to clear the text area.
This is my code for when the buttons are pressed:
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("one"))
{
answerText.append("1");
userAnswer = userAnswer + "1";
}
// same code for two, three, four... to nine.
if(e.getActionCommand().equals("enter"))
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
}
The answer variable and delete button is :
answerText = new JTextArea();
answerText.setEditable(false);
clearbtn = new JButton("Clear");
clearbtn.setActionCommand("clear");
clearAnswer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
answerText.setText("");
}
});
How do I make sure that my answerText is completely clear?
Your error message:
java.lang.NumberFormatException: For input string
This means that you are trying to parse a string into a number, but the string contains something that cannot be parsed into a number. Java prints the content of the string after the text For input string. In this case there's nothing after that text, because the string that you are trying to parse is the empty string - that you set in the text box by calling answerText.setText("");
Solution: Check if the string you are trying to parse is empty before you try to parse it into a number. For example:
if (e.getActionCommand().equals("enter"))
{
if (!"".equals(userAnswer)) // Check if userAnswer is not empty
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a number before pressing Enter.");
}
}
The variable userAnswer doesn't get cleared when answerText is cleared. This might cause issues.
The exception you are having is probably being cause because int userValue = new Integer(userAnswer); is called at a point where userAnswer is empty (because it can't make a number out of nothing).

Add dialog box when the program is clossed

I want to add an option when somebody closes the frame to check if are there any thread running and if there are any I want to display a dialog box which should ask the user if he really wants to exit. The problem is that no matter which is the option of the user the program closes anyway.
Here is what I tried:
private void addActionWhenFrameIsClosed( )
{
addWindowListener( new WindowAdapter( )
{
public void windowClosing( WindowEvent e )
{
if( isThereAnyThreadRunning( ) )
{
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog( null, "There are some threads running... "
+ "\nAre you sure you want to exit?",
"Warning", dialogButton );
if( dialogResult == JOptionPane.YES_OPTION)
{
dispose( );
}
}
}
} );
}
Please try adding this line of code as first line in addActionWhenFrameIsClosed
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

JOptionPane cancel button and getting input

I'm trying to get the user to input there name if it is left blank it will ask again, if they fill it out it sets a JLabel or hit cancel to get out.
My last if statement is wrong it does not like nameEnt.
public Player() {
//setBackground(Color.green);
setSize(600, 400);
name = new JLabel();//Input hint
JOptionPane nameOption = new JOptionPane();
String nameEnt = nameOption.showInputDialog("First Name: ");
if (!nameEnt.matches("[a-zA-Z]+")) {
name.setText(nameEnt);
}
if (nameEnt.length() == 0) {
//if this condition is true JOption stays until name is entered or canceled
}
if (nameEnt == nameOption.CANCEL_OPTION) {
System.exit(0);
}
}
The JOptionPane.CANCEL_OPTION is a static int field, and you can't compare String with int with ==.
Good practice
In your case you want to use ok and cancel button JOptionPane.showConfirmDialog and JOptionPane.showInputDialog() in one shot and this is not possible, i suggest to use this instead :
JTextField nameF = new JTextField(20);//create TextField
JPanel myPanel = new JPanel();//cerate JPanel
myPanel.add(new JLabel("Name"));
myPanel.add(nameF);//add your JTextField to your panel
int result;
do {
result = JOptionPane.showConfirmDialog(null, myPanel,
"Title of Panel", JOptionPane.OK_CANCEL_OPTION);//add your panel to JOptionPane
if (result == JOptionPane.OK_OPTION) {//if the user press OK then
if (nameF.getText().isEmpty()) {//check if the input is empty
//if this condition is true JOption stays until name is entered or canceled
} else if (!nameF.getText().matches("[a-zA-Z]+")) {//check if the input match with your regex
//name match exactly
//name.setText(nameF.getText());
}
}
} while (result != JOptionPane.CANCEL_OPTION);//If the user hit cancel then exit
As per the JOptionPane API, if the user cancels the dialog, null is returned.
And so the correct solution is to to not to use equals, but rather to check the return value for null and to do this first, before checking its length.
public Player() {
//setBackground(Color.green);
setSize(600, 400);
name = new JLabel();//Input hint
JOptionPane nameOption = new JOptionPane();
String nameEnt = nameOption.showInputDialog("First Name: ");
if (nameEnt == null) {
// user canceled. get out of here.
System.exit(0);
// or return;
// or throw some exception
}
if (!nameEnt.matches("[a-zA-Z]+")) {
name.setText(nameEnt);
}
if (nameEnt.length() == 0) {
//if this condition is true JOption stays until name is entered or canceled
}
// if (nameEnt == nameOption.CANCEL_OPTION) {
// System.exit(0);
// }
}
But why are you creating a JOptionPane this way? Better to use the static method of creation.
// don't use null as the first parameter if the GUI is already showing
String nameEnt = JOptionPane.showInputDialog(null, "First Name: ");
if (nameEnt == null) {
// user canceled. get out of here.
System.exit(0);
}
Or maybe something like this, if you're trying to loop to get input:
public Player() {
setSize(600, 400); // This is not good to do. Ask for details and I'll tell.
name = new JLabel();// Don't forget to add this to the GUI!
String nameEnt = "";
while (nameEnt.trim().isEmpty()) {
// if the GUI is already showing, pass a component from it as the first param here, not null
nameEnt = JOptionPane.showInputDialog(null, "First Name: ");
if (nameEnt == null) {
// user canceled. get out of here.
System.exit(0);
// or return;
// or throw some exception
} else if (!nameEnt.matches("[a-zA-Z]+")) {
name.setText(nameEnt);
} else {
// set it to "" so that we keep looping
nameEnt = "";
}
}
}

how to call recursively a method in a try-catch block

hi i have this problem i got a method that let a user insert a value representing the "quantity" of a product, now if the quantity wanted by the user is higher then the stock quanity it has to throw an exception and let the user input again the number i tryed it inserting a recursive call of the same method but even if it success it goes in an infinite loop like the exception is still "alive"
...
try {
if (!lol2)
throw new NegativeNumberException();
} catch (NegativeNumberException pto) {
JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
this.addToCart(cart,quant);
}
EDIT i am including now all the code but it's a bit hard so sry for the "complexity" of the code
FULL CODE
public void addToCart(ArrayList<Utilizzabile> cart,ArrayList<Integer> quant) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
boolean lol=false;
Utilizzabile us=null;
String id = JOptionPane.showInputDialog(frame, "Inserisci un ID prodotto:");
if (id ==null) { return;}
while (!id.matches("[0-9]+")) { //user inserts a value and the while checks for an int value inserted
JOptionPane.showMessageDialog(frame, "Valore inserito errato");
id = JOptionPane.showInputDialog(frame, "Inserisci un ID prodotto:");
if (id == null) { return;} }
int iden = Integer.parseInt(id);
for (Utilizzabile u: arr) { // this for loop checks if the ID inserted represents a product in the catalog
if ((u.getId() == iden) && (u.eAcquistabile())) {
lol =true;
us = u; } }
if (lol == true) { //now if the ID corresponds to an existent product it ask the user to input the quantity requested
boolean lol2=false;
String qua = JOptionPane.showInputDialog(frame, "Inserisci un quantità da aggiungere al carrello:");
if (qua ==null) { return;}
while (lol2==false) {
while (!qua.matches("[0-9]+")) {
JOptionPane.showMessageDialog(frame, "Valore inserito errato");
qua = JOptionPane.showInputDialog(frame, "Inserisci un quantità da aggiungere al carrello:");
if (qua == null) { return;} }
if (qua.length()>0 && qua.length()<=8) {
int quantit = Integer.parseInt(qua);
for (int l=0;l<cart.size();l++) { //this for checks if in the cart were already that product and then changes the quantities only
if ((cart.get(l).getId() == us.getId()) && (us.getRem()-quantit >0) ) {
int num = quant.get(l)+quantit;
quant.set(l,num);
JOptionPane.showMessageDialog(frame, "Quantità del prodotto richiesto aggiornata");
return;}
}
if ( (us.getRem()-quantit) >0) { //checks if all went good and the quantity is avaiable
JOptionPane.showMessageDialog(frame, "Prodotto della quantità richiesta aggiunto al carrello");
lol2=true;
cart.add(us);
quant.add(quantit);} }
try {
if (lol2==false)
throw new NegativeNumberException(); }
catch (NegativeNumberException pto){
JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
this.addToCart(cart,quant); }
} }
else {
JOptionPane.showMessageDialog(frame, "Prodotto non trovato");
this.addToCart(cart,quant); }
}
this code essentially is a graphical section for let the user add a product to the cart and check is everything is good but i need to place an exception to check if the quantity in stock is less then the quantity wanted by the user (i ve done it without exception with no problems but this is for an exam and i just noticed that the professor wants that i have to solve this problem by using an exception
It's not good to use recursion for that, because after "n" invocations you can receive StackOverFlowError. And I agree with #laune.
Thus I recommend to use loop. For example:
while (true){
// lol2 here is TRUE if was entered correct value and false if not.
if (lol2)
break;
else {
JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
this.addToCart(cart,quant);
}
}
insert try catch into do while loop.
when user insert correct value stop loop
E.g
int a=10;
do{
try{
if(a<20)
throw new NegativeNumberException();
else
break;
}catch (NegativeNumberException pto){
JOptionPane.showMessageDialog(frame, "Quantità non disponibile");
//enter quantity again
// a=20;
}
}while(true);
Never use exceptions to control the regular or almost regular flow of control. It's bad programming style.
Use some do statement to repeat the dialog until a satisfactory input is achieved.
Due to lack of context, no code is provided. (Where is that recursive call??)
Later
There is room for exception handling, though. You could throw away pattern matching and length check and catch NumberFormatException.
Integer quantity = null;
do {
String id ... dialogue
try {
quantity = Integer.parseInt( id );
if( quantity <= 0 ) throw new NumberFormatException( "only positive integers" );
} catch( NumberFormatException nfe ){
... error dialogue;
quantity = null;
}
} until( quantity != null );

Return to previous ShowInputDialog after ShowMessageDialog

There will be a ShowInputDialog box for user to key in numbers. When user keys in character it will show a MessageDialog box to indicate invalid input.
How do I return to the previous showInputDialog for user to reenter the number after the user click on "OK" button on the MessageDialog box?
The codes:
public static void addStock(Stock s[],int index)
{
s[index] = new Stock();
try{
s[index].setNumber(Double.parseDouble(showInputDialog(null,"Enter number: ")));
}catch(NumberFormatException e){
showMessageDialog(null, "Invalid input. Enter digits only.", "Error!",ERROR_MESSAGE);
}
}
*Edit: It is an inventory system using dialog boxes as the interface to interact with user. For example, to add,delete,update stock in the system.
Try this one :
boolean isValSet = false;
while(!isValSet)
{
try {
String val=JOptionPane.showInputDialog(null,"Enter number: ");
double parseDouble = Double.parseDouble(val);
//set you parseDouble to your attribute.
isValSet=true;
} catch(NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid input. Enter digits only.", "Error!",JOptionPane.ERROR_MESSAGE);
}
}

Categories

Resources