Home Guess the Passcode program not working?
Reply: 0

Guess the Passcode program not working?

user8887 Published in September 20, 2018, 10:23 pm

This program is meant to guess a randomly generated 4-digit passcode and then output the how many guesses it took to get the correct code, but nothing happens...

My approach was to use a for loop to try every single possible combination of four digits of the numbers 0 - 9. This is inside an infinite loop that will only break when the passcode is guessed.

I don't know what's wrong with my program, nothing is printed but the program doesn't loop infinitely.

function start() {
    var secretPasscode = generateRandomPasscode();

    var i = 0;

        var guess = "";

        for(var firstDigit = 0; firstDigit <= 9; firstDigit++){
            guess += firstDigit;
            for(var secondDigit = 0; secondDigit <= 9; secondDigit++){
                guess += secondDigit;
                for(var thirdDigit = 0; thirdDigit <= 9; thirdDigit++){
                    guess += thirdDigit;
                    for(var fourthDigit = 0; fourthDigit <= 9; fourthDigit++){
                        guess += fourthDigit;
        return guess;

        if(guess == secretPasscode){
        println("It took " + i + " guesses to get the correct");


This is the code that generates the random passcode:

function generateRandomPasscode() {
    var randomPasscode = "";

    for(var i = 0; i < 4; i++) {
        var randomDigit = Randomizer.nextInt(0, 9);
        randomPasscode += randomDigit;

    return randomPasscode;
share|improve this question
  • 1
    See the line right after the loop that says return guess? That will be the end of execution of the start function. Try removing it. – danh Feb 14 at 2:57
  • Also note that the println will execute on every iteration except the last one. Put it inside the guess is correct condition to make it run only when you're done. Maybe also, add some safety to the loop to stop after a high number of iterations whether or not you've found the solution. – danh Feb 14 at 2:59
  • Thank you for the suggestion. You were right about the println, however, removing the return statement makes the code loop infinitely... – High School Student Feb 14 at 3:09
  • Ah, that means your loop never finds a solution. Don't fix that by returning right away, fix it by finding the solution. – danh Feb 14 at 3:10

1 Answer 1

active oldest votes
up vote 0 down vote
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.299384 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO