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 }
}
Related
I'm practicing a simple Java GUI by making a login system without a database, but my if statement using .equals doesn't work because it always says incorrect password.
contains() work but I think it's not that secure
String user = USERNAME.getText();
String pass = PASSWORD.getText();
if(user.equals("username") && pass.equals("password") ){
JOptionPane.showMessageDialog(null, "Welcome to GUI");
} else {
JOptionPane.showMessageDialog(null, "Wrong Username and password");
}
As #MadProgrammer pointed out that equals() is a case sensitive method.
"password1" is NOT EQUAL to "PASSWORD1" //The strings should match with case.
Also to avoid NullPointerException a better way is
String user = USERNAME.getText();
String pass = PASSWORD.getText();
if ("username".equals(user) && "password".equals(pass)) {
JOptionPane.showMessageDialog(null, "Welcome to GUI");
} else {
JOptionPane.showMessageDialog(null, "Wrong Username and password");
}
I am trying to make it so that if the username and / or password aren't correct, the program will run it over again, instead of just doing the print command in the else statement. I tried putting another while loop in the else statement and nesting the if statement inside that checks the username and password inside of it, but then I realized I would have to copy all the code from the if statement into the else statement, which obviously seems like it is not the correct solution and is probably very clunky. What is the right way to refer the program back to run from the start or something?
// Declare Variables
Scanner input = new Scanner(System.in);
String username;
String password;
String calculator = "calculator";
String renameUser = "renameUser";
String renamePass = "renamePass";
String getIp = "getIp";
String exit = "exit";
String command;
// Prompt User to login
System.out.println("Username: ");
username = input.nextLine();
System.out.println("Password: ");
password = input.nextLine();
if (username.equals("admin") && password.equals("admin") ) // Must use the equals method of string class to compare, == operator will NOT work.
{
System.out.println("Success! Welcome " + username + "!");
while (true) // Infinite loop using the true statement
{ command = input.nextLine();
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{ // renameUser code here
if (command.equals(renamePass))
{ // renamePass code here
if (command.equals(getIp))
{ // getIp code here
if(command.equals(exit))
{
break;
}
System.out.println("Logging out!");
}
}
}
}
}
}
else
{
System.out.println("Wrong username or password, please try again.");
}
}
}
Think about the below logic
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{
If command equals calculator then how can it equal renameUser
You should have it
if (....) {
}
else if (...) {
}
statement or as a switch statement
This snippet here is increasing the cyclomatic complexity of your software making it hard to make a decision, if you want to change that later, you have more chances to break the code than success
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{ // renameUser code here
if (command.equals(renamePass))
{ // renamePass code here
if (command.equals(getIp))
{ // getIp code here
if(command.equals(exit))
{
try to design something more like a witch case logic
Example:
switch (userInput) {
case renameUser:
renameUser();
break;
case getIp:
getIp();
break;
...
default:
break;
}
I first want to validate that the user entered a value and to make sure to exit if 'cancel' was pushed. Then, I want to validate that the String releaseDateString is in the correct format at the same time as converting the String to java.sql.Date.
The first validation is taking place but then the JOptionPane carries on repeating itself and does not even consider the try and catch following it.
Here is my method
boolean retry = false;
java.sql.Date releaseDate = null;
String releaseDateString = "";
String title = "";
while (!retry) {
while(!retry){//field is validated to make sure a value was entered and to exit if cancel was pushed
releaseDateString = JOptionPane.showInputDialog("Please input the release date of the movie (yyyy-mm-dd)");
qtd.stringValidation(releaseDateString);
}
try { //the date is validated to make sure it is in the correct format
releaseDate = java.sql.Date.valueOf(releaseDateString);
} catch (Exception e) {
retry = false;
JOptionPane.showMessageDialog(null, "Make sure you enter a date in the format of 'dd-mm-yyy'");
}
}
It links to this method
public static boolean stringValidation(String attribute){
boolean retry = false;
if (attribute == null){
System.exit(0);
}
else if (attribute.equals("")) //if the cancel button is selected or no value was entered into the
{
JOptionPane.showMessageDialog(null, "Make sure you enter a character into the textbox");
}
else {
retry = true;
}
return retry;
}
When you do this,
qtd.stringValidation(releaseDateString);
You aren't assigning the result to retry. I believe you wanted,
retry = qtd.stringValidation(releaseDateString);
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 );
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);
}
}
}
}