Jump to content

Was writing a simple console game in Java. I am stuck in a situation where to continue further; I need to point the flow of the program to a while loop that comes earlier before this block of code I am talking about. The game is about creating a random integer, and I have to guess the integer and also get hints if I am close or far.

 

import java.util.Scanner;

public class GuessTheNumber{
    int input, random, lastInput;
    Scanner scanner = new Scanner(System.in);
    public void RandomValue(){
       random = (int) Math.random() * 100;
    }
    public void Input(){
        System.out.println("Guess The Number challenge!");
        System.out.println("Enter a number.");
        input = scanner.nextInt();
    }
    public void Compute(){
        if (random == input){
            System.out.println("You guessed the number on your first try!");
            System.out.println("The number is "+random);
            scanner.close();
        }
        else {
            if (Math.abs(random - input) >= 75){
                System.out.println("too high");
            }
            if (Math.abs(random - input) >= 50){
                System.out.println("high");
            }
            if (Math.abs(random - input) >= 25){
                System.out.println("low");
            }
            if (Math.abs(random - input) < 25){
                System.out.println("too low");
            }
            while(input != random){
                lastInput = input;
                input = scanner.nextInt();
                if (random == input){
                    System.out.println("You guessed the number!");
                    System.out.println("The number is "+random);
                    scanner.close();
                    break;
                }
                if (Math.abs(random - input) < Math.abs(random - lastInput)){
                    System.out.println("lower");
                }
                else {
                    System.out.println("Don't enter the same number!");
                    break;
                }
                if (Math.abs(random - input) > Math.abs(random - lastInput)){
                    System.out.println("higher");

                }
                else{
                    System.out.println("Don't enter the same number!");
                    break;
                }
            }
    }
}
    public static void main(String[] args){
        GuessTheNumber game = new GuessTheNumber();
        game.Input();
        game.RandomValue();
        game.Compute();
    }
    
}

 

First of all, this code already doesn't work as planned, but I will try to solve that later, but the main face problem is that at "Don't enter the same number", instead of the break, I need to jump the flow again to that while loop that is above it. How do I do it? "Goto" actually doesn't exist, I guess.

PLEASE MARK COMMENTS AS SOLUTION IF SATISFIED!!

bigger number better, makes me look cooler.

Link to comment
https://linustechtips.com/topic/1528643-how-to-jump-between-flow-in-java/
Share on other sites

Link to post
Share on other sites

Is there a reason you're using multiple if/else in a row? Why not just this, then you won't be using a break:

 

if (random == input){
    System.out.println("You guessed the number!");
    System.out.println("The number is "+random);
    scanner.close();
} else if (Math.abs(random - input) < Math.abs(random - lastInput)){
 	System.out.println("lower");
} else if (Math.abs(random - input) > Math.abs(random - lastInput)){
	System.out.println("higher");
} else {
	System.out.println("Don't enter the same number!");
}

 

Link to post
Share on other sites

22 minutes ago, Hensen Juang said:

How do I do it? "Goto" actually doesn't exist, I guess.

The gist of it would be to run the entire program in a loop and only drop out of the loop once the conditions have been met.

 

int target = random();
ArrayList<Integer> previousGuesses = new ArrayList<>(10);

while (true) {
    int input = getInput();

    if (input == -1) {
        // quit
        break; // drops out of the loop
    }
    else if (previousGuesses.contains(input)) {
        // Choose another number
    }
    else if (input > target) {
        // too high
    }
    else if (input < target) {
        // too low
    }
    else {
        // you got it!
        break; // drops out of the loop
    }
    
    previousGuesses.add(input);
}

 

You also will need to keep track of your previous guesses, hence my ArrayList. You could also use a straight int[] and keep track of your index manually, but you have to be prepared to accept a large number of guesses, and ArrayList takes the work out of expanding the array.

 

P.S. Don't quote my Java verbatim, I'm running on memory.

 

P.P.S. Make sure you're following the Java standard naming capitalization rules (*hinthint* functions start lowercase).

