1 Replies - 491 Views - Last Post: 26 June 2016 - 10:05 AM Rate Topic: -----

#1 frostedlime5   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 40
  • Joined: 01-April 16

Why is my java programming not exiting out of the code

Posted 26 June 2016 - 09:59 AM

Currently, I am making a dice game called 43. If the user plays, and chooses to say no at the end to play again, it is supposed to exit the program. My problem is, it will not exit. Any tips on how to solve this please? Here is my code.
import java.util.Scanner;

public class dice_game {
	public static void main(String args[]){
		int n=6, total, randomNum1, randomNum2;
		String choice;
		boolean flag = true;
		Scanner input = new Scanner(System.in);
		System.out.println("IT'S TIME TO PLAY 43!");
		while(flag){
			int rollNum=1;
			int randomTotal=0;
			for(int i=0; i<n; i++){
				int randomNumGen1 = (int)(Math.random() * 6)+1;
				int randomNumGen2 = (int)(Math.random() * 6)+1;
				randomNum1 = randomNumGen1;
				randomNum2 = randomNumGen2;
				randomTotal += randomNum1 + randomNum2;
				if(randomNum1==randomNum2){
					System.out.println("ROLL #" + rollNum+ ": " + randomNum1 + " " + randomNum2 + " DOUBLES!!! YOUR TOTAL IS: " + randomTotal);
					rollNum++;
					i--;
					if(randomTotal>=45){
						System.out.println(" YOU ARE A WINNER!");
						break;
					}
					else if(randomTotal == 10 || randomTotal == 20 || randomTotal == 30 || randomTotal == 40){
						System.out.println("TOO BAD! YOU LOSE!");
						System.exit(0);
					}
			}
				else if(randomNum1!=randomNum2){
					System.out.println("ROLL #" + rollNum+ ": " + randomNum1 + " " + randomNum2 + " YOUR TOTAL IS: " + randomTotal);
					rollNum++;
					if(randomTotal>=45){
						System.out.println("YOU ARE A WINNER!");
						break;
					}
					else if(randomTotal == 10 || randomTotal == 20 || randomTotal == 30 || randomTotal == 40){
						System.out.println("TOO BAD! YOU LOSE!");
						break;
					}
				}	
			}
			System.out.println("Would you like to play again (Yes or No)?");
			choice = input.nextLine();
			if(choice=="yes" || choice=="YES" || choice=="Yes"){
				flag=false;
				}
			if(choice=="no" || choice=="NO" || choice=="No"){
				System.exit(1);
			}
		}
	}
}


Is This A Good Question/Topic? 0
  • +

Replies To: Why is my java programming not exiting out of the code

#2 NormR   User is online

  • D.I.C Lover
  • member icon

Reputation: 870
  • View blog
  • Posts: 6,695
  • Joined: 25-December 13

Re: Why is my java programming not exiting out of the code

Posted 26 June 2016 - 10:05 AM

The code should use the equals() method to compare Strings, not the == operator:
   str1.equals(str2);  // see if str1 is the same as str2 


Also there is another version of the equals method that will ignore the case.
See the API doc for the String class for more details.

This post has been edited by NormR: 26 June 2016 - 10:07 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1