I keep getting an "else without if" error - java

I'm trying to write some code that makes the user input a valid username and they get three tries to do it. Every time I compile it I get an else without if error wherever I have a else if statement.
Scanner in = new Scanner(System.in);
String validName = "thomsondw";
System.out.print("Please enter a valid username: ");
String input1 = in.next();
if (input1.equals(validName))
{
System.out.println("Ok you made it through username check");
}
else
{
String input2 = in.next();
}
else if (input2.equals(validName))
{
System.out.println("Ok you made it through username check");
}
else
{
String input3 = in.next();
}
else if (input3.equals(validName))
{
System.out.println("Ok you made it through username check");
}
else
{
return;
}

You are misunderstanding the use of if-else
if(condition){
//condition is true here
}else{
//otherwise
}else if{
// error cause it could never be reach this condition
}
Read more The if-then and if-then-else Statements
You can have
if(condition){
}else if (anotherCondition){
}else{
//otherwise means 'condition' is false and 'anotherCondition' is false too
}

If you have an if followed by an else, that ends the block. You can have if followed by multiple else if statements, but only one else -- and the else must be last.

You need to either: change all your "else" except the last to "else if", or put plain "if" before the following "else if" statements:
(1)
else if (input2.equals(validName))
{
System.out.println("Ok you made it through username check");
}
(2)
else if (input3.equals(validName))
{
System.out.println("Ok you made it through username check");
}

Your code is not very maintainable. What would you do, if the user got 5 tries? Add some additional if blocks? And what if the user has 10 tries? :-) You see what I mean.
Try the following instead:
Scanner in = new Scanner(System.in);
int tries = 0;
int maxTries = 3;
String validName = "thomsondw";
while (tries < maxTries) {
tries++;
System.out.print("Please enter a valid username: ");
String input = in.next();
if (input.equals(validName)) {
System.out.println("Ok you made it through username check");
break; //leaves the while block
}
}

Related

JAVA While loop - last else if statement not working

package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
System.out.println("What is the password?");
Scanner new2 = new Scanner(System.in);
int input = 0;
while(input <= 5 )
{
String password = new2.nextLine();
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
else if("bluesky123".equals(password)) {
System.out.println("You got it right!");
break;
}
else if(input == 5) {
System.out.println("maximum number of attempts reached");
break;
}
}
}
}
basically, once I hit the 5 loops, it just says "incorrect password" and breaks. not the "maximum attempts" message.
Allow me to annotate:
This if statement will always be evaluated:
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
This if statement will only be evaluated if the password is "bluesky123". In this case, it will always evaluate to true.
else if("bluesky123".equals(password)) {
System.out.println("You got it right!");
break;
}
There is no case when this if statement will ever be evaluated. Once if-else finds a statement that is true, it will skip all others in that section.
else if(input == 5) {
System.out.println("maximum number of attempts reached");
break;
}
In your case, you should consider a nested if (i.e. an if inside another if).
while(input <= 5 )
{
String password = new2.nextLine();
if(!password.equals("bluesky123")){
System.out.println("Incorrect password");
input++;
}
else {
System.out.println("You got it right!");
break;
}
if((input == 5) && (!password.equals("bluesky123"))) {
System.out.println("maximum number of attempts reached");
break;
}
}
Your logic has some flaws. You have to pay attention to how JAVA processes if / else if
https://www.tutorialspoint.com/java/if_else_statement_in_java.htm
I tested your code it is working! The only thing that you need to do is to move the follow line to inside the while loop
System.out.println("What is the password?");
Doing this it will print "Incorrect password" and then it will print again
"What is the password?"
Because in the way that it is working now seems that the software is not waiting the password to be retyped when in fact it is.

Password checker java program

