Ricky Ricky - 3 months ago 19
Java Question

Java while loop bracket function

My Code:

import java.util.*;

public class test

public static void main(String[] args)
Scanner Input = new Scanner(System.in);

System.out.println("Randomly put a ball to cup");
int cupnumber = (int) ((Math.random()*6)+1);

System.out.println("Guess where is it");
int guess;
guess = Input.nextInt();

System.out.println("Guess a number");
guess = Input.nextInt();

public static void guess(int cupnumber, int guess)
if(cupnumber == guess)
System.out.print("Guess it correctly");
System.out.println("Try again");



I am new to java programming. In the above code, without these bracket {} under while loop part, i cannot re-input a number if cupnumber doesn't not equal to guess. Yet, with these {} bracket under while loop, i can re-input a number if cupnumber doesn't not equal to guess.

Why does{} bracket make such a difference?

Can anyone help me? Thank you


The while statement continually executes a block of statements while a particular condition is true.

Its syntax can be expressed as:

while (condition) {

In your code, as long as the cupnumber IS NOT EQUAL TO guess (condition becomes true), while loop goes inside the brackets.

Please find the below Oracle link for more understanding: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html