Write a Java program to prompt the user for choosing a task between two tasks (%
ID: 3536809 • Letter: W
Question
Write a Java program to prompt the user for choosing a task between two tasks (%u201CRollDice%u201D or %u201CDistance%u201D). When the user type in %u201CRollDice%u201D, then your program will carry out the simulation of the rolling of a pair of dice. For each die in the pair, the program should generate a random number between 1 and 6 (inclusive). It should print out the result of the roll of each die and the total roll (the sum of the two dice).
When the user type in %u201CDistance%u201D, then your program will carry out the computation of the distance between two points in the Cartesian coordinate system. The distance between the two points (x1,y1) and (x2,y2) is computed by taking the square root of the quantity (x1-x2)2+ (y1-y2)2. Format the resulting distance so that it is represented with two digits after the decimal place. The inputs will always be integers.
You must use a switch statement and the Random class (plus other classes) for this program.
Explanation / Answer
//please use jdk 7 and above to compile
import java.util.Scanner;
import java.io.*;
import java.util.Random;
import java.lang.*;
class Choice
{
public static void main(String args[]) throws IOException
{
//read
Scanner rw = new Scanner(System.in);
System.out.println("Enter your Choice: RollDice Or CDistance");
String ch = rw.next();
switch(ch)
{
case "RollDice":
Random r=new Random();
int r1= r.nextInt(6) +1 ;
int r2 = r.nextInt(6) +1;
System.out.println("Roll 1 Value: "+r1+" Roll 2 Value:"+r2+" Sum of Rolls:"+(r1+r2));
break;
case "CDistance":
System.out.println("Enter two points in separate lines as space separated integers:");
int x1= rw.nextInt();
int y1=rw.nextInt();
int x2= rw.nextInt();
int y2=rw.nextInt();
double dist = Math.sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
System.out.format("The value of Distance is: %.2f %n", dist);
break;
default:
System.out.println("Please enter 'RollDice' or 'CDistance' only (without quotes)");
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.