0
import java.util.*;

class token {
public static void main(String args[]){
    Scanner input = new Scanner(System.in);
    Random number = new Random();

    System.out.println("Do you want to play again(y/n)? ");
    String in = input.nextLine();   

    do{
    int num1,num2,sum;
    num1 = 1+number.nextInt(6);
    num2 = 1+number.nextInt(6);

    sum = num1 + num2;


    System.out.print("Dice 1: "+num1);
    System.out.print("\nDice 2: "+num2);
    System.out.print("\nSum: "+sum);

    if(sum%2==1){
        System.out.println("\nYou have lost 1 token.");
    }else if(sum>10){
        System.out.println("\nYou have won 2 tokens.");
    }else if(sum>11){
        System.out.println("\nYou have won 2 tokens.");
    }else if(sum>12){
        System.out.println("\nYou have won 2 tokens.");
    }else{
        System.out.println("\nYou have won 1 token.");
    }

    System.out.println("Do you want to play again(y/n)? ");
    String in1 = input.nextLine();  
    }while(in == "y");

}
}

So I tried to use a do while loop but unfortunately, it does not loop at all. Sample output: Do you want to play again(y/n)? y Dice 1: 3 Dice 2: 4 Sum: 7 You have lost 1 token. Do you want to play again(y/n)? y

I want my program to continuously loop unless the user enters n.

name123
  • 773
  • 3
  • 9
  • 9

4 Answers4

2

replace in == "y" with in.equals("y")

and

String in1 = input.nextLine(); with in = input.nextLine();

because you are not up updating value of in so if input is "y" for the 1st time it will loop forever, or will run just once otherwise.

Ankit
  • 6,554
  • 6
  • 49
  • 71
0

You should take repeated input in your while loop, and then have a termination condition:

String in = input.nextLine();
do {
    /* conditional logic */
    in = input.nextLine();
} while (in.equals("y"));

The way you have it you are setting it to a new string every time within the loop, which will cause it to not be used in the next sequence.

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
Rogue
  • 11,105
  • 5
  • 45
  • 71
0

Instead of using

while(in == "y");

you should use:

while(in.equals("y"));

== operator is testing the reference.

equals really checks the contents of the string.

Attila
  • 3,206
  • 2
  • 31
  • 44
0

You should use

while(!in.equalsIgnoreCase("n"));

Qazi
  • 132
  • 1
  • 3
  • 11