Array not returning strings - java

This is assessed work so please don't give the answer, just advice!
I'm trying to get my program to return the strings pass, compensation pass or fail depending on the values inputted by the user. However, it's not returning the values and I'm receiving an error for 'weighting'. Earlier it was working, however not in a suitable way because it wouldn't always return the correct before results. I added the array because i think that's what is needed, but now I'm just getting an error. Cheers.
enter code here
public class MarkCalculator {
static int[] marks = new int[12];
static int[] weighing = new int[6];
// public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int weighting;
int coursework;
int exammark;
for (int i = 0; i < marks.length / 2; i++) {
System.out.println("Please enter course work weighting");
weighting = kb.nextInt();
weighing[i] = weighting;
}
for (int i = 0; i < marks.length / 2; i++) {
System.out.println("Please enter course work mark ");
coursework = kb.nextInt();
marks[i] = coursework;
}
for (int i = 0; i < marks.length / 2; i++) {
System.out.println("Please enter exam mark ");
exammark = kb.nextInt();
marks[i + 6] = exammark;
}
System.out.println("Calculating Marks");
MarkCalculator mc = new MarkCalculator();
String[] results = mc.computeMarks(marks, weighing);
for (String result : results) {
System.out.println("Results are " + result);
}
}
public String[] computeMarks(int[] marks, int[] weighing) {
int[] formula = new int[12];
String[] results = new String[weighing.length];
for (int i = 0; i < weighing.length; i++) {
int exam = marks[i];
int cw = marks[i+weighing.length];
int weight = weighing[i];
formula [i]= ((cw + weight) + (exam * (100 - weight)) / 100);
if ((formula[i]<=39) && (formula[i] > 35)) {
results[i] = "COMPENSATION PASS";}
else if (formula[i] >= 40) {
results[i] = "PASS";
}
else {
results[i] = "FAIL";
}
}
return results;
}
public static void computeResult (int[] coursework, int[] exammark)
{
computeResult(coursework,exammark);
}
}

Was posted as comment:
You could separate the marks into two arrays which will be easier to debug? Also it seems like you might be going over the array index for weightings on this line
for (int i = 0; i < marks.length;i++)
{
int exam = marks[i];
int cw = marks[i];
int weight = weighing[i]; // Error is here
//...
}
Because "weighing" has a range 0-5 and you are cycling through to 0-11 (with the marks array)

weighting and marks are different length arrays, yet you are doing the loop
for (int i = 0; i < marks.length; i++)
which will go out of bounds for weighting when i > 5.
It looks like you need to do something like this:
for (int i = 0; i < weighting.length; i++) {
int cw = marks[i];
int exam = marks[i+weighting.length];
int weight = weighing[i];
But that will depend on how you are storing the marks for the cw and exam in the marks array. I would recommend creating separate arrays for cw and exam as these are different items and will make things a lot easier to read and debug for yourself.

As you've asked for tips to improve your program as well, without specific code, then I would consider doing the following:
1) Have separate arrays for exam and cw marks. You're making it hard for yourself to debug your program by concatenating them together and this is also the source of your error.
2) Assuming that you always have the same number of exams as you do cw elements then I would consider having a class variable in MarkCalculator that stores the number of tests. Something like this:
private static int NUM_TESTS.
This way you can initialise arrays like this:
private static int[] examMarks = new int[NUM_TESTS]
and you can do the looping in computeMarks like this:
for (int i = 0; i < NUM_TESTS; i++)
This way if you decide you want more tests you only have to update the code in one place. It would also be easy to change your program so that the user could define how many tests should be calculated.
3) Where you have:
weighting = kb.nextInt();
weightings[i] = weighting;
replace it with:
weightings[i] = kb.nextInt();
as the variable weighting only seem to be used in this place and is therefore unnecessary. This will result in fewer operations the program has to perform and reduces the amount of code on the screen. In practice the compiler will likely remove this redundant variable, but it is good practice to think about how many operations you are performing and which of them aren't necessary.
4) It's better practice to explicitly set access modifiers on fields in a class. So you should have:
'private static int[] weightings = new int[NUM_TESTS];`
If you want to access it from another class you would then typically specify a getter method like so:
public int[] getWeightings() { return weightings; }
5) This is less important, but I would move main to the bottom of the class. In Java it's more typical to see the classes fields first, then the constructor, then public methods, then private methods and have the main at the bottom. In large projects it helps keeping to good style as it makes the code easier to read and understand.
These reference might help you learn more:
Java Coding Style Guide
Oracle Tutorial on access-modifiers