Main System (Byarlant): Ryzen 9 5950X | Asus B550-Creator ProArt | EK 240mm Basic AIO | 32GB G.Skill DDR4 3600MT/s CL16 | XFX Speedster SWFT 210 RX 6600 | Samsung 990 PRO 2TB / Samsung 990 EVO Plus 4TB | Corsair RM750X | StarTech 4× USB 3.0 Card | Realtek RTL8127 10G NIC | Hyte Y60 Case | Dell U3415W Monitor | Keychron K12 Blue (RGB backlight)

 

Laptop (Narrative): Lenovo Flex 5 81X20005US | Ryzen 5 4500U | 16GB DDR4 3200MT/s (soldered) | Vega II 384SP Graphics | SKHynix P31 1TB NVMe SSD | Intel AX200 Wifi | Asus 2.5G USB NIC | Asus ProArt PA278QV | Keychron K4 Brown (white backlight)

 

Proxmox Server (Veda): Ryzen 7 3800XT | ASRock Rack X470D4U | Corsair H80i v2 | 128GB Micron DDR4 ECC 3200MT/s | 2× Samsung PM963a 960GB SSD / 4× WD 10TB / 4× Seagate 14TB Exos / 4× Micron MX500 2TB / 8× WD 12TB (custom external SAS enclosure) | Seasonic Prime Fanless 500W | Intel X550-T2 10G NIC | LSI 9300-8i HBA | Adaptec 82885T SAS Expander | Fractal Design Node 804 Case

 

Proxmox Server (La Vie en Rose)GMKtec Mini PC | Ryzen 7 5700U | 32GB Lexar DDR4 (SODIMM) | Vega II 512SP Graphics | Lexar 1TB 610 Pro SSD | 2× Realtek 8125 2.5G NICs


Media Center/Video Capture (Jesta Cannon): Ryzen 5 1600X | ASRock B450M Pro4 R2.0 | Noctua NH-L12S | 16GB Crucial DDR4 3200MT/s | EVGA GTX750Ti SC | UMIS NVMe SSD 256GB / TEAMGROUP MS30 1TB | Corsair CX450M | Viewcast Osprey 260e Video Capture | TrendNet (AQC107) 10G NIC | LG WH14NS40 BD-ROM | Silverstone Sugo SG-11 Case | Sony XR65A80K

 

Workbench (Doven Wolf): Lenovo m715q | Ryzen Pro 3 2200GE | 16GB Crucial DDR4 3200MT/s (SODIMM) | Vega 8 Graphics | SKHynix (OEM) 256GB NVMe SSD | uni 2.5G USB NIC | HDMI add-in module

 

Network:

Spoiler
                       ┌─────────────── Office/Rack ───────────────────────────────────────────────┐
Google Fiber Webpass ── Cloud Gateway Max ══╦═ Pro XG 8 ══╦═ Flex 2.5-8 ══╦═ Doven Wolf
                      La Vie en Rose (DNS) ═╬═ Narrative  ╠═ Veda-NAS     ╠═ La Vie en Rose (vmbr)
                                Veda (DNS) ─┘             ╠═ Veda (vmbr)  ├─ Ptolemy (vmbr)
╔═════════════════════════════════════════════════════════╩═ Ptolemy-NAS  ├─ Veda (Mgmt)
║   ┌ Closet ┐      ┌───────── Bedroom ─────────┐                         └─ Veda (IPMI)
╚═══ Flex XG ══╦╤═══ Flex XG ══╤╦═ Byarlant
       (PoE)   ║│              │╠═ Narrative 
Kitchen Jack ══╣└─ Dual PoE ┐  │╚═ Jesta Cannon*
   (Testing)   ║┌─ Injector ┘  └── Work Laptop
     Bedroom ══╝│        ┌─────── Media Center ────────────────────────────┐
     Jack #2    └──────── Switch 8 ────────────┬─ nanoHD Access Point (PoE)
Notes:                                         ├─ Sony PlayStation 4 
─── is Gigabit / ═══ is Multi-Gigabit          ├─ Pioneer VSX-S520
* = cable passed from Bedroom to Media Center  └─ Sony XR65A80K (Google TV)
Link to post
Share on other sites

