Jump to content

Java loop problem

VUKI656

*NOTE: i'm just starting out, so if i made some really stupid mistakes, don't bash me with them.

 

 

I am creating a program where you have to insert the right password else it gives you one less try and you can try again. If you fail 3 times it locks. I already made something similar but i had the problem where it also didn't recognize the correct password. After i deleted it and quit, tried again and now i wrote this from scratch and a lot more things don't work as they should. 

 

PROBLEMS

1. How to make the while loop take the input(password in this case) and compare it to the correctPass. I just wrote 1 != 2 so it loops until it executes "else" and then breaks out of the loop, but it doesn't work. 

2. Also the "attempt" subtraction part also doesn't work. 

3. If i enter the correct password it still gives me the "Try again"

 

Heres the code

 

importjava.util.Scanner; public class Application {public static void main(String[] args) { while(1 != 2) { String correctPass = "Java"; System.out.println("Enter the password"); Scanner input = new Scanner(System.in);String line = input.nextLine(); if(line == correctPass) {System.out.println("Wellcome back sir!");break;}else {intnum = 3;System.out.println("Wrong password, please try again! "  + num + " attempts left!");num = num - 1;if(num == 0) {System.out.println("System Locked!");break;}}  }}}

post-124566-0-68681000-1431558132.png

Edited by colonel_mortis
Code tags
Link to comment
Share on other sites

Link to post
Share on other sites

Well.. for problem #2, your reseting the num to 3 every time it loops.

 

Put int num = 3; outside the while loop.

Intel i5-6600k (Cooled by a 212 evo) - Asus Z170-A - Asus Dual OC GTX 1060 - NZXT S340 - WD 1TB (Getting SSD this month, hopefully) - 8GB DDR4-2400

LG G4 - Asus Zenwatch 2

 

Link to comment
Share on other sites

Link to post
Share on other sites

Well.. for problem #2, your reseting the num to 3 every time it loops.

 

Put int num = 3; outside the while loop.

I did but still nothing, or did i placed it wrong? 

post-124566-0-69488500-1431558740_thumb.

Link to comment
Share on other sites

Link to post
Share on other sites

Isnt break; going to stop it if it executes? How exactly should i type the .equals ?

Link to comment
Share on other sites

Link to post
Share on other sites

-snip-

Try this:

 

