Programming Examples

Java program for a game of dice is to be simulated for two players, each player gets a chance to throw his dice


A game of dice is to be simulated for two players, each player gets a chance to throw his dice, and the value is added to his points, this process continues alternately until for the player whose added points equals to 20 and is declared the winner. Write a program to simulate this process using the random( ) function.

Solution

import java.util.*;
class Game
{
	public static void main(String arr[])
	{
		int i,r1,r2,s1=0,s2=0;
		for(i=1;s1<20 && s2<20;i++)
		{
		r1=1+(int)(Math.random()*20);
		s1+=r1;
		if(s1<20)
		{
		r2=1+(int)(Math.random()*20);
		s2+=r2;
		}
		}
		if(s1>s2)
		System.out.println("Winner is player 1");
		else
		System.out.println("Winner is player 2");
	}
}
Output

Latest Current Affairs 2025 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2025 Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz