Write a program that prompts for a pattern of 6 dice and then counts the number
ID: 3532187 • Letter: W
Question
Write a program that prompts for a pattern of 6 dice and then counts the number of throw necessary to get that pattern to appear. Use several methods: you might have one for input, one for processing, and one for output (Please use these methods and more if needed). Guarantee inputs are in an acceptable range (The numbers typed in are between 1-6). A sample run of the game would look like this:
Please enter a series of 6 dice that you would like the computer to duplicate
1 2 3 4 5 6
(Notice that there are spaces in between each number)
It took 4506 throws to get the pattern 1 2 3 4 5 6 to appear
Explanation / Answer
//DicePattern.java
import java.util.Random;
import java.util.Scanner;
public class DicePattern {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int[] pattern=getPattern(input);
int[] toss;
int times=0;
while(true){
times++;
toss=Toss();
if(match(toss,pattern))
break;
}
System.out.printf("It took %d throws to get the pattern ",times);
printArr(pattern);
System.out.println("to appear");
input.close();
}//end main
public static int[] getPattern(Scanner input){//returns pattern from userinput
int[] picks=new int[6];
int flag=0;
do{
flag=0;
System.out.println("Please enter a series of 6 dice that you would like the computer to duplicate");
for(int i=0;i<picks.length;i++){
picks[i]=input.nextInt();
if(picks[i]<1 || picks[i]>6){
flag=1;
}
}
if(flag==1){
System.out.println("There was one or more invalid input. Numbers must be between 1 and 6.");
}
}while(flag==1);
return picks;
}//end getPattern
public static int[] Toss(){//return rand of 6 dice
int[] toss=new int[6];
Random rand=new Random();
for(int i=0;i<6;i++){
toss[i]=rand.nextInt(6)+1;// 1 to 6
}
return toss;
}//end Toss
public static boolean match(int a[],int b[]){//return if numbers match
if(a.length!=b.length)
return false;
for(int i=0;i<a.length;i++){
if(a[i]!=b[i])
return false;
}
return true;
}
public static void printArr(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
}
}//end class
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.