Eren Arican
Eren Arican

Reputation: 11

A random number with 3 digit and try to guess every digit one by one

I am new in Java and for the moment basic with methods, classes and constructors. For practice I am trying to write a basic game (safecracker). So my logic is get a 3 digit random number and try to guess it.

private static int takeRandomSafeCode(int min, int max) {
    Random random = new Random();
    int result = random.nextInt(max - min) + min;
    return result;  

 private static void playGame() {
    int safeCode = takeRandomSafeCode(100, 999);
    int guess = takeGuess();

These are my random number methods. But if player guess a number and first digit is correct but on a wrong place I want to say "1 digit is correct but on a wrong position" or if one digit is correct "1 digit is correct and correct position"

I need to use here if-else statement i guess but I get my numbers int variable. What is the way of checking numbers one by one? Do I need to use a String? I am a little bit lost at this point. I would appreciate with your help.

Upvotes: 0

Views: 1328

Answers (2)

Michael
Michael

Reputation: 44250

It may be preferable - and result in simpler code - if you generate an integer array with three elements. Logically, the safe code 1-2-3 is not one hundred and twenty three but actually 1 followed by 2 followed by 3.

private static int takeRandomDigit() {
    Random random = new Random();
    int result = random.nextInt(10);
    return result;
}

private static void playGame() {
    int[] safeCode = {takeRandomDigit(), takeRandomDigit(), takeRandomDigit()};
    int guess = takeGuess();

    for (int safeDigit : safeCode) // for each digit in the safe code
    {
        // if the digit matches the guess, do something
    }
}

Upvotes: 1

Veselin Davidov
Veselin Davidov

Reputation: 7081

You can use some math to take the numbers for example if your number is: d=253

d % 10 -> gives you 3
d / 10 % 10 -> gives you 5
d / 100 -> gives you 2

Changing it to string is also an option because you can then access the different characters using the string functions like charAt etc.

But if you want to make it the Java and OOP way in order to learn you can make an object and add the 3 numbers as properties of that object and input some of the logic for checking there instead of doing some magic tricks like the above. For example:

class Combination {
  private  int firstPos;
  private  int secondPos;
  private  int thirdPos;

  public  Combination(){
    firstPos=random.nextInt(10);
    secondPos=random.nextInt(10);
    thirdPos=random.nextInt(10);
 }

 public boolean checkCombination(Combination testedCombination){
       .............
 }
 some methods, getter, setters etc
}

Upvotes: 0

Related Questions