I am trying to create a program that will check the password of the user. I want the program to end once the user gets it correct but if not I want it to ask only 4 times.
Problem: even if you do get the password correctly the program keeps on asking guess the password. And if you get it wrong it will ask incorrectly. How can I fix this?
import java.util.Scanner;
public class HowToAdd {
public static void main (String [] args){
Scanner input = new Scanner (System.in);
int trys = 0;
String password=null;
do{
System.out.println("Guess the password");
password = input.next();
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
}else{
System.out.println("Try again");
input.next();
trys++;
}
}while(trys<2);
System.out.println("Try again later!");
input.close();
}
}
You just need to add a break:
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
break;
}
Not only did I add a break to fix the problem of not leaving the loop when correct password is entered but I added a couple of other things to help you out see below:
public static void main (String [] args){
Scanner input = new Scanner (System.in);
int trys = 0;
String password=null;
System.out.println("Guess the password:");
while(trys<2)
{
password = input.next();
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
break;
}else{
trys++;
if(trys != 2)
{
System.out.println("Try again:");
}
}
}
if(trys == 2)
{
System.out.println("Try again later!");
}
input.close();
}
Try this it will break out of the loop if it is correct using the break; statement. Also it will only display guess a password the first try then try again after that. Also it won't say try again later if they guessed right because it checks if they guessed wrong twice.
You can fix it with a break keyword, like so :
if(password.equalsIgnoreCase("Password")){
System.out.println("Great job");
break;
}
The break is explained here :
Branching Statements
What you need to implement can be done without using break statements.
Try to look at the flow of my codes.
Scanner scn = new Scanner(System.in);
int tries=0;
String pw = "";
System.out.println("Guess the password");
pw = scn.nextLine();
while(!pw.equalsIgnoreCase("Password") && tries < 3){
tries++;
System.out.println("Try again");
pw = scn.nextLine();
}
if(tries >= 3)
System.out.println("Try again later!");
else
System.out.println("Great job!");
TEST RUN 1:
Guess the password
1st try
Try again
2nd try
Try again
3rd try
Try again
last try
Try again later!
TEST RUN 2:
Guess the password
password
Great job!
Here is another variant of code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int trys = 0;
String password = null;
// create variable for a number of tries
int numberOfCheks = 4;
do {
System.out.println("Guess the password");
password = input.nextLine();
if (password.equalsIgnoreCase("Password")) {
System.out.println("Great job");
break;
} else if (++trys == numberOfCheks) {
//Break if you've used all your tries
System.out.println("Try again later!");
break;
} else {
System.out.println("Try again");
// input.next(); - Useless. You don't handle it. Removed
}
//There is already tries number check. So 'true' can be used as the condition.
} while (true);
input.close();
}

Else without if?

I was working on my assignment for my Java 1 class and I am getting an error that does not seem like it should be one. Can I get some help? It is saying that I have an else w/out if.
here is the if block
char placement = scan.next().toUpperCase().charAt(0);
if(placement == 'F')
{
System.out.print("Please Enter The Show To Be Added At The Beginning Of The List: ");
String show = scan.next();
TVShows.add(0, show);
}
else if(placement == 'R');
{
System.out.print("Please Enter The Show To Be Added At The End Of The List");
String show = scan.next();
TVShows.add(show);
}
else
{
System.out.println("Invalid Choice Please Try Again");
}
Remove the semi colon
else if (placement == 'R');
^
which is terminating the else if block statement

How make this program terminate after

Below is a simple program that I wrote that will ask for a password. If I enter the incorrect password I am prompted with "Password incorrect would you like to try again?", and if I say no or anything else that doesn't begin with a 'y', it will terminate the program. The problem is, if I enter the correct password which is "Noah" it says "Password correct" and it loops back to "Enter password" again. How can I make this program terminate after I enter the correct password? Thank you.
import java.util.Scanner;
public class methods
{
public static void main (String [] args)
{
Scanner sc = new Scanner(System.in);
String response = "yes";
System.out.println("Enter password:");
while(response.charAt(0)=='y')
{
String input = sc.nextLine();
if(input.equalsIgnoreCase("Noah")==true)
{
System.out.println("Password correct");
}
else if(input.equalsIgnoreCase("Noah")==false)
{
System.out.println("Password incorrect, would you like to try again?");
response = sc.nextLine();
}
}
}
}
while(response.charAt(0)=='y')
{ System.out.println("Enter password")
String input = sc.nextLine();
if(input.equalsIgnoreCase("Noah")==true)
{
System.out.println("Password correct");
break;
}
else if(input.equalsIgnoreCase("Noah")==false)
{
System.out.println("Password incorrect, would you like to try again?");
response = sc.nextLine();
}
}
use break; then you can terminate.
if("Noah".equalsIgnoreCase(input)){
System.out.println("Password correct");
break;
}
There are a few ways. In increasing severity:
1) Use a break statement. That will take program control flow to just after the end of the while loop.
2) Use a return statement. That will exit the function and, in your specific case, that will end the program.
3) Insert System.exit(n) where n is a number, probably non-zero, to indicate a return status. This terminates the Java Virtual Machine, and returns the value n to the operating system.
In your case I'd be inclined to go with (1) or (2).
if(input.equalsIgnoreCase("Noah")==true)
{
System.out.println("Password correct");
break;
}
or you can add response ="no";
if(input.equalsIgnoreCase("Noah")==true)
{
System.out.println("Password correct");
response ="no";
}
" no" or anything that dose not start with the 'y' char .
After doing a couple of changes, I guess this is what you are looking for :
import java.util.Scanner;
public class Methods{
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
String response = "yes";
while(response.charAt(0)=='y'){
System.out.println("Enter password:");
String input = sc.nextLine();
if(input.equalsIgnoreCase("Noah")==true){
System.out.println("Password correct");
break;
}
else if(input.equalsIgnoreCase("Noah")==false){
System.out.println("Password incorrect, would you like to try again?");
response = sc.nextLine();
}
}
}
}