import java.util.Scanner; public class Application {public static void main(String[] args) { while(1 != 2) { String correctPass = "Java"; System.out.println("Enter the password");Scanner input = new Scanner(System.in);String line = input.nextLine(); if(line == correctPass) {      System.out.println("Wellcome back sir!");}      else {            intnum = 3;            System.out.println("Wrong password, please try again! "  + num + " attempts left!");            num = num - 1;}      if(num == 0) #            {            System.out.println("System Locked!");            }             break;else {}}}  }}}

 

Edited by colonel_mortis
Code tags

Main Rig - Case: Corsair 200R   Motherboard: Gigabyte GA-Z270-GAMING-K3  CPU: Intel i5 7600 RAM: Corsair H55 RAM: Corsair Vengeance 16GB 3000MHz SSD: Crucial MX500 1 TB 

HDD: 2TB WD Green  GPU: Gigabyte GTX 1660 Ti 6GB Windforce  PSU: Corsair CX 600W  

HTPC - Case: CiT MTX-007B   Motherboard: Biostar H61MGV3, CPU: Intel i5 2400  RAM: Patriot 4GB 1333MHz SSD: 240GB Toshiba SSD PSU: 180W CIT (Came with case)

Corsair 200R Front Bezel Mod

Link to comment
Share on other sites

Link to post
Share on other sites

 

Eh, it will but the 1 != 2 just doesn't seem like the logical way to go about the loop.

 

also, .equals(string), so in your code it will be

if (line.equals(correctPassword))        // do stuff

Thank you so much. That solved to problem when entering the correct password. Now all i need is to figure out the subtraction of the attempts. 

Also for the 1 != 2, what should i put in  instead of that so that it loops until I enter the correct password ?

 

Try this:

 

importjava.util.Scanner;

 

public class Application {

public static void main(String[] args) {

 

while(1 != 2) {

 

String correctPass = "Java";

 

System.out.println("Enter the password");

Scanner input = new Scanner(System.in);

String line = input.nextLine();

 

if(line == correctPass) {

      System.out.println("Wellcome back sir!");

}

      else {

            intnum = 3;

            System.out.println("Wrong password, please try again! "  + num + " attempts left!");

            num = num - 1;

}

      if(num == 0) #

            {

            System.out.println("System Locked!");

            }

             break;

else {

}

}

}

 

 

}

}

}

 

It doesent quite work, it has a lot of errors. What exactly did you do there?

Link to comment
Share on other sites

Link to post
Share on other sites

Thank you so much. That solved to problem when entering the correct password. Now all i need is to figure out the subtraction of the attempts. 

Also for the 1 != 2, what should i put in  instead of that so that it loops until I enter the correct password ?

 

Try the following:

String correctPass = "Java";String line = "";int num = 3;while(!line.equals(correctPass)) {// the rest should go here}

This should fix both of the issues. The subtraction wasn't working because you were initializing the variable num inside the while-loop, which resulted in it being re-initialized back to 3. Generally speaking, you should never initialize variables inside a loop, unless you literally need the variable to be re-initialized for every loop (such as when using random numbers).

 

As for loops that run until a certain condition is fulfilled, the most common way to do it is using while(True) with break and continue statements as necessary. The advantage of using while(True) is that it enables multiple break conditions. However, it can also make the aim of the code hard to follow.

I own and use, sorted from newest to oldest: SteelSeries 6Gv2. Microsoft SideWinder X4. Mionix Naos 7000. Zowie EC1 Evo. Microsoft SideWinder X8. Microsoft IntelliMouse Explorer 3.0. Dell U2414H. Samsung P2270H. AKG K273 Pro. Sennheiser HD555. Razer Goliathus Speed Medium. Func 1030 L. Qpad CT Medium.

I used to own: Razer DeathAdder 3G. Razer Krait. IntelliMouse Optical 1.1. SteelSeries QcK.

Link to comment
Share on other sites

Link to post
Share on other sites

Bare with me as I use c# and i only have small experience in java. I am also writing this on a chromebook any way here is how I would do it's probably not the best coding but it should work.

importjava.util.Scanner; public class Application {public static void main(String[] args) {    //Create attemps    int attempts=0;    //set password    string correctpass="Java";        do    {        System.out.println("Enter the password");             //get user input        Scanner input = new Scanner(System.in);        String line = input.nextLine();            //if password is correct        if (line == correctpass)        {            break;        }else        {            System.out.println("Incorrect");            //increments attemps            attempts++;            //pauses for enter type to try again            //not sure if this work i read its the same as Console.readkey in c#            System.in.read();        }    }while(attempts!=3)    if (attempts < 3)    {        System.out.println("Welcome back sir");    }else    {        System.out.println("system is locked");    }        System.in.read();}

                     ¸„»°'´¸„»°'´ Vorticalbox `'°«„¸`'°«„¸
`'°«„¸¸„»°'´¸„»°'´`'°«„¸Scientia Potentia est  ¸„»°'´`'°«„¸`'°«„¸¸„»°'´

Link to comment
Share on other sites

Link to post
Share on other sites

 

*NOTE: i'm just starting out, so if i made some really stupid mistakes, don't bash me with them.

 

 

I am creating a program where you have to insert the right password else it gives you one less try and you can try again. If you fail 3 times it locks. I already made something similar but i had the problem where it also didn't recognize the correct password. After i deleted it and quit, tried again and now i wrote this from scratch and a lot more things don't work as they should. 

 

PROBLEMS

1. How to make the while loop take the input(password in this case) and compare it to the correctPass. I just wrote 1 != 2 so it loops until it executes "else" and then breaks out of the loop, but it doesn't work. 

2. Also the "attempt" subtraction part also doesn't work. 

3. If i enter the correct password it still gives me the "Try again"

 

Heres the code

 

importjava.util.Scanner; public class Application {public static void main(String[] args) { while(1 != 2) { String correctPass = "Java"; System.out.println("Enter the password"); Scanner input = new Scanner(System.in);String line = input.nextLine(); if(line == correctPass) {System.out.println("Wellcome back sir!");break;}else {intnum = 3;System.out.println("Wrong password, please try again! "  + num + " attempts left!");num = num - 1;if(num == 0) {System.out.println("System Locked!");break;}}  }}}

 

import java.util.Scanner;public class App{    public static void main(String[] args){        //Initialize the password        String correctPass="Java";        //Create an instance of the Scanner (outside loop so you don't waste resources creating it everytime)        Scanner input = new Scanner(System.in);        //attempt counter        int attempts = 0;        while(attempts<3){                //prompt for password                System.out.print("Input password: ");                String line = input.nextLine();                //check if pw is equal to correctPass                if(line.equals(correctPass)){                    System.out.println("Welcome back!");                    break;                    }                else{                    //increment the attempts and notify the user he has (3-#attempts) attempts left                    attempts++;                    System.out.println("Wrong password. You have "+(3-attempts) +" left");                    //if he inputs the pw wrong 3 times it exits the app                    if(attempts==3){System.exit(0);}                    }            }            //Your code starts here :)System.out.println("Body of the app starts here!");    }}

Now it should work :D

Asrock 890GX Extreme 3 - AMD Phenom II X4 955 @3.50GHz - Arctic Cooling Freezer XTREME Rev.2 - 4GB Kingston HyperX - AMD Radeon HD7850 - Kingston V300 240GB - Samsung Spinpoint F3 1TB - Chieftec APS-750 - Cooler Master HAF912 PLUS


osu! profile

Link to comment
Share on other sites

Link to post
Share on other sites

Do not use break or continue. These are basically goto in disguise and make code harder to understand and modify. Use as many flag boolean variables as are needed to keep a loop going and wrap conditional code in if statements as needed. In this case, consider how you might use exceptions to direct control flow; also think about a timeout to prevent bots or ddos.

 

Do not store passwords in plain text and definitely do not hard code them into your source file.

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×