So I made this really hard to follow method a while ago and I came back to add in another indented if statement to check against an array list of Users using a for loop.
Before I added this in, the method worked fine but now I am getting an error on the last 'else' keyword. It says "syntax error. please delete this token".
I have no errors when I delete the last else keyword but I'm not sure why when they are four if keywords - should there not be a fourth else keyword?
Thanks for any help given.
//method to validate input by user to log in
public void validateInput() {
//presence check on username
if (qi.getEnteredName().length() > 0) {
//compare entered username to stored user accounts
for(int i = 0; i < users.size(); i++) {
if (qi.getEnteredName().equalsIgnoreCase(getUserList().get(i).getUsername())) {
//presence check on password
if (qi.getEnteredPass().length > 0) {
//ensures password is at least 6 char long
if(qi.getEnteredPass().length > 5) {
qi.getMainCards().next(qi.getPanels()); //getPanels() == cardPanel
} else {
JOptionPane.showMessageDialog(null,
"Your password must be at least six characters long.",
"Password Violation", JOptionPane.WARNING_MESSAGE);
}
}else {
JOptionPane.showMessageDialog(null,
"Your did not enter a password.",
"Password Violation", JOptionPane.WARNING_MESSAGE);
}
}
else { JOptionPane.showMessageDialog(null,
"You are not registered.",
"User Violation", JOptionPane.WARNING_MESSAGE);
}
else {
JOptionPane.showMessageDialog(null,
"You did not enter a username. Please try again.",
"Username Violation", JOptionPane.WARNING_MESSAGE);
}
}
}
}
Well, basically your last two else statements are matching up with the same if statement which is probably not what you want. You'd have to move the second else statement outside of another }. You have this:
else { JOptionPane.showMessageDialog(null,
"You are not registered.",
"User Violation", JOptionPane.WARNING_MESSAGE);
}
else {
JOptionPane.showMessageDialog(null,
"You did not enter a username. Please try again.",
"Username Violation", JOptionPane.WARNING_MESSAGE);
}
}
But you really want this:
else { JOptionPane.showMessageDialog(null,
"You are not registered.",
"User Violation", JOptionPane.WARNING_MESSAGE);
}
}else {
JOptionPane.showMessageDialog(null,
"You did not enter a username. Please try again.",
"Username Violation", JOptionPane.WARNING_MESSAGE);
}
This is why it's very important to format your code correctly and neatly with proper indentation. In Eclipse (if you're using that) you can select everything and hit ctrl + i (I think) or cmnd + i depending on whether you're using a PC or a mac, and it will properly format your indentation.
That being said, it's probably a lot easier to do if, else if, and else statements than what you're doing here.
You have two else statements.
On the top level you have if, else and another else.
It should be if, else if, and the ultimate condition would be else. If you are dealing with many if statements, every next if should be else if, because else means "if everything else is not true".
You missed the right place in your if statement, as already mentioned by other answers. To prevent such annoying errors I would recommend to organize the code in more readable manner. For your case it could be something similar to (if I got the logic correctly):
public void validateInput() {
final String name = qi.getEnteredName();
final String password = qi.getEnteredPass();
if (empty(name)) {
showWarn("Username Violation", "You did not enter a username. Please try again.");
} else if (!registered(name)) {
showWarn("Username Violation", "You are not registered.");
} else if (empty(password)) {
showWarn("Password Violation", "Your did not enter a password.");
} else if (password.length < 6) {
showWarn("Password Violation", "Your password must be at least six characters long.");
} else {
// we are good
qi.getMainCards().next(qi.getPanels());
}
}
private boolean registered(String name) {
for(int i = 0; i < users.size(); i++) {
if (name.equalsIgnoreCase(getUserList().get(i).getUsername())) {
return true;
}
}
return false;
}
private void showWarn(String title, String message) {
JOptionPane.showMessageDialog(null,
message,
title, JOptionPane.WARNING_MESSAGE);
}
private boolean empty(String string) {
return string != null && !string.isEmpty();
}
Related
I'm working on a Java project, building a simple system, and it has some methods, one of them is "Change PassWord", I put the user's information (username & password) in a text file called ("Users.txt").
Now this is the description of the method:
boolean ChangePassWord(): Asks the user to enter old password for
verification, the user has at maximum three tries to enter correct old
password; if not the password will not be changed and a message Box
will be shown for the user. If user entered correct old password then
he is authenticated to changer his password and asked to enter new
password and confirming the new. Once if confirmed correctly the old
password will be changed to the new one and a message box will be
shown if wrong confirmation the old password will not be changed and a
message box will be shown.
I wrote this code:
boolean changePassword(){
String pass=JOptionPane.showInputDialog(null, "Enter old password: ", "Input", JOptionPane.QUESTION_MESSAGE);
if(pass.equals(Password)) {
String newpass=JOptionPane.showInputDialog(null,
"Enter new password: ", "Input", JOptionPane.QUESTION_MESSAGE);
String connewpass=JOptionPane.showInputDialog(null,
"Enter confirming new password: ", "Input",
JOptionPane.QUESTION_MESSAGE);
if(newpass.equals(connewpass)){
Password= newpass;
JOptionPane.showMessageDialog(null, "password changed ", "message",
JOptionPane.INFORMATION_MESSAGE);
return true;
}
else
JOptionPane.showMessageDialog(null, "Wrong Conferm ", "message",
JOptionPane.INFORMATION_MESSAGE);
}
else
JOptionPane.showMessageDialog(null, "Wrong password ", "message",
JOptionPane.INFORMATION_MESSAGE);
return false;
}
but I think that it's wrong, and I need to use a loop I think.
I hope you help me!
A while loop is appropriate for your case. I will briefly explain how this while loop runs 3 times.
So, first n=3. The condition n-- > 0 means 2 things. Check if n is greater than zero and subtract the value of n by 1. These 2 things happen in that exact order.
So the condition checks that n is indeed greater than zero and enters the loop. At the same time n is also decreased by 1 and becomes 3-1=2.
This goes on 3 times. After the 3rd time, n becomes 0. And the condition 0 > 0 is false and therefore the while loop breaks.
boolean changePassword(){
String pass = ""; //get old password from user
int n = 3;
while (n-- > 0) {
if(pass.equals(Password)) {
String newPass = ""; // get new password from user
String conNewPass = ""; // confirm new password from user
if (newPass.equals(conNewPass)) {
Password = newPass;
// password changed
return true;
} else {
// wrong confirmation.. password not changed
return false;
}
}
else {
// tell user to enter the correct old password
pass = ""; // ask user for old password again
}
}
// show error message that user entered the old password 3 times incorrectly
// and return false
return false;
}
I keep getting a syntax error on my last else statement in a string of if, else if , else , and I can't figure out why nor can I find anywhere that tells me what's really confusing is I have done this type of if else statement setup before and never had this problem. I have tried using 2 coding programs (JCreator and Eclipse) but they both give me an error Eclipse gives me a syntax error on the word else and JCreator on the entire statement saying it has no if statement to pair with it, but I have done one like this and didn't need an if statement as is was the final one.
import java.util.Scanner;
public class Hotel
{
public static void main(String[] args)
{
String answer = "";
Scanner keyboard = new Scanner(System.in);
GuestInterface go = new GuestInterface();
PassswordField hotel = new PassswordField();
System.out.println("do you wish do acces the guest interface or the hotel staff interface? ");
System.out.println("Hint: hotel staff -or- guest");
answer = keyboard.nextLine();
if(answer.equalsIgnoreCase("hotel Staff"))
{
System.out.println("Enter username");
answer = keyboard.nextLine();
hotel.readPassword("Enter Passsword \n ");
System.out.print("\n" + "incorect Password");
System.out.println("System will now shut down");
System.exit(0);
}
else
if(answer.equalsIgnoreCase("Guest"))
{
go.run();
}
else //error throws on this statment
{
System.out.println("uncompatible responce");
System.out.println("System ato shut down activated");
System.exit(0);
}
}
}
You wrote a ; at the end of this line:
if(answer.equalsIgnoreCase("Guest"));
So that is a seperate if-statement. Right after that, you start with this:
{
go.run();
}
else //error throws on this statment
{
// (...)
}
Which makes no sense to the compiler, because it didn't start with an if-statement.
Remove the ; to solve the error.
I have been having some issues when comparing the strings of 2 EditText boxes.
Here is the JAVA:
public void signUpSubmit(View v){
ErrorBox.setText("");
String eAdd = EmailAddress.getText().toString();
String eAddConf = ConfirmEmail.getText().toString();
String pass = Password.getText().toString();
String passConf = ConfirmPassword.getText().toString();
String fName = FirstName.getText().toString();
String lName = LastName.getText().toString();
Boolean emailSame;
Boolean passSame;
Boolean emailEmpty;
Boolean passEmpty;
Boolean fNameEmpty;
Boolean lNameEmpty;
if(eAdd.equals(eAddConf)){
emailSame = true;
}else{
emailSame = false;
}
if(pass.equals(passConf)){
passSame = true;
}else{
passSame = false;
}
if(eAdd.equals("")){
emailEmpty = true;
}else{
emailEmpty = false;
}
if(pass.equals("")){
passEmpty = true;
}else{
passEmpty = false;
}
if(fName.equals("")){
fNameEmpty = true;
}else{
fNameEmpty = false;
}
if(lName.equals("")){
lNameEmpty = true;
}else{
lNameEmpty = false;
}
Boolean noErrors;
String ErrorCode = null;
if(emailEmpty==true){
noErrors=false;
ErrorCode = "Email is Empty";
}else if(fNameEmpty==true){
noErrors=false;
ErrorCode = "First name is Empty";
}else if(lNameEmpty==true){
noErrors=false;
ErrorCode = "Last Name is Empty";
}else if(passEmpty==true){
noErrors=false;
ErrorCode = "Password is Empty";
}else if(emailSame==true){
noErrors=false;
ErrorCode = "Emails Don't Match";
}else if(passSame==true){
noErrors=false;
ErrorCode = "Passwords Don't Match";
}else{
noErrors=true;
}
if (noErrors==false){
ErrorBox.setText(ErrorCode);
}else{
String signUpStatus = signUpHttp(eAdd, pass, fName, lName);
if (signUpStatus.equals("Error")){
ErrorBox.setText("Server Down, Please Try Again Later");
}else if (signUpStatus.equals("False")){
ErrorBox.setText("That Email has already been used");
}else if (signUpStatus.equals("True")){
MainActUN.setText(eAdd);
MainActPW.setText(pass);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
}
I did have the repetitive if statements in their own function, but I did this to see if it would fix my problem but it didn't, any help is greatly appreciated.
EDIT----------------------------------
Sorry about not being specific, if all the text boxes are filled, I get that the emails don't match, I have removed the email test and the same things happen saying the passwords don't match, however That the rest with .equals("") are fine.
Let me see if my pasta code reading skills are accurate. Look at what you're doing here:
if(pass.equals(passConf)){
passSame = true;
}else{
passSame = false;
}
In plain English: "If the password and password confirmation match, passSame is true"
Now down here:
}else if(passSame==true){
noErrors=false;
ErrorCode = "Passwords Don't Match";
Don't you mean to set noErrors to true?
Even though the password and password confirmation passed your test (they are indeed the same), you make the passing condition into a failing test. You're doing the same thing for your e-mail and e-mail confirmation.
String testing works, but your code marks a passing test as a fail. There's nothing wrong with the String comparison, but there's something wrong with your logic.
Just for the future, there's a great (ultimately pointless) debate among programmers about whether the opening curly brace should be on its own line or on the end of the preceding line. There is no debate, however, about where the closing curly brace goes.
}else{
is just fugly code. I have to agree that you need to strip out all of this redundant stuff. I know you did it for testing, but you're subjecting our eyes to some seriously stylistically atrocious code, which is not a nice thing to do given that you're asking us to look at it for free. Use a little more whitespace -- your code will be infinitely easier to read.
Write compact code (or as compact as Java will allow). Matching, testing, etc. can all be done in a couple of lines of code each. Java is a wordy enough language as it is.
I have a login form which if is success to login. I want to get a name of the logged, here see my code:
try {
if(jTextField1.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Pleass Input Username");
}
else if(jPasswordField1.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Please Input Password");
}
else
{
rs = con.executeQuery("SELECT * FROM MsEmployee WHERE EmployeeID='"+jTextField1.getText()+"' And Password='"+jPasswordField1.getText()+"'");
if (rs.next())
{
help.IDemployee = jTextField1.getText();
JOptionPane.showMessageDialog(null, "Login Success! welcome "+ help.IDemployee);
MainMenu mm = new MainMenu(true);
mm.setVisible(true);
this.dispose();
}else
{
JOptionPane.showMessageDialog(null, "Username not found!!");
}
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,ex.getMessage());
}
So I want to display the EmployeeName from MSEmployee which it got from EmployeeID.
I think something like this:
String qry;
qry = "Select EmployeeName From MsEmplyee WHERE EmployeeID = '" + jtextField1.gettext() + "'" ;
But when I compile, its just print the text above, not get the value. Can anyone help please?
As suggested in a comment, please check which name, MsEmplyee/MsEmployee, is correct.
This is not related to your problem but I think there can be one (possible) improvement in your code.
Instead of using
if(jTextField1.getText().equals(""))
It is better to use trim() method before using equals() method. So if user enters a space in jTextField1, your check will be bypassed in this case. So better to use trim() method to remove all first and last space characters from the string.
if(jTextField1.getText().trim().equals(""))
Same can be done for password field.
You did not read the result set value.
// help.IDemployee = jTextField1.getText();
help.IDemployee = rs.getString(1);
The column index is from 1 for the first column. Not from 0
You Can Try This !
String EmployeeName = rs.getString("Column Label In Database (Like EmployeeName)");
System.out.println(EmployeeName);
I have a few buttons on my panel and everytime I click on it an input dialog box appears. It has an inbuilt cancel button. Now, when i click on the cancel button in the beginning of the code without entering the quantity in the dialog box, it says, "This is an invalid" number. This line has to only appear if the user enters alphabets or symbols, and not on pressing cancel. Can we solve this?
First you need a way to decide if a String represents a number; the method below uses Double.valueOf() to decide.
private Double valueOf(String s) {
try {
return Double.valueOf(s);
} catch (NumberFormatException e) {
return null;
}
}
Here's an example of how you might use the method:
private void display() {
String input = JOptionPane.showInputDialog(
null, "Enter a number?", "Number", JOptionPane.QUESTION_MESSAGE);
Double value = valueOf(input);
JOptionPane.showMessageDialog(null, "The value " + input
+ " is " + (value != null ? "valid" : "invalid") + ".");
}
See also How to Make Dialogs.
Try doing,
String Input = JOptionPane.showInputDialog(null,"Enter the number?",
"Number", JOptionPane.QUESTION_MESSAGE);
if (Input.equals(""))
{
JOptionPane.showMessageDialog(null,"This is an invalid number");
}
The following link explains it even better: Simple Data Validation.
String Input = JOptionPane.showInputDialog(null,"Enter the number?",
"Number", JOptionPane.QUESTION_MESSAGE);
if
(Input.matches(("((-|\+)?[0-9]+(\.[0-9]+)?)+"))) {
JOptionPane.showMessageDialog(null,"valid number");
}
else{
JOptionPane.showMessageDialog(null,"This is an invalid number");
}