Java Basic Login Feature

I'm trying to implement a login feature in this program. I finally figured it out how to do a basic one, but sadly I do not know how to end it, like for example if the user had finally reached the limit of 3 it should end, but mine still continues and I don't know where and what code I should put in order for it to end than continuing to the main program.
import java.io.*;
public class Password{
public static void main(String args[]) throws IOException{
String name, un, pw;
String Username = "passwordtest";
String Password = "test123";
int stud;
double math, science, english, filipino, social, ave, sum, fingrade;
BufferedReader inpt = new BufferedReader (new InputStreamReader(System.in));
for(int trial=1; trial<=3; trial++){
System.out.print("Username: ");
un = inpt.readLine();
System.out.print("Password: ");
pw = inpt.readLine();
System.out.println("");
if (un.equals(Username) && pw.equals(Password)){
System.out.println("You have successfully logged in!");
trial=trial+2;
continue;
}else{
System.out.println("Sorry, Incorrect Username/Password");
System.out.println("Please Try Again");
System.out.println("");
}
}
System.out.println("");
System.out.println("Welcome to ITMinions' Grading System!");
System.out.println("How many students' grades would you like to record?");
System.out.print("Answer: ");
stud=Integer.parseInt(inpt.readLine());
System.out.println("");
for (int ctr=1; ctr<=stud; ctr++){
System.out.print("Name of the student: ");
name = inpt.readLine();
System.out.println("");
System.out.println("Input the following grades");
System.out.print("Math: ");
math = Double.parseDouble(inpt.readLine());
if(math<65 || math>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
System.out.print("Science: ");
science = Double.parseDouble(inpt.readLine());
if(science<65 || science>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
System.out.print("English: ");
english = Double.parseDouble(inpt.readLine());
if(english<65 || english>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
System.out.print("Filipino: ");
filipino = Double.parseDouble(inpt.readLine());
if(filipino<65 || filipino>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
System.out.print("History: ");
social = Double.parseDouble(inpt.readLine());
if(social<65 || social>100){
System.out.println("");
System.out.println("Wrong input, try again.");
System.out.println("");
ctr=ctr-1;
continue;
}
sum=math+science+english+filipino+social;
ave=sum/5;
System.out.println("");
System.out.println("The average of " + name + " is: " + ave);
System.out.println("");
}
}
}
Please help! And yes this is related to school work :)
Thanks!
I would rewrite the part of the loop that handles succesfull login as follows:
if (un.equals(Username) && pw.equals(Password)){
System.out.println("You have successfully logged in!");
break;
}
Notice using the break keyword to break out of the loop.
You can use System.exit(0); to exit when the user has used all login attempts.
You must use another variable for example: boolean isLoggedIn, and set that if successfully logged in, and then break instead of continue as below:
if (un.equals(Username) && pw.equals(Password)){
System.out.println("You have successfully logged in!");
isLoggedIn = true;
break;
}else{
System.out.println("Sorry, Incorrect Username/Password");
System.out.println("Please Try Again");
System.out.println("");
}
Then outside the for loop, check if(isLoggedIn) and do actions accordingly.
Modify your fi statement
if (un.equals(Username) && pw.equals(Password)){
System.out.println("You have successfully logged in!");
break;;
}else{
System.out.println("Sorry, Incorrect Username/Password");
System.out.println("Please Try Again");
System.out.println("");
}
}
if(trail==4)
{
//Write your locking logic here
}
its not good practice to hard code things in your code. Try to use property file for simplicity or if you have time use jdbc
To avoid Null pointer exception use
Username.equals(un)
Also, make sure you follow proper Java coding standards like camel-case for variable naming, and all upper case for constants. Since username and password are hardcoded, they are infact constants. So, change
String Username = "passwordtest";
String Password = "test123";
to
final String USERNAME = "passwordtest";
final String PASSWORD = "test123";
It would also be better if you could load these constants from a properties file, because when passwords change, you need not modify your code, just edit properties file.
To clarify the previous answers:
booelan isLoggedIn = false;
for ( int trials = 3; trials > 0; trials-- )
{
<ask uname, password> // Java convention: don't capitalise variable names
if ( isLoggedIn = <uname/password are OK> {
System.out.println ( "Success" );
break;
}
System.out.printf ( "Bad uname/pass, %d attempts remaining\n", trials );
}
if ( !isLoggedIn ) {
System.out.println ( "User couldn't give valid credentials, quitting after three attempts, due to security reasons" );
Thread.sleep ( 3000 ) // try to fight brute-force attackers
System.exit ( 1 ); // Not zero, it's not a regular end
}
// Go ahead with your application

Categories