Ignoring the many redundant if-else statements, the basic problem with your while-loop is its position. Take that while-loop out of the else-statement of Compute. The logic of that if-else block is only about the very first guess, the while-loop is about all subsequent guesses. That means Compute should run through the if-else block once and then get stuck in the while loop until the correct number is guessed. Basically this:

 

if (input = random)
	// Hooray, you got it right on your first guess
} else {
	// Try again
}

while (input != random){
	// Do all the value checks and tell the player if they should guess higher or lower
}

 

 

And now a word from our sponsor: 💩

ℑ𝔣 𝔶𝔬𝔲 𝔬𝔫𝔩𝔶 𝔫𝔬𝔱𝔦𝔠𝔢 𝔭𝔢𝔯𝔣𝔬𝔯𝔪𝔞𝔫𝔠𝔢 𝔭𝔯𝔬𝔟𝔩𝔢𝔪𝔰 𝔴𝔥𝔢𝔫 𝔶𝔬𝔲 𝔥𝔞𝔳𝔢 𝔞 𝔰𝔱𝔞𝔱 𝔠𝔬𝔲𝔫𝔱𝔢𝔯 𝔬𝔳𝔢𝔯𝔩𝔞𝔶 𝔞𝔠𝔱𝔦𝔳𝔢, 𝔶𝔬𝔲 𝔞𝔯𝔢 𝔪𝔢𝔯𝔢𝔩𝔶 𝔩𝔬𝔬𝔨𝔦𝔫𝔤 𝔣𝔬𝔯 𝔭𝔯𝔬𝔟𝔩𝔢𝔪𝔰 𝔱𝔬 𝔟𝔢 𝔲𝔭𝔰𝔢𝔱 𝔬𝔳𝔢𝔯. 𝔗𝔲𝔯𝔫 𝔬𝔣𝔣 𝔱𝔥𝔢 𝔠𝔬𝔲𝔫𝔱𝔢𝔯 𝔟𝔢𝔣𝔬𝔯𝔢 𝔞𝔰𝔨𝔦𝔫𝔤 𝔣𝔬𝔯 𝔥𝔢𝔩𝔭 𝔞𝔫𝔡 𝔰𝔢𝔢 𝔦𝔣 𝔶𝔬𝔲 𝔰𝔱𝔦𝔩𝔩 𝔫𝔬𝔱𝔦𝔠𝔢.

-.-. --- --- .-.. --..-- / -.-- --- ..- / -.- -. --- .-- / -- --- .-. ... . / -.-. --- -.. .

ᑐᑌᑐᑢ

Spoiler

    ▄██████                                                      ▄██▀

  ▄█▀   ███                                                      ██

▄██     ███                                                      ██

███   ▄████  ▄█▀  ▀██▄    ▄████▄     ▄████▄     ▄████▄     ▄████▄██   ▄████▄

███████████ ███     ███ ▄██▀ ▀███▄ ▄██▀ ▀███▄ ▄██▀ ▀███▄ ▄██▀ ▀████ ▄██▀ ▀███▄

████▀   ███ ▀██▄   ▄██▀ ███    ███ ███        ███    ███ ███    ███ ███    ███

 ██▄    ███ ▄ ▀██▄██▀    ███▄ ▄██   ███▄ ▄██   ███▄ ▄███  ███▄ ▄███▄ ███▄ ▄██

  ▀█▄    ▀█ ██▄ ▀█▀     ▄ ▀████▀     ▀████▀     ▀████▀▀██▄ ▀████▀▀██▄ ▀████▀

       ▄█ ▄▄      ▄█▄  █▀            █▄                   ▄██  ▄▀

       ▀  ██      ███                ██                    ▄█

          ██      ███   ▄   ▄████▄   ██▄████▄     ▄████▄   ██   ▄

          ██      ███ ▄██ ▄██▀ ▀███▄ ███▀ ▀███▄ ▄██▀ ▀███▄ ██ ▄██

          ██     ███▀  ▄█ ███    ███ ███    ███ ███    ███ ██  ▄█

        █▄██  ▄▄██▀    ██  ███▄ ▄███▄ ███▄ ▄██   ███▄ ▄██  ██  ██

        ▀███████▀    ▄████▄ ▀████▀▀██▄ ▀████▀     ▀████▀ ▄█████████▄

 

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

×