Else statement not recognised java - java

private void EnterbuttonActionPerformed(java.awt.event.ActionEvent evt) {
if (Usernamefield.getText().equalsIgnoreCase("User"));
if (Passwordfield.getText().equalsIgnoreCase("420"));
{
JOptionPane.showMessageDialog(null, "Welcome, User!");
}
else
{
JOptionPane.showMessageDialog(null, "Wrong Username/Password!");
}
It says that an else statement cannot work without an if, there are clearly 2 if statements however. I would like to create a simple log-in GUI in Java.

change
if (Usernamefield.getText().equalsIgnoreCase("User"));
if (Passwordfield.getText().equalsIgnoreCase("420"));
to
if (Usernamefield.getText().equalsIgnoreCase("User") &&
Passwordfield.getText().equalsIgnoreCase("420"))
{
JOptionPane.showMessageDialog(null, "Welcome, User!");
}
else
{
JOptionPane.showMessageDialog(null, "Wrong Username/Password!");
}
You want both conditions to be true in order to accept the user.
And don't put a ; at the end of an if condition, since that makes it an empty if statement that does nothing (that's the reason your else had no matching if).

Try the below code.
private void EnterbuttonActionPerformed(java.awt.event.ActionEvent evt) {
if (Usernamefield.getText().equalsIgnoreCase("User") && Passwordfield.getText().equalsIgnoreCase("420"))
{
JOptionPane.showMessageDialog(null, "Welcome, User!");
}
else
{
JOptionPane.showMessageDialog(null, "Wrong Username/Password!");
}

Related

While loop inside multiple if condition in android studio

I'm using while loop and inside am using two if statements.
while(cr.moveToNext()){
if(cr.getCount() > 0){
if((cr.getString(5).equals(username)) && cr.getString(6).equals(password)
&& cr.getString(14).equals("success")) {
String un = cr.getString(2);
String uc = cr.getString(1);
String rc = cr.getString(4);
......................
Toast.makeText(LoginActivity.this, "Successfully Logged In", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), Dashboard.class);
startActivity(intent);
} else{
Toast.makeText(LoginActivity.this, "Invalid Login", Toast.LENGTH_SHORT).show();
}
}
}
In this scenario, if I passed wrong value "Invalid Login" is executing many times [as it is inside while loop] and If I pass correct values both successfully login and Invalid login message is showing. How to make if condition to be properly work in this type of scenario...
Assuming you want to check that everything is in order before starting the activities you can do the loop twice, like below.
I also used do while, so as not to skip the first result.
private void handleCursor(Cursor cr){
boolean everythingGood = true;
do{
if (cr.getCount() > 14) { // <- if you are using cr.getString(14)
//to get "Success" string, then you should
//check for that too
if (!checkSuccess(cr) )
everythingGood = false; }
}else {
//not enough columns received.. assumed login fail.
//do your failure workflow
everythingGood = false;
}
} while(cr.moveToNext() && everythingGood);
if(everythingGood){
//second loop (no need to check any more, just spawn the activities)
cr.moveToFirst();
do{
createActivities(cr);
}while(cr.moveToNext();
}else {
handleFailure();
}
}
I moved your check condition out to another function to make it easier to see the while loop
private boolean checkSuccess(Cursor cr){
return cr.getString(5).equals(username)) && cr.getString(6).equals(password)
&& cr.getString(14).equals("success");
}
you can use break; or you can use a boolean flag variable , at first keep it true, then enter the conditions if it is true and once entered make the flag variable false in side that condition.
Boolean isValid;
isValid = true;
while(cr.moveToNext())
{
if (cr.getCount() > 0)
{
if ((cr.getString(5).equals(username))
&& cr.getString(6).equals(password) && cr.getString(14).equals("success"))
{
if (isValid)
{
isValid=false;
String un = cr.getString(2);
}
}
else { .......... }
}
}

How do I keep asking the user for input if the input wasn't a number?

