HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Guessing Game In Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
gamejavaguessing

Problem

import java.io.IOException;
import java.util.Scanner;

public class Main {

    private static int random = (int) (Math.random() * 100 + 1);
    private static int data;
    private static int go;
    private static int attempt = 10;

    public static void Start() throws IOException {

        Scanner scanInput = new Scanner(System.in);
        data = scanInput.nextInt();

        if (data > 100) {
            System.out.println("Only Enter Numbers Between 0-100");
            Start();
        } else if (data == random) {
            System.out.println("Wow, you guessed it!!");
            scanInput.close();
            System.exit(0);
        } else if (data  random) {
            go += 1;
            if (go == attempt) {
                System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
                scanInput.close();
                System.exit(0);
            }
            System.out.println("Lower");
            Start();
        }
    }

    public static void main(String[] args) throws IOException {
        System.out.println("Guess A Number Between 0-100 Within " + attempt + " Goes");
        Start();
    }

}

Solution

I will try to point out things that can be improved in your code:

  1. Removing complexity by using return:



if (data > 100) {
        System.out.println("Only Enter Numbers Between 0-100");
        Start();
        return;
    }

    if (data == random) {
        System.out.println("Wow, you guessed it!!");
        scanInput.close();
        return;
    }

    if (data  random) {
       // ...
    }


  1. Try to avoid recursion, if it is not needed - your code can be easily converted not to use recursion:



public static void Start() throws IOException {

while (true) {

    if (go == attempt) {
        System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
        scanInput.close();
        System.exit(0);
        return;
    } 

    Scanner scanInput = new Scanner(System.in);
    data = scanInput.nextInt();

    if (data > 100) {
        System.out.println("Only Enter Numbers Between 0-100");
        continue;
    }

    if (data == random) {
        System.out.println("Wow, you guessed it!!");
        scanInput.close();
        break;
    } 

    if (data < random) {
        go ++;
        if (go == attempt) {
            System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
        continue;
    }
}


  1. return value instead of System.exit(0);



In order to make your function more reusable, you can have it return a boolean specifying if the number was guessed or not. The caller can decide what to do with the information (maybe this should be integrated in some guessing Web service and those exits are not ok).

Also, it would make sense to allow the user to abort guessing.

// true if guesses, otherwise false
public static boolean Start( throws IOException {
    go = 0;

    while (true) {
        if (go == attempt) {
            System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
            scanInput.close();
            return false;
        }

        Scanner scanInput = new Scanner(System.in);
        data = scanInput.nextInt();

        // define an abort constant and inform the user what value abort the guessing process
        if (data == AbortNumber) {
            System.out.println("Guessing aborted by user");
            return false;
        }

        if (data > 100) {
            System.out.println("Only Enter Numbers Between 0-100");
            continue;
        }

        if (data == random) {
            System.out.println("Wow, you guessed it!!");
            scanInput.close();
            break;
        } 

        if (data < random) {
            go ++;
            if (go == attempt) {
                System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
            continue;
        }
}


  1. Variable initializations - go is initialized with 0, but it is better to put it explicitly. It is particularly useful, when your guessing instance is reused, as go is changed during the guessing process.



  1. Proper names for variables - it is recommended to provide meaningful names for your variables. E.g.:



data -> userGuess
go -> step
attempt -> maxAttempts


  1. Avoid repetition - use a constant for maximum number range and use it across your code:



const int MaxNumber = 100;
// ...
static int random = (int) (Math.random() * MaxNumber + 1);
// ...
if (data > MaxNumber)
// ...
System.out.println("Only Enter Numbers Between 0-" + MaxNumber);
// ...


  1. Testing for maximum attempts - == should do the work, but >= is safer: if (go >= attempt). It sounds a little paranoiac, but in complex programs and especially when dealing with multi-threading, it is possible that the variable passes over the threshold and the cycle never ends.



Final code

By merging some parts of code in a separate function, your final code could look like (not tested and no renames performed):

```
private static const int MaxNumber = 100;
private static int random = (int) (Math.random() * MaxNumber + 1);
private static int data;
private static int go;
private static int attempt = 10;

private static void endGuess(String message, Scanner scanInput) {
System.out.println(message);
scanInput.close();
}

public static boolean StartGuess() throws IOException {
go = 0;

while (true) {
Scanner scanInput = new Scanner(System.in);
data = scanInput.nextInt();

if (go >= attempt) {
endGuess("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(", scanInput);
return false;
}

if (data > MaxNumber ) {
endGuess("Only Enter Numbers Between 0-" + MaxNumber, scanInput);
continue;
}

if (data == random) {
endGuess("Wow, you guessed it!!", scanInput);
return true;
}

go ++;

if (data rand

Code Snippets

if (data > 100) {
        System.out.println("Only Enter Numbers Between 0-100");
        Start();
        return;
    }

    if (data == random) {
        System.out.println("Wow, you guessed it!!");
        scanInput.close();
        return;
    }

    if (data < random) {
        go ++;
        if (go == attempt) {
            System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
            scanInput.close();
            System.exit(0);
            return;
        }
        System.out.println("Higher");
        Start();
        return;
    }

    if (data > random) {
       // ...
    }
public static void Start() throws IOException {

while (true) {

    if (go == attempt) {
        System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
        scanInput.close();
        System.exit(0);
        return;
    } 

    Scanner scanInput = new Scanner(System.in);
    data = scanInput.nextInt();

    if (data > 100) {
        System.out.println("Only Enter Numbers Between 0-100");
        continue;
    }

    if (data == random) {
        System.out.println("Wow, you guessed it!!");
        scanInput.close();
        break;
    } 

    if (data < random) {
        go ++;
        if (go == attempt) {
            System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
        continue;
    }
}
// true if guesses, otherwise false
public static boolean Start( throws IOException {
    go = 0;

    while (true) {
        if (go == attempt) {
            System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
            scanInput.close();
            return false;
        }

        Scanner scanInput = new Scanner(System.in);
        data = scanInput.nextInt();

        // define an abort constant and inform the user what value abort the guessing process
        if (data == AbortNumber) {
            System.out.println("Guessing aborted by user");
            return false;
        }

        if (data > 100) {
            System.out.println("Only Enter Numbers Between 0-100");
            continue;
        }

        if (data == random) {
            System.out.println("Wow, you guessed it!!");
            scanInput.close();
            break;
        } 

        if (data < random) {
            go ++;
            if (go == attempt) {
                System.out.println("You have guessed the wrong number " + go + " times, sorry but you'll have to try again! :(");
            continue;
        }
}
data -> userGuess
go -> step
attempt -> maxAttempts
const int MaxNumber = 100;
// ...
static int random = (int) (Math.random() * MaxNumber + 1);
// ...
if (data > MaxNumber)
// ...
System.out.println("Only Enter Numbers Between 0-" + MaxNumber);
// ...

Context

StackExchange Code Review Q#118422, answer score: 12

Revisions (0)

No revisions yet.