You will encounter an error as "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6"
This is because in method computeMarks. The length of marks (int[]) is 12.
and you just declare a variable with length 6 to handle:
int[] formula = new int[6];
when variable i in for loop reaches 6. The following code will throw out an error.
formula [i]= ((cw + weight) + (exam * (100 - weight)) / 100);
Have a try to declare it with length of 12.
int[] formula = new int[12];
Just paste code for method computeMarks.
public String[] computeMarks(int[] marks, int[] weighing) {
int[] formula = new int[12];
String[] results = new String[weighing.length];
StringBuilder sb = new StringBuilder();
for (int i = 0; i < weighing.length; i++) {
sb.setLength(0);
int exam = marks[i];
int cw = marks[i + weighing.length];
int weight = weighing[i];
formula[i] = ((cw + weight) + (exam * (100 - weight)) / 100);
if ((formula[i] <= 39) && (formula[i] > 35)) {
sb.append("COMPENSATION PASS");
} else if (formula[i] >= 40) {
sb.append("PASS");
} else {
sb.append("FAIL");
}
sb.append(" cw mark is ").append(cw).append(" and exam mark is ")
.append(exam);
results[i] = sb.toString();
}
return results;
}

Related

Random numbers in an array without duplicates

I know this question has been answered out there, but those solutions don't fit in with the way I'm going about, so I'm enquiring to see if there is a simpler solution.
I'm using the set interface and I need there to be 6 random numbers and you can't have duplicates in the set interface.
This is what I've currently got, the way I I'm doing it is not ideal and often causes crashes.
public void drawLotto(){ //The validation I have here I know isn't the most effective way and is-
Random r = new Random();//resource comsuning but this was the only way I could think of doing it.
int draw[] = new int[6];
int min = 1;
for(int i = 0; i < draw.length; i++){
draw[i] = r.nextInt(lotteryMax-min) + min;
lotteryDraw.add(draw[i]);
}
int size = lotteryDraw.size();
if(size != 6){
drawLotto();
}
for(int i = 0; i < draw.length; i++){
System.out.println(draw[i] + " ,");
}
System.out.println();
}
``
Thank you, any help is appreciated.
The reason you have problems is because you recursively call drawLotto(), which will in turn create a new instance of the Random. If drawLotto() cannot create a correct list, it will have to do a full retry of all 6 numbers. This might cause your application to use a high amount of memory, resulting in the crash you experience
One way you could do this is by keep looping until you find 6 unique numbers:
public void drawLotto(){
Random r = new Random();
Set<Integer> draw = new HashSet<>();
int min = 1;
int lotteryMax = 50;
while(draw.size() < 6){
draw.add(r.nextInt(lotteryMax-min) + min);
}
String lotteryDrawing = draw.stream().map(String::valueOf).collect(Collectors.joining(" ,"));
System.out.println(lotteryDrawing);
}
Though you have to make sure that your lotteryMax is higher than the number you need
check this out
public void drawLotto(){
Random random = new Random();
while(lotteryDraw.size()<6) {
lotteryDraw.add(random.nextInt(max-min)+min);
}
lotteryDraw.forEach(System.out::println);
}
Use a set if you want to avoid duplicate values.
Example:
public static Set <Integer> drawLotto() { //The validation I have here I know isn't the most effective way and is-
Random r = new Random(); //resource comsuning but this was the only way I could think of doing it.
int draw[] = new int[6];
int min = 1;
int lotteryMax = 10;
Set<Integer> lotteryDraw = new HashSet<Integer>();
for (int i = 0; i < draw.length; i++) {
draw[i] = r.nextInt(lotteryMax - min) + min;
lotteryDraw.add(draw[i]);
}
int size = lotteryDraw.size();
if (size != 6) {
return drawLotto();
} else {
return lotteryDraw;
}
}

Program starts misbehaving after a certain threshold

