Question

I am trying to create a Mastermind game in which colors are numbers [] and one number can never repeat itself in the String. The string should be made of 4 characters. I cannot figure out why my code keeps on printing strings with repeated characters.

import java.util.Random;
import java.util.Scanner; 
public class Question1

{
public static void main(String[] args)
{
    String toGuess="";

    while(!IsValidNumber(toGuess));
    {
        for(int i=0; i<4; i++)
        {
            Random rando= new Random();  
            int rd=rando.nextInt(9);

            toGuess=toGuess+rd;

        }
    }
    System.out.println(toGuess);
}



public static boolean IsValidNumber(String s) // boolean
{
    boolean noRepetition = true;
    for(int i = 0; i < s.length(); i++)
    {
        for(int j = 0; j < i; j++)
        {
            if(i == j)
            {
                continue;
            }
            else if(s.charAt(i) == s.charAt(j))
            {
                noRepetition = false;
                return false;
            }
        }

    }
    return noRepetition;
}
}

The boolean IsValidNumber never operates, I tried to print simple check words at different levels of it, and nothing ever prints but the String.

Thanks in advance, cheers

Was it helpful?

Solution

You've got a stray semicolon after the while() declaration, which causes the loop to immediately end. Consequently, your for loop constructs a number, and whatever number it constructs is immediately printed.

Consider the following instead:

public static void main(String[] args)
{
   String toGuess="";

   do { // Always try to generate at least one number.
       toGuess = ""; //Reset each time we loop.

       for(int i=0; i<4; i++) {
            Random rando= new Random();
            int rd=rando.nextInt(9);
            toGuess=toGuess+rd;
        }
    } while(!IsValidNumber(toGuess));

    System.out.println(toGuess);
}

That might work better.

Basically, while (exp); is equivalent to while(exp) {} or an empty while loop. Only put a semicolon after your while(exp) when using the do...while construct I illustrate here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top