I'm making a cash register with an "other" option, which allows the user to add an amount through user input. I have done this with a JOptionPane, the "other" button code is the following:
private void btnOverigActionPerformed(java.awt.event.ActionEvent evt) {
String prijs = JOptionPane.showInputDialog(this, "Vul een bedrag in");
try {
double overigePrijs = Double.parseDouble(prijs);
if (overigePrijs > 0){
aantalProducten[6]++;
totaalPerProduct[6] += overigePrijs;
}
huidigePrijsDisplay();
}
catch (Exception letter){
while (true){
prijs = JOptionPane.showInputDialog(this, "Vul a.u.b. alleen cijfers in.");
}
}
This while-loop will not close the JOptionPane, even when inputting numbers, how do I loop this correctly?
Edit after almost finishing my SE studies:
I was missing an if-statement in my while-loop. What I was trying to do was checking if the input of prijs were only numbers and if not, keep showing the dialog. I never got around to fixing this because it's an old project but I should have stated the motivation behind the code more clearly!
The question is not clear itself. What I assume that if the try part does not run as you wish, the JOptionPane should reopen and user should be prompted to do it again. If it is so, you can do the following:
Create a method:
private void doTheTask(){
String prijs = JOptionPane.showInputDialog(this, "Vul een bedrag in");
try{
//your task here.
}
catch (Exception letter){
//Call the method again.
doTheTask();
}
}
And call the method inside your action:
private void btnOverigActionPerformed(java.awt.event.ActionEvent evt){
doTheTask();
}
I suggest you a different approach in your code:
String prijs = "";
double overigePrijs = -1;
while (true) {
prijs = JOptionPane.showInputDialog(null, "Vul een bedrag in");
if (prijs != null) { // if user cancel the return will be null
try {
overigePrijs = Double.parseDouble(prijs);
break; // Exits the loop because you have a valid number
} catch (NumberFormatException ex) {
// Do nothing
}
} else {
// You can cancel here
}
// You can send a message to the user here about the invalid input
}
if (overigePrijs > 0) {
aantalProducten[6]++;
totaalPerProduct[6] += overigePrijs;
}
huidigePrijsDisplay();
This code will loop until the user enters a valid number and then you can use after the while loop. Some improvement may be necessary like a cancel logic or change the message on the second time but the main idea is this.

If else branch never used

I'm using if else and writing down some codes suddenly happens the else said the branch is never used... but it should work.
The statement looks like this
JOptionPane.showConfirmDialog(null,full_name+"\n"+number_age+"\n"+gender+"\n"+address+
"\n"+birthday+"\n"+cell_no,"CHECK INFORMATION!",JOptionPane.YES_NO_OPTION);
if(true){
JOptionPane.showMessageDialog(null,"Thank you for Entering");
}else{
JOptionPane.showMessageDialog(null,"Please Retry");
}
Check JOptionPane.showConfirmDialog response and compare with JOptionPane.YES_NO_OPTION:
int answer = JOptionPane.showConfirmDialog(null,full_name+"\n"+number_age+"\n"+gender+"\n"+address+
"\n"+birthday+"\n"+cell_no,"CHECK INFORMATION!",JOptionPane.YES_NO_OPTION);
if (JOptionPane.YES_OPTION == answer)) {
JOptionPane.showMessageDialog(null,"Thank you for Entering");
} else {
JOptionPane.showMessageDialog(null,"Please Retry");
}

java login & signup form issue

I'm learning Java in school right now and I've tried to make a little login/signup form. So everyone who wants to play my small game has to signup/login first to get their stats loaded. I've seen some basic login forms when I searched some solutions on google, but always with lines like this:
if ( username_tf.getText() == "admin" && password_tf.getText() == "123" ) { ...
But I want people to be able to make their own username & password. That's what I was trying to do:
int i;
String username[] = new String[500];
String password[] = new String[500];
// REGISTER BUTTON - no if else yet, just the basics I need to test login button
public void jButton2_ActionPerformed(ActionEvent evt) {
username[i] = jTextField1.getText();
password[i] = jPasswordField1.getText();
i++;
} // end of jButton2_ActionPerformed
// LOGIN BUTTON
public void jButton1_ActionPerformed(ActionEvent evt) {
for ( int j = 0; j < i; j++ ) {
username[j] = jTextField1.getText(); // same error without this line
password[j] = jPasswordField1.getText(); // "
if ( username[j].equals(username[i]) && password[j].equals(password[i]) ) {
JOptionPane.showMessageDialog(this, username[j] + ", welcome back.", "Successfully logged in.", JOptionPane.INFORMATION_MESSAGE);
} else {
if ( !username[j].equals(username[i]) ) {
JOptionPane.showMessageDialog(this, "Wrong username.", "Error.", JOptionPane.ERROR_MESSAGE);
} else if ( !password[j].equals(password[i]) ) {
JOptionPane.showMessageDialog(this, "Wrong password.", "Error.", JOptionPane.ERROR_MESSAGE);
} else if ( !username[j].equals(username[i]) && !password[j].equals(password[i]) ) {
JOptionPane.showMessageDialog(this, "Wrong username & password.", "Mega Error.", JOptionPane.ERROR_MESSAGE);
}
} // end of if-else
} // end of for
} // end of jButton1_ActionPerformed
I've tried the same code with == operators, but I'm still getting the same error. ^^
I'm getting the Username is wrong option pane always, can somebody help me there? :)
Would appreciate any kind of help and therefore I'm new to Java I'd also appreciate if you could explain why you're using it when you use some difficult code. :D

How to return properly in if else and avoid "void" for errors about return

I am having a hard time how to return into specific variable or how to return without getting any error base on my program.
class Facebook {
public static void main(String[]args){
String user = JOptionPane.showInputDialog(null,"Enter Username: ");
String pass = JOptionPane.showInputDialog(null,"Enter Password: ");
if(user.equals("jas")&&(pass.equals("bsit"))){
JOptionPane.showMessageDialog(null,"Welcome "+ user);
Selection Class = new Selection();
Selection.Selection1();
}
else if (!user.equals("jas")||(!pass.equals("bsit"))) {
JOptionPane.showMessageDialog(null,
"Invalid Username or Password",
"Wrong Authentication",
JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
}
class Selection{
public Selection1(){
try{
String select = JOptionPane.showInputDialog("[1]Home\n[2]Profile\n[3]Logout");
int numbers = Integer.parseInt(select);
if (numbers == 1){
JOptionPane.showMessageDialog(null,"Mang Tani: Lumakas ang hanging amihan halos nilipad ang mga bubong ng mga bahay\n\nJessica Soho: Isang sikat na pagkain sa davao inubos ng kabataan \n\n Boying Remulla: Walang pasok dahil sa malakas na ulan\n#WalangPasok.");
return select;
}
else if (numbers == 2){
JOptionPane.showMessageDialog(null,"Name: Ralph Jasper \n\n Age: 17 \n\n Address: Tierra Nevada, General Trias, Cavite");
}
else if (numbers == 3){
}
}
catch (NumberFormatException nfe){
JOptionPane.showMessageDialog(null,"Please input only numbers","Invalid Input",JOptionPane.ERROR_MESSAGE);
}
}
}
1) you want a method with a return value of a string
Replace
public Selection1(){
with
public String select()
2) all "paths" of a non-void method must result in a return statement. This does not mean a return statement needs to be inside any if else's, but you do need to return something within the method.
Suggestion: declare a String result = ""; outside of the try catch, return it after, outside of the catch, and assign it to your JOptionPane value in between like result = JOptionPane...
3) I'm assuming you actually want that value that's returned?
Selection selector = new Selection();
String selected = selector.select();
// TODO use that value
Notice: Java naming conventions -- methods are lowerCase, classes are UpperCase.

Categories