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 );
Related
I am trying to make a practice program for a bookstore clerk that allows the clerk to add, remove, edit, and search for books in its database. I have all but made the entire program however I am getting stuck on 2 errors. It is a total of 234 lines of code in all so I will try to shorten it to the relevant parts to make it easier on those willing to help me. I am using Eclipse with JDE and JDK 10. The Eclipse project was initiated using the JavaSE-10 execution environment as far as I am aware. Below are the 2 methods causing the errors.
public class Bookstore {
public static void main(String[] args) {
try(
//Creating table connection and statement
Connection conn = DriverManager.getConnection("***********",
"****", "*********"); //Please note that I blocked out the actual connection information here
Statement stmt = conn.createStatement();
){
Scanner input = new Scanner(System.in);
int selection = 0;
//Menu for action selection and user input
while(selection != 5) {
System.out.println("Please enter the number corresponding to the action you would like to take:\n"
+ "1. Enter book\n"
+ "2. Update book\n"
+ "3. Delete book\n"
+ "4. Search books\n"
+ "5. Exit");
selection = input.nextInt();
//Selection sorting
if(selection == 1) {
//Collecting book information
System.out.println("Please enter the Title of the book you would like to put into the system: ");
String title = input.next();
System.out.println("Please enter the Author of said book: ");
String author = input.next();
System.out.println("Please enter the number of said book currently in stock: ");
int qty = input.nextInt();
//Sending info to the addBook method
addBook(title, author, qty, stmt);
} else if(selection == 2) {
//Collecting book information
System.out.println("Please enter the id of the book you would like to update: ");
int id = input.nextInt();
//Sending info to the updateBook method
updateBook(id, stmt);
} else if(selection == 3) {
//Collecting book information
System.out.print("Please enter the id of the book you would like to delete from the system: ");
int id = input.nextInt();
//Sending info to deleteBook method
deleteBook(id, stmt);
} else if(selection == 4) {
searchStore(stmt);
} else if(selection == 5) {
System.out.println("Goodbye");
input.close();
} else { //Invalid entry handler
System.out.println("Sorry, that isn't a valid selection.");
}
}
} catch(SQLException ex) {
ex.printStackTrace();
}
}
} //This is the line giving me the error "Syntax error on token "}", delete this token"
Now I have already done some research regarding the error at the bottom of this block of code. As far as I can tell I am not missing any brackets and there are no variables or anything being created outside of a class that would cause this error. The only other solution I have been able to find is that "Eclipse is just being weird".
My second error comes from this block of code:
public static void resultSetPrinter(ResultSet rset) {
while(rset.next()) {
String title = rset.getString("Title");
String author = rset.getString("Author");
int qty = rset.getInt("qty");
System.out.println("Title: " + title + "\nAuthor: " + author + "\nNumber in stock: " + qty + "\n\n");
}
if(rset == null) {
System.out.println("No records for the entry could be found.");
}
} //This is the line giving me the "Syntax error, insert "}" to complete ClassBody" error
I have also done some research regarding the error at the bottom of this block and when I do remove the bracket as requested the error just jumps up to the method before this one. I haven't included the other 4 methods in the class to try and reduce the headache of running through all this code since they aren't giving me errors. Any help would be greatly appreciated at this point, I am completely stumped.
Thanks mainly to Elliott Frisch I have found my answer. Essentially I needed to put all my methods into my main class by the name of Bookstore. I moved the } to the end of my program and added try catch statements for each method. For example I changed the last code block I put in my question to:
public static void resultSetPrinter(ResultSet rset) {
try {
if(rset.next()) {
while(rset.next()) {
String title = rset.getString("Title");
String author = rset.getString("Author");
int qty = rset.getInt("Qty");
System.out.println("Title: " + title + "\nAuthor: " + author + "\nNumber in stock: " + qty + "\n");
}
} else {
System.out.println("No records for the entry could be found.\n");
}
} catch(SQLException ex) {
ex.printStackTrace();
}
}
You'll also note that I added an if else statement to check if the ResultSet rset was empty, if it wasn't I proceeded as normal and if it was I printed a simple message to let the user know nothing was found.
Thank you both Elliott Frisch and Marco13 for the asssistance.
So there is this certain part of my program where I can create an account and the created account will be inserted into my database. And I'm trying to code something where *refer to the code:
public void actionPerformed(ActionEvent e) {
String user = userField.getText().trim();
String pass = passField.getText().trim();
String conPass = confirmPass.getText().trim();
try{
// TODO Auto-generated method stub
if(e.getSource()==submit){
if (user.equals(user)&&pass.length()==0){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if the pass field is blank
else if(user.length()<5){
JOptionPane.showMessageDialog(null,"Username must be at least 5 characters!");
}
else if(user.equals(user)&&pass.equals(conPass)&&pass.length()!=0){
String sqlLogin = "insert into tblLogin (username,pssword) values ('"+user+"','"+pass+"')";;
getQuery(sqlLogin);
JOptionPane.showMessageDialog(null, "Account Successfully Created!");
create.dispose();
GUI gui = new GUI();
}//if(pass.equals(conPass))
else if(user.length()==0&&pass.length()==0){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if both fields are blank
else if (user.length()==0 &&pass.equals(pass)){
JOptionPane.showMessageDialog(null, "Fill in the empty field!");
}//check if user field is blank
else if(user.equals(user)&&pass!=conPass){
JOptionPane.showMessageDialog(null, "Password do not match!");
}//check if password and confirm pass matches
}
I dont really know how to say the problem but look in the if and else if statements, if the user meet one the those conditions, the program should print the JOptionPane thing. Except for the second else if.
You might be wondering why I put these codes at my else if
else if(user.equals(user)&&pass.equals(conPass)&&pass.length()!=0){
String sqlLogin = "insert into tblLogin (username,pssword) values ('"+user+"','"+pass+"')";;
getQuery(sqlLogin);
JOptionPane.showMessageDialog(null, "Account Successfully Created!");
create.dispose();
The reason for this is that, my program is having some logic error when I try to put it in if statement. Please help me with my code thanks :) Feel free to write a new code for me :DD
i might try something like this:
public static boolean isSet(String s){
if(s==null || "".equals(s)) return false;
return true;
}
//.... your validation here
if(isSet(user) && isSet(pass) && isSet(conPass) && pass.equals(conPass)){
//create account
}else{
//smth wrong eg. if(!pass.equals(conPass) { //wrongpass }
}
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.
i am trying to have a check on that if value is null then don't show the message and recall the constructor, i did the following way but its not working.
if (title == null) {
JOptionPane.showMessageDialog(null, "Please Enter All Values");
new InfoFrame();
}
else {
try {
System.out.println(title+""+date);
System.out.println(title+""+date);
s.execute("INSERT INTO task ([title],[deadline],[priority],[time]) VALUES ('"+ title+ "','"+ date+ "','"+ priority + "','"+ time + "')");
JOptionPane.showMessageDialog(null,"Your Task has been added to the Database:");
} catch (Exception e) {
System.out.println(e.getMessage());
}
*Edited the var Title like stupid naming conventions
if (Title.isEmpty()) {
Will do the trick.
If you want to check both null or empty
if (Title == null || Title.isEmpty()) {
Also its better to start your variable in simple letters.
I'm creating a method to take an input by a user and validate it to make sure it's correct. If it's correct it will call a method and input the user input in to it. But for some reason, the method call is not working. It doesn't produce any errors, it just simply doesn't do it. I placed a print statement at the end of the code to make sure it actually reaches there and it does, but for some reason it's just not calling the method like it's supposed to. The other method works fine if I call it by itself and input a string via the parameters.
The code is:
public void getGetScheduledShowByFilmInput()////new - omar////
{
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
String filmInput;
filmInput = "";
boolean foundFilm;
foundFilm = false;
System.out.println("Here is a list of films that are currently showing:");
for(Film film : films){
System.out.println(film.getFilmName());
}
System.out.println("");
System.out.println("Please type the film name that you wish to view the corresponding shows for and press enter.");
System.out.println("Type 'exit' and press enter to exit this process.");
while(foundFilm == false){
try{
filmInput = reader.readLine();
}
catch (IOException e){
System.out.println("Error");
}
//If user enters "exit" then return.
if(filmInput.equals("exit")){
return;
}
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName() == filmInput){
foundFilm = true;
break;
}
}
if(foundFilm = true){
System.out.println("Film found.");
}
else{
System.out.println("The film name you entered has not been recognised. Please try again.");
}
}
//Call the function and input the film name input by the user.
getScheduledShowsByFilm(filmInput); ////This is the code that seems to be the problem.
System.out.println("reached bottom");
}
and the second method is:
public void getScheduledShowsByFilm(String inputFilmName)
{
ArrayList<Show> scheduledShows;
scheduledShows = new ArrayList<Show>();
for(Film film : films){
if(inputFilmName == film.getFilmName()){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}
for(Show show : scheduledShows){
System.out.println("**********************************");
show.getShowDetails();
System.out.println("**********************************");
}
}
The second method works perfectly when I call it on its own and enter parameters manually though.
It's probably something extremely simple that I'm not understanding! haha, thank you for your help :)
foundFilm can never be false because you always assign true to it:
if(foundFilm = true){
System.out.println("Film found.");
}
try changing it to this:
if(foundFilm)
{
System.out.println("Film found.");
}
In getGetScheduledShowByFilmInput() and getScheduledShowsByFilm(String) avoid doing string comparison using the equality operator (==). The == operator tests for object equality, but you want to test whether two strings contain the same sequence of characters. Therefore, use equals instead:
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName().equals(filmInput)){
foundFilm = true;
break;
}
}
and
for(Film film : films){
if(inputFilmName.equals(film.getFilmName())){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}