I am new to Java and programming overall. I am currently attending an introductory class to object oriented programming and need some help in writing a code. The program I am writing is for a dart game. I am supposed to randomly generate the number of times the dart hits a certain area of the board and store it into one array. Then in another array, I have to keep track of the scores. the scores should add up to a total of 1000 or over but I am having problem doing that. My program works fine but it does show the result even when the sum is under 1000. I even tried using do-while loop but i don't seem to get the right answer. Also I need help with shortening the lines 18-27. Here's my code, any kind of help is appreciated.
import java.util.Arrays;
import java.util.Random;
public class Assignment3Q1
{
public static void main(String[] args)
{
Random darts = new Random();
int [] timesHit = new int [10];
int sum=0;
int tosses=0;
do
{
for ( int i = 0; i < timesHit.length; i++)
{
timesHit[i]= 20 + darts.nextInt(20);
}
int [] points = new int [10];
points [0] = timesHit[0]*7;
points [1] = timesHit[1]*5;
points [2] = timesHit[2]*5;
points [3] = timesHit[3]*5;
points [4] = timesHit[4]*3;
points [5] = timesHit[5]*3;
points [6] = timesHit[6]*3;
points [7] = timesHit[7];
points [8] = timesHit[8];
points [9] = timesHit[9];
for (int i=0; i<timesHit.length; i++)
{
tosses += timesHit[i];
}
for (int i=0; i<points.length; i++)
{
sum += points[i];
}
System.out.println(tosses);
System.out.println(sum);
break;
}while (sum>=1000);
}
}
Here is the correct logic to keep looping until the desired result (sum >= 1000). Also notice the use of the multiplier array so that the points can be calculated in the hit loop. The other two sums can also be done in the same loop.
public class Assignment3Q1 {
public static void main(String[] args)
{
Random darts = new Random();
int sum=0;
int tosses=0;
int multiplier[] = {7, 5, 5, 5, 3, 3, 3, 1, 1, 1};
do
{
int [] timesHit = new int [10];
int [] points = new int [10];
tosses = 0;
sum = 0;
for ( int i = 0; i < timesHit.length; i++)
{
timesHit[i]= 20 + darts.nextInt(20);
points[i] = timesHit[i] * multiplier[i];
tosses += timesHit[i];
sum += points[i];
}
} while (sum<1000);
System.out.println("Final Tosses="+tosses);
System.out.println("Final Sum="+sum);
}
}
Related
So i am kinda new to java and i need help with a problem.
I have this code:
import java.util.Random;
public class Board
{
private int NumberOfCards;
private int NumberOfPairs;
private int[] DeckOfCards;
private int CardsRemaining;
public Board(int NumberOfPairs){
this.NumberOfCards = NumberOfCards;
this.NumberOfPairs = NumberOfPairs;
this.CardsRemaining = CardsRemaining;
DeckOfCards = new int [2*NumberOfPairs];
Random numbers = new Random();
for (int i = 0; i < NumberOfPairs; i++) {
DeckOfCards[i] = numbers.nextInt();
}
The code above is not completed and there are many classes left to be completed but the
problem is that:
Lets say that NumberOfPairs = 3
This will mean that inside the array we will have the numbers 0,1,2 with random positions and this will also mean that we will have 3 positions of the array "empty" (because the size is 2*NumberOfPairs)
What i am trying to do is for example this:
Inside the array will still be the numbers 0,1,2 but twice and with random order such as:
1,0,2,2,1,0
Does anyone have any ideas ? Thank you in advance!
Oh yes i forgot to mention that the NumberOfPairs is not certain and will be given by the user via input
Because Random is random, it won't generate sequences like that. You have to actually make a sequence if that's what you want.
There's a bit of tricky math in the indexes, you should write these out by hand to see how it works.
Integer deck = new Integer[2*NumberOfPairs];
for (int i = 0; i < NumberOfPairs; i++) {
deck[i*2] = i;
deck[i*2+1] = i;
}
Now you have a list of values that aren't random but exactly the sequence you want. Now if you want them to be in a random order you need to shuffle them, like a deck of cards.
List<Integer> deckList = new ArrayList<>( Arrays.asList( deck) );
Collections.shuffle( deckList );
int i = 0;
DeckOfCards = new int[2*NumberOfPairs];
for( Integer x : deckList )
DeckOfCards[i++] = x;
Now you have some preset values in a random order. This would be a bit less complicated if you used an ArrayList for DeckOfCards instead of an plain int array. (Code is untested.)
(For comparison, I'll write the same code with DeckOfCards as an ArrayList<Integer>.)
DeckOfCards = new ArrayList<>();
for (int i = 0; i < NumberOfPairs; i++) {
DeckOfCards.add( i );
DeckOfCards.add( i );
}
Collections.shuffle( DeckOfCards );
(One more edit: if you are actually building a deck of cards, the usual way to do it is just to assign a List the numbers 0 through 51 (52 values for each card). Then a suit is numbers 0 through 3 (space, heart, diamond, club) like this card / 13 -- that's card divided by 13 and the face of each card is card % 13 where the face value of 10 or less are their own number+1, an ace is 0, and the values of jack, queen and king are 10, 11, and 12.)
The main thought of what you want to do is to get all the numbers inside an array and then suffle them.
Firstly, you must create an array with all the numbers that you want. In your case the numbers that you want are from 0 to NumberOfPairs two times. For example if the NumberOfPairs = 3, then the numbers that you have are (0, 0, 1, 1, 2, 2). Therefore, you got this code:
import java.util.Random;
public class Board {
private int NumberOfCards;
private int NumberOfPairs;
private int[] DeckOfCards;
private int CardsRemaining;
public Board(int NumberOfPairs){
this.NumberOfPairs = NumberOfPairs;
this.NumberOfCards = NumberOfCards*2;
this.CardsRemaining = CardsRemaining;
DeckOfCards = new int [2*NumberOfPairs];
Random numbers = new Random();
for (int i = 0; i < NumberOfCards; i++) {
for (int j = 0; j < 1; j++) {
DeckOfCards[i] = i;
}
}
}
}
And finally, you must suffle the numbers. To suffle the numbers, you have to
switch every current position of the array with a random one. So, for this step your code is something like this:
import java.util.Random;
public class Board {
private int NumberOfCards;
private int NumberOfPairs;
private int[] DeckOfCards;
private int CardsRemaining;
public Board(int NumberOfPairs){
this.NumberOfPairs = NumberOfPairs;
this.NumberOfCards = NumberOfPairs*2;
this.CardsRemaining = CardsRemaining;
DeckOfCards = new int [2*NumberOfPairs];
private int temp;
private int randomPos;
Random numbers = new Random();
for (int i = 0; i < NumberOfCards; i++) {
for (int j = 0; j < 1; j++) {
DeckOfCards[i] = i;
}
}
for (int i = 0; i < NumberOfCards; i++) {
randomPos = random.nextInt(NumberOfCards);
temp = DeckOfCards[i];
DeckOfCards[i] = DeckOfCards[randomPos];
DeckOfCards[randomPos] = DeckOfCards[temp];
}
}
}
And you are done. I hope that I helped you.
I think that it supposed to be posted with entire codes in this time.
When I'm trying to get values from Scanner into array named "score",
the second for statement shows unexpected outcomes.
import java.util.Scanner;
public class B1546 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int N = input.nextInt();
int[] score = new int[N];
Max scoreMax = new Max();
double sum = 0;
for (int i=0; i<N; i++) {
score[i] = input.nextInt();
}
for (int i=0; i<N; i++) {
System.out.println(score[i]); // this show the problems
sum = sum + ((double) score[i] / scoreMax.max(score) * 100);
}
System.out.println(sum / N);
}
}
class Max {
int max (int[] score) {
int[] tmpArray;
tmpArray = score;
for( int i=0; i<score.length-1; i++) {
for( int j=i+1; j<score.length; j++) {
if (tmpArray[i]<tmpArray[j]) {
int tmp = tmpArray[i];
tmpArray[i] = tmpArray[j];
tmpArray[j] = tmp;
}
}
}
return tmpArray[0];
}
}
For example, when I type
3
10 20 30
then It comes
10
20
10
...
not
10
20
30
...
I don't know what is the problem.
Your Max.max method changes the array - the 3 lines starting with int tmp =.
Likely the source of your problems is not understanding reference types. tmpArray = score does not make a separate copy of the array score -- you just have two references to the same array. This concept is fundamental to Java programming.
int max (int[] score) {
int[] tmpArray;
tmpArray = score;
}
score is a reference to the array object. Here you create a new reference to the existed array. To fix it, jut make a new array object:
int max(int[] score) {
int[] tmpArray = Arrays.copyOf(score, score.length);
}
int[] are objects and therefore are passed-by-reference in Java. When you do the following in your Max#max(int[]) method:
int[] tmpArray;
tmpArray = score;
Both tmpArray and score will hold the same reference, so when you swap values in the tmpArray, the score-array will be modified as well.
You'll have to create a new integer-array instead for the tmpArray, and copy the values. The simplest would be one of the following two:
int[] tmpArray = score.clone();
// or:
int[] tmpArray = Arrays.copyOf(score, score.length);
I would suggest the second, the .clone() is normally used for other purposes.
Try it online.
Score Finder (100 Marks)
Praveen is finding a job as a Computer Science teacher in school.
He has been rejected many times by different schools but this time he is determined to get the job.
He goes to the principal of the school St. Mary.
The principal says that in his school there is Grading and Credit system.
There are N subjects and each subject has a credit Ci attached to it (1 <= i <= N).
Each student gets a particular grade in each subject and each grade has a point value which are:
A = 10,
A(minus) = 9,
B = 8,
B(minus) = 7,
C = 6,
C(minus) = 5
Now if there are 3 subjects of credits 4, 3 and 2 respectively and a particular student scores A(minus),
B and C in these 3 subjects respectively then his score would be calculated as follows:
Total Score=Summation of product of Grade point and corresponding credit for each subject.
= ( (9*4) + (3*8) + (2*6) ) = 72.
He wants Praveen to tell total distinct Scores that are possible
to be given to a student given credits of N subjects by assigning different grades to each subject.
Input Format
Your function contains a single argument- a one-dimensional Integer Array A of N elements where each represents Credit of that subject.
The first line of input contains an Integer N denoting the size of the array.
Next N lines of input each containing an Integer denoting the credit Ci of ith subject
Constraints
1 <= N <= 100
1 <= Ci <= 5
Output Format
You must return a single integer denoting the total number of scores that are possible to be given.
Sample TestCase 1
Input
2
1
2
Output
16
now I am writing code like this
package javaapplication1;
import java.util.Scanner;
public class CandidateCode {
private static void possibleCombination(int input) {
int i=0;
int[] a=new int[Grades.length];
a[i]=input;
System.out.println("the a is "+a[i]);
}
private static final int[] Grades = new int[]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
public static void main(String[] args) {
int i=0,j,totalSummation=0;
Scanner uInput = new Scanner(System.in);
System.out.println("Enter length of Array:");
int index = uInput.nextInt();
int[] Credit = new int[index];
for (i = 0; i <= Credit.length-1; i++) {
Credit[i] = uInput.nextInt();
System.out.println("credit is" + Credit[i]);
for ( j = 0; j <= Grades.length - 1; j++) {
totalSummation = +(Grades[j] * Credit[i]);
possibleCombination(totalSummation);
// System.out.println("total sum is " + totalSummation);
}
}
}
}
Now I want to store the values calculated in each iteration...
Meaning for
iteration first the values are 10,9,8,7,6,5,4,3,2,1
itertion second the values are 20,18,16,14,10,8,6,4,2
i want to sum each value of 1st iteration with all the values of 2nd iteration.
i,e 10+20, 10+18, 10+16, 10+14, 10+10, 10+8, 10+6, 10+4, 10+2
similarly for 9,8,7,6,5,4,3,2,1
To achieve this I need to store the values per iteration but I am stuck here, please guys help me to get rid of this problem thank you in advance.
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class Sample {
public static void main(String args[] ) throws Exception {
Scanner scan = new Scanner(System.in);
int nValue = scan.nextInt();
if(nValue<1 || nValue>100){
System.out.println("Array Value cannot be less than 1 or greater than 100");
}
int[] inputCredits = new int[nValue];
for( int i=0 ; i < nValue ; i++){
inputCredits[i]=scan.nextInt();
if(inputCredits[i]<1 || inputCredits[i]>5){
System.out.println("Credit Value cannot be less than 1 or greater than 5");
}
}
List<Integer> list1 = Arrays.stream(inputCredits).boxed().collect(Collectors.toList());
List<Integer> list2 = Arrays.asList(5,6,7,8,9,10);
//checked for basic constraints up till this point
//Next what we multiply all the inputted Credits with the possible grades and
// store in the list where x input Credits will produce a list of x*6 entries
// where first six entries are the possibilities for the first Credit, next 6
// entries for the 2nd credit and so on, having this knowledge we loop through // the list to get all the possible scores
List<Integer> permutedList = list1.stream().flatMap(i -> list2.stream().map(j -> i*j)).collect(Collectors.toList());
List<Integer> listForDistinctSet= new ArrayList<Integer>();
for(int i=0; i<6 ; i++){
listForDistinctSet.add(permutedList.get(i));
}
Set<Integer> distinctSet = new HashSet<Integer>();
for(int j=6,k=j+6;k<=permutedList.size();j=k,k=k+6){
Set<Integer> newSet = new HashSet<Integer>();
for(int i=0; i<listForDistinctSet.size(); i++){
for(; j<k ; j++){
int sum = listForDistinctSet.get(i) + permutedList.get(j);
newSet.add(sum);
}
j=k-6;
}
distinctSet=newSet;
listForDistinctSet = new ArrayList<>(distinctSet);
}
System.out.println(distinctSet.size());
}
}
If you don't want to store in a multi-dimensional array then you need to store each iteration in single dimensional array as below. But this code will work only for two credits.
public class CandidateCode {
private static int possibleCombination(int input)
{ int i=0;
int[] a=new int[Grades.length];
a[i]=input;
return a[i];
}
private static final int[] Grades = new int[]{10, 9, 8, 7, 6, 5, 4,
3, 2, 1};
public static void main(String[] args) {
int i=0,j,totalSummation=0;
Scanner uInput = new Scanner(System.in);
System.out.println("Enter length of Array:");
int index = uInput.nextInt();
int[] Credit = new int[index];
int[] creditarr = new int[10];
int[] credit1 = new int[10];
int[] credit2 = new int[10];
for (i = 0; i <= Credit.length-1; i++) {
Credit[i] = uInput.nextInt();
System.out.println("credit is" + Credit[i]);
for ( j = 0; j <= Grades.length - 1; j++) {
totalSummation = +(Grades[j] * Credit[i]);
creditarr[j]=possibleCombination(totalSummation);
if(Credit[i]==1) {
credit1[j]=creditarr[j];
}
if(Credit[i]==2){
credit2[j]=creditarr[j];
}
}
}
for(int k=0;k<credit1.length;k++) {
for(int l=0;l<credit2.length;l++) {
int final_no=credit1[k]+credit2[l];
System.out.println("final_no :" +final_no);
}
}
}
}
Is this what you want?
I guess the below code would be the best solution.This code will work for the no of credits you mention.
public class Candidate {
private static final int[] Grades = new int[]{10, 9, 8, 7, 6, 5};
public static void main(String[] args) {
// TODO Auto-generated method stub
int i=0,score=0,totalsummation=0;
Scanner uInput = new Scanner(System.in);
System.out.println("Enter length of Array:");
int arraylength = uInput.nextInt();
int[] credits= new int[arraylength];
ArrayList<Integer> combination = new ArrayList<Integer>();
for (i = 0; i <credits.length; i++) {
credits[i] = uInput.nextInt();
}
switch(credits.length) {
case 1:
for(int c1=10;c1>=5;c1--) {
totalsummation = c1*credits[0];
combination.add(totalsummation);
}
break;
case 2:
for(int g:Grades) {
for(int c2=10;c2>=5;c2--) {
totalsummation=g*credits[0]+c2*credits[1];
combination.add(totalsummation);
}
}
break;
case 3:
for(int g:Grades) {
for(int c3=10;c3>=5;c3--) {
totalsummation=g*credits[0]+c3*credits[1]+c3*credits[2];
combination.add(totalsummation);
}
}
break;
case 4:
for(int g:Grades) {
for(int c4=10;c4>=5;c4--) {
totalsummation=g*credits[0]+c4*credits[1]+c4*credits[2]+c4*credits[3];
combination.add(totalsummation);
}
}
break;
case 5:
for(int g:Grades) {
for(int c5=10;c5>=5;c5--) {
totalsummation=g*credits[0]+c5*credits[1]+c5*credits[2]+c5*credits[3]+c5*credits[4];
combination.add(totalsummation);
}
}
break;
default:
System.out.println("Invalid Input");
}
ArrayList<Integer> distinctnos =(ArrayList<Integer>) combination.stream().distinct().collect(Collectors.toList());
System.out.println(distinctnos.size()); }
}
Hope this answers your question.
Ok, following our discussion in comments: you don't need two for loops.
for i = 0; i < array.size(); i++ {
sum += grade[i]*credit[i]
}
Sorry for the generic coding style. Is it what you want?
I need to create random numbers that will run through an array without duplicates.
The problem is the duplication and I can't use any of the utils except the Scanner for input (teacher instruction) like java.util.Random or java.util.ArrayList.
I use a function called random that my teacher wrote to us and the function newNum(int num) is where I need what I have asked - random numbers.
package exercise;
import java.util.Scanner;
public class Bingo {
static int size = 10;
static int num;
static int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
private static Scanner sc;
public static void main(String[] args) {
System.out.print("Press Enter to start: ");
sc = new Scanner(System.in);
sc.nextLine();
System.out.println("");
// int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// int[] tempArray = arr;
int num = random();
// int num = sc.nextInt();
// System.out.println(num);
while (size > 0) {
System.out.println(num);
size--;
newArray(num);
num = random();
newNum(num);
// System.out.println(num);
}
}
public static int random() {
int max = 10;
double r = Math.random();
int num = (int) (r * max + 1);
return num;
}
public static int newNum(int num) {
// Here should go the code for the function for getting only new
// random number without duplications
return num;
}
public static int newArray(int num) {
int[] tempArray = arr;
arr = new int[size];
int x = num - 1;
for (int i = 0; i < x; i++) {
if (i < size) {
arr[i] = tempArray[i];
}
}
for (int i = num; i < size; i++) {
if (i < size) {
int y = i - 1;
arr[y] = tempArray[i];
} else {
int a = size - 1;
arr[a] = tempArray[size];
}
}
return num;
}
}
First of all, you write that you can't use shuffle, but that doesn't mean that you are prohibited from implementing it. It's not that hard, actually.
If you want to do that, use the Fisher-Yates shuffle, as found on wikipedia: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
(by the way, since you are going to school, if you find such a wikipedia article - or any other article - to be interesting, you might propose to your teacher to hold an essay on that, easily earned additional good grade)
Of course, this assumes that you have a vector to shuffle, which is inefficient for large vectors ("random numbers within zero to one billion"). In this case you might want to go with:
To find n random numbers within 0..m
1. Initialize an empty list of already used random numbers which is ordered, called "numbers"
2. for i = 0..n-1
2a: r = random(0..m-i) (uniform distribution)
2b: for every entry in numbers
if entry <= r, r++
2c: sort r into numbers (maybe by using a single bubblesort step)
This shifts the complexity from the size of the vector as before to the amount of generated numbers.
Explanation: In every iteration, we want to find an unused number. We find the rth unused number (there is a range of 0..m-i of unused numbers in iteration i). Now we only need to find out which number is the rth unused one. This is done by the inner iteration. We need numbers to be sorted because of this example: current state: numbers = {5, 1}, r = 4. r < 5 -> do nothing. r >= 1 -> r++. End up with r = 5, got a double entry.
If sorting is not wanted for the resulting list, simply go with two lists.
I recently made a very simple practice program in Python, that takes user input and rolls dice. The code is:
import random
import sys
import math
def roll(rolls, sides, results):
for rolls in range(1, rolls + 1):
result = random.randrange(1, sides + 1)
print result
results.append(result)
def countf(rolls, sides, results):
i = 1
print "There were", rolls, "rolls."
for sides in range(1, sides + 1):
if results.count(i) != 1:
print "There were", results.count(i), i,"s."
else:
print "There was", results.count(i), i
i = i + 1
if i == sides:
break
rolls = input("How many rolls? ")
sides = input("How many sides of the die? ")
results = []
roll(rolls, sides, results)
countf(rolls, sides, results)
(actually this is part of a larger program, so I had to cut'n'paste bits, and I might have missed something out).
And so I decided to translate that to Java. Notice the algorithm here: get random number, print it, append it to an array, then count the amount of each number in the array at the end, and print out that value. Problem is, I don't know how to do the equivalent of someArray.count(someIndex) in Java syntax. So my Java program looks like this so far:
import java.util.*;
public class Dice {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random();
int[] results = new int[TIMES_TO_ROLL];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt(6);
System.out.println(result);
results[i] = result;
}
}
public static int getInt(String prompt) {
System.out.print(prompt + " ");
int integer = input.nextInt();
input.nextLine();
return integer;
}
}
So can someone help me with the array counting code? I understand that this might not be a defined method, since Python is higher level after all, so I could make my own array counting method, but I was wondering if Java, like Python, has a predefined one.
EDIT: I managed something like this:
public static int arrayCount(int[] array, int item) {
int amt = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == item) {
amt++;
}
else {
amt = amt;
}
}
return amt;
}
EDIT: Just out of interest, assuming I use Command prompt to run my Java program and Python.exe (command prompt console for Python), which one will be faster (in other words, for the same code, which language has better performance?)?
You could use a HashMap to store the result.
If the new number is not in your map you add it with "1" as initial value.
If it exists your put "+1" to the current map value.
To display the values you just have to iterate on you entries in a for each loop.
The solution is to transform your array to a List and then use the Collections.frequency method:
List<Integer> resultList = Arrays.asList(results);
int freq = Collections.frequency(resultList, 4);
Also you could use ArrayList from the very beginning saving you the transformation:
List<Integer> result = new ArrayList<Integer>();
// add results
int freq = Collections.frequency(result, 4);
See the Collections documentation here
EDIT: If performance is an issue (as suggested in the comments) then maybe you want to use each index of the array as a counter, as follows:
Random flip = new Random(SIDES);
int[] counters = new int[SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
counters[result] = counters[result]+1;
}
Notice that you no longer need to count at the end since you've already got all the counters in the array and there is no overhead of calculating the hash.
There are a couple libraries that will do this for you:
Google Guava's MultiSet
Apache Common's Bag
But for something so simple, you may consider an extra library a bit excessive.
You can also do this yourself with an int[]. Assuming your dice is using whole numbers, have the number rolled refer to the index into the array, and then increment the value at that index. When you need to retrieve the value for a given number, look up its value by the index.
private static final int NUMBER_DICE_SIDES = 6;
public static void main(String[] args) {
final static int TIMES_TO_ROLL = getInt("Times to roll?");
Random flip = new Random(NUMBER_DICE_SIDES);
int[] results = new int[NUMBER_DICE_SIDES];
for (int i = 0; i < TIMES_TO_ROLL; i++) {
int result = flip.nextInt;
System.out.println(result);
results[result]++;
}
for(int i = 0; i < NUMBER_DICE_SIDES; ++i) {
System.out.println((i+1)+"'s: " + arraysCount(results, i));
}
}
public static int arrayCount(int[] array, int item) {
return array[item];
}
There's a frequency method in collections
int occurrences = Collections.frequency(listObject, searchItem);
Java doc for collections
As far as I am aware, there is no defined method to return the frequency of a particular element in an array. If you were to write a custom method, it would simply be a matter of iterating through the array, checking each value, and if the value matches the element you're after, incrementing a counter.
So something like:
// in this example, we assume myArray is an array of ints
private int count( int[] myArray, int targetValue) {
int counter = 0;
for (int i = 0 ; i < myArray.length; i++ ) {
if (myArray[i] == targetValue) {
counter++;
}
}
return counter;
}
Of course, if you want to find the frequency of all the unique values in your array, this has the potential of being extremely inefficient.
Also, why are you using a 7-sided die? The Random nextInt() will return a number from 0 up to but not including the max. So your die will return values from 0 through 6. For a six-sided die, you'd want a new Random(6); and then increment your roll by one to get a value from one through six: flip.nextInt() +1;.
class FindOccurrence {
public static void main (String[]args) {
int myArray[] = {5, 8, 5, 12, 19, 5, 6, 7, 100, 5, 45, 6, 5, 5, 5};
int numToFind = 5;
int numberOfOccurrence = 0;
for (int i=0; i < myArray.length; i++) {
if (numToFind == myArray[i]) {
numberOfOccurrence++;
}
}
System.out.println("Our number: " + numToFind);
System.out.println("Number of times it appears: " + numberOfOccurrence);
}
}