Please write in JAVA code:
Create a simple dice game that rolls 2 die at the press of a button. Append the results of each roll to a text area. If the values rolled are the same(i.e., you've rolled a double), indicate that next to the dice values.
import java.io.*;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import java.util.Random;
public class gam{
// Open file in append mode.
public static void appendStrToFile(String fileName,
String str)
{
try {
// Open given file in append mode.
BufferedWriter out = new BufferedWriter(
new FileWriter(fileName, true));
out.write(str+"\n");
out.close();
}
catch (IOException e) {
System.out.println("exception occoured" + e);
}
}
// perform game using random numbers.
static void func(){
String s="", d1="",d2="";
Random rand = new Random();
int rand_int1 = rand.nextInt(6)+1;
int rand_int2 = rand.nextInt(6)+1;
d1=Integer.toString(rand_int1);
d2=Integer.toString(rand_int2);
if(rand_int1==rand_int2){
s=d1+", "+d2+" you've rolled a double.";
}
else{
s=d1+", "+d2;
}
appendStrToFile("result.txt", s);
}
public static void main(String []args){
// crate a file
File file = new File("C:\\Users\\LENOVO\\Desktop\\game\\result.txt");
int t=1;
boolean result;
try
{
result = file.createNewFile(); //creates a new file
if(result) // test if successfully created a new file
{
System.out.println("file created "+file.getCanonicalPath()); //returns the path string
}
else
{
System.out.println("File already exist at location: "+file.getCanonicalPath());
}
}
catch (IOException e)
{
e.printStackTrace(); //prints exception if any
}
// Take input
Scanner myObj = new Scanner(System.in);
while(t ==1){
System.out.println("Press 1 to role dice or press 0 to exit game.");
String option = myObj.nextLine();
t=Integer.parseInt(option);
if(t==1){
func();// perform the game
}
else{
System.out.println("Exiting game...");
}
}
}
}
The final results of the game are written to "result.txt" file.
Get Answers For Free
Most questions answered within 1 hours.