I have a homework task as follows:
The bin packing problem is to pack the objects of
various weights into containers. Assume each
container can hold a maximum of 10 pounds. The
program uses an algorithm that places an object into
the first bin in which it would fit. Your program should
prompt the user to enter the total number of objects
and the weight of each object. The program displays
the total number of containers needed to pack the
objects and the content of each container. Here is a
simple run of the program:
Enter the number of objects: 6
Enter the weight of the objects: 7 5 2 3 5 8
Container 1 contains objects with weight: 7 2
Container 2 contains objects with weight: 5 3
Container 3 contains objects with weight: 5
Container 4 contains objects with weight: 8
Now I have decided to try making it smarter and optimize the object allocation. It seemed to be working fine, but when I started testing using more numbers than the sample run I noticed that the highest I can go is 27 objects. Anything higher and I start getting a few containers at the end of the execution that could be merged into a single one. Any ideas and suggestions are welcome. Thank you in advance!
package classwork;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.Scanner;
public class BinPacking {
private static final int binLimit = 10;
public static boolean lessThanLimit(int a, int b) {
if (a + b < binLimit) {
return true;
} else {
return false;
}
}
public static boolean perfectFit(int a, int b) {
if (a + b == binLimit) {
return true;
} else {
return false;
}
}
public static boolean weightsLeft(boolean[] a) { // check if there is one more item that has not been binned yet.
for (boolean b : a) {
if (b) {
return true;
}
}
return false;
}
public static ArrayList<int[]> distributeObjects(int[] weights) {
int counter = 0;
boolean[] objectAssigned = new boolean[weights.length]; // array to track which objects have been assigned already
ArrayList<int[]> result = new ArrayList<int[]>(); // list of int[] to be returned
for (int i = 0; i < weights.length; i++) {
ArrayList<Integer> currentBin = new ArrayList<Integer>(); // list to store the values of the weights in currrent bin
int currentBinWeight = 6;
if (!objectAssigned[i]) {
currentBin.add(weights[i]);
currentBinWeight = weights[i];
objectAssigned[i] = true;
} else
counter = 1;
stupidLoopThatWontBreak:
while (currentBinWeight < binLimit && counter < 1) {
counter = 1;
if (!weightsLeft(objectAssigned)) { // break loop if no more weights left
result.add(currentBin.stream().mapToInt(Integer::intValue).toArray());
break stupidLoopThatWontBreak;
}
for (int j = i + 1; j < weights.length; j++) {
if (perfectFit(currentBinWeight, weights[j]) && !objectAssigned[j]) {
currentBin.add(weights[j]);
currentBinWeight += weights[j];
objectAssigned[j] = true;
break stupidLoopThatWontBreak;
}
if (lessThanLimit(currentBinWeight, weights[j]) && !objectAssigned[j]) {
currentBinWeight += weights[j];
currentBin.add(weights[j]);
objectAssigned[j] = true;
}
}
}
// convert arraylist to int[] and add it to result. Java 8+ feature
if (!currentBin.isEmpty()) {
result.add(currentBin.stream().mapToInt(Integer::intValue).toArray());
counter = 0;
}
}
return result;
}
public static void main(String[] args) {
System.err.println("Container weight limit is " + binLimit);
Scanner in = new Scanner(System.in);
//Test numbers 7, 5, 3, 2, 5, 8
// System.out.print("Enter the weights of the objects you want to put into the bins: ");
// String input = in.nextLine();
// in.close();
//========================Random numbers for testing======================
String input = "";
Random ran = new Random();
System.out.print("Enter number of weights to be randomly generated: ");
int num = in.nextInt();
in.close();
for (int i = 0; i < num; i++) {
input += (ran.nextInt(binLimit) + 1) + " "; //+1 to not have zeroes
}
//========================End of random numbers===========================
ArrayList<Integer> list = new ArrayList<Integer>();
String[] str = input.trim().split(" "); // trim surrounding spaces, use space char as separator
for (String a : str) {
list.add(Integer.valueOf(a));
}
// sort the list in a descending order
Collections.sort(list);
Collections.reverse(list); // this could be avoided if I started checking from the last index in distributeObjects()
System.out.println("The generated and sorted descendingly weights are:");
System.out.println("\n" + list.toString() + "\n");
int[] weights = new int[list.size()];
for (int a = 0; a < weights.length; a++) {
weights[a] = list.get(a);
}
ArrayList<int[]> bins = distributeObjects(weights);
for (int i = 0; i < bins.size(); i++) {
System.out.println("Container " + (i + 1) + " contains objects with weight: " + Arrays.toString(bins.get(i)));
}
}
}
Since I cannot comment, I am posing this as an answer -
Run above code with "10 9 8 8 8 7 7 7 6 6 6 5 5 5 4 4 4 4 4 3 3 2 2 2 2 2 2 2 1 1" as input array and you will see the problem being caused by 'counter' variable. If you replace 'counter=1;' from else with 'continue;' it should work for this input. You still need to test this for other inputs. Also, the above code needs refactoring - for example - use either list or weights. Both are nor required.
I tried not to distort your code too much, but this should give you your desired output. The problem was with your second loop, it caused some trouble with the counter variable since counter was never set back to 0 at the end of your loop if the bin should not already be added (when you did not find the first weight that has to be added to the bin).
The easiest way to fix your program is simply to move counter = 0; inside the if statement where you check if there is already a weight inside of the bin or not outside of the if block.
I removed the "stupidLoopThatWouldNotBreak" below and replaced it with another for loop, that looks through all remaining weights if there is one that can fit.
public static ArrayList<int[]> distributeObjects(int[] weights) {
boolean[] objectAssigned = new boolean[weights.length]; // array to track which objects have been assigned already
ArrayList<int[]> result = new ArrayList<int[]>(); // list of int[] to be returned
for (int i = 0; i < weights.length; i++) {
ArrayList<Integer> currentBin = new ArrayList<Integer>(); // list to store the values of the weights in currrent bin
int currentBinWeight = 0;
//This loop searches for the first unused Weight, so you do not need `count` anymore
for (int j = i; j < weights.length; j++) {
if (!objectAssigned[j]) {
currentBin.add(weights[j]);
currentBinWeight = weights[j];
objectAssigned[j] = true;
break;
}
i = j; //You can skip all iterations with used weights
}
for (int j = i; j < weights.length && currentBinWeight < binLimit; j++) {
if (perfectFit(currentBinWeight, weights[j]) && !objectAssigned[j]) {
currentBin.add(weights[j]);
currentBinWeight += weights[j];
objectAssigned[j] = true;
break; //this break gives some performance bonus
}
if (lessThanLimit(currentBinWeight, weights[j]) && !objectAssigned[j]) {
currentBinWeight += weights[j];
currentBin.add(weights[j]);
objectAssigned[j] = true;
}
}
// convert arraylist to int[] and add it to result. Java 8+ feature
if (!currentBin.isEmpty()) {
result.add(currentBin.stream().mapToInt(Integer::intValue).toArray());
}
}
return result;
}
You can further enhance your code if you split this loop up. You can add more functions like the two helperfunctions perfectFit and lessThanlimit. You can for example add another function that will search for the first empty element, maybe even add it to the bin. Also the 2 functions you already have could be merged into one function called addWeight or attemptAdd. Furthermore you could create seperate classes for the bin and for the weights.

Checking if the graph exist (java)

Determine whether there exists a graph with a sequence of degrees of vertices (s = s1, s2...sn).
What is the best and most optimized algorithm for solving this problem.
Input:
the first line contains `t<100` - amount of sequnces.
the second line contains value `n <= 1000000`(length of a sequence).
the third line contains contains `n` non-negative integer numbers. And so on.
Output:
if the graph can exist print "yes" otherwise print "no".
For example:
Input:
3
5
1 2 3 2 1
4
3 3 2 2
3
1 3 2
Output:
No
Yes
Yes
The maximum execution time should be 0.4 second.
Here is my code (If the number of odd vertices is even, then the graph exists):
import java.util.Scanner;
public class Main {
public static final Scanner in = new Scanner(System.in);
public static void isGraph (int []a, int n) {
int k=0;
for(int i=0; i< n; i++) {
if(a[i] %2 != 0) {
k++;
}
}
if(k%2 == 0)
System.out.println("Yes");
else
System.out.println("No");
}
public static void main(String[] args) throws Exception{
double t1 = System.nanoTime();
int n;
int []a;
int t = Integer.parseInt(in.nextLine());
while(t-- > 0) {
n = in.nextInt();
a = new int[n];
for(int i=0; i<n; i++)
a[i] = in.nextInt();
isGraph(a,n);
}
System.out.println(System.nanoTime() - t1);
}
}
But the execution time of this program is more than 0.4 second. I get run time exceeded. How I can optimize code and speed up runtime. May be there is another algorithm to solve this task, please help me.
I think I have a faster way for you. Please verify this. If you are concerned about the final outcome of even/odd, then there seems to be no reason to keep track of the k counter. You can keep a dynamic value of whether the running sequence is even or odd:
public static void isGraph (int []a, int n) {
int k = 0;
for(int i=0; i< n; i++) {
k += a[i] & 1;
}
if(k%2 == 0)
System.out.println("Yes");
else
System.out.println("No");
}
This might help your reading: I have no experience with it however, I got it from a competition website:
Slow way to read:
/** Read count integers using Scanner */
static int scanInteger(int count) {
Scanner scanner = new Scanner(input);
int last = 0;
while (count-- > 0) {
last = scanner.nextInt();
}
return last;
}
Faster way:
static int readIntegers(int count)
throws IOException {
BufferedReader reader = new BufferedReader(
new InputStreamReader(input) );
StringTokenizer tokenizer = new StringTokenizer("");
int last = 0;
while (count-- > 0) {
if (! tokenizer.hasMoreTokens() ) {
tokenizer = new StringTokenizer(reader.readLine());
}
last = Integer.parseInt(tokenizer.nextToken());
}
return last;
}
EDIT: to show how to avoid two phases where Phase 1 is the read loop, and Phase 2 is the algorithm:
public static void main(String[] args) throws Exception{
double t1 = System.nanoTime();
int n;
// int []a; // Not necessary
int t = Integer.parseInt(in.nextLine());
while(t-- > 0) {
n = in.nextInt();
// a = new int[n]; // Not necessary
int k = 0;
int a;
for(int i=0; i<n; i++) {
a = in.nextInt();
k += a & 1;
}
// isGraph(a,n); // Not necessary
if(k % 2 == 0)
System.out.println("Yes");
else
System.out.println("No");
}
System.out.println(System.nanoTime() - t1);
}
May be there is another algorithm to solve this task
That's not the problem (IMO).
Hint 1: since you know the length of the sequence beforehand, you can create the array and parse the sequence faster than this:
a = Arrays.stream(s.split(" ")).mapToInt(Integer::parseInt).toArray();
(Java 8+ streams are elegant, but they are not the fastest way.)
Hint 2: using Scanner is probably faster than reading strings and parsing them.
Hint 3: you could probably avoid creating an array entirely. (It would be poor coding practice IMO ... but if performance is critical ...)

How to use previous parameter from array in for loop

I have been try to code this, to increment the user input by 33 if the input is "31" or more up to the input or "90", and I have hit a wall where I want to use the user input from the array but I cannot. Could anyone help? Thank you.
if (choice.equals("R")) {
System.out.println("You have selected to draw a Rectangle!");
System.out.println("Please enter the Height and Width of the rectangle that is within 30cm - 90cm: ");
int[] array = new int[2];
int[] array2 = new int[2];
Scanner scan = new Scanner(System.in);
String line1 = scan.nextLine();
String[] numbers1 = line1.split(" ");
for(int i=0;i<numbers1.length;i++){
array[i] = Integer.parseInt(numbers1[i]);
}
I am trying to make a method to be able to easily call upon it later on, but that's the problem as I cannot complete my calculation.
public static void timeTurn (int a, int b) {
for(int i = 1000; i < 3001; i+= 33) {
if(numbers1.equals(>=30)) {
}
}
}
int[] array2 = new int[2]; is useless here.
By the way, please do not name a variable "array" or "array2". It's hard to understand for others and for yourself in the future.
if you defined the "array"s length to 2, then this for loop for(int i=0;i<numbers1.length;i++){...} is meaningless cause you already defined that you can only have two integers in this array.
I do not know the meaning of "convert cm to milliseconds" since one is distance and the other is time...
I can not understand (int a, int b) what "a", "b" means.
by my understanding the second code should be:
public static void timeTurn (int[] length) {
int minMillsecond = 1000;
int maxMillsecond = 3001;
int gap = 33;
for(int len : length){
if (30 <= len <= 90){
len += minMillsecond;
while(len < 3000){ len+=gap;}
print len;
}
}
}

Count how many times an element occurs in an array - Java

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);
}
}

Categories