My code outputs this:
Computer 1 bets 5
Computer 2 bets 8
Computer 3 bets 4
Computer 4 bets 3
Computer 5 bets 8
I want to make a method "displayWinners()" that compares the bet value of all the objects in this array and returns all of the object id's with the highest bet value, in this case it would be Computer 2 and 5 with a bet of 8. How would i do that?
public class Computer {
Computer[] c;
private int id;
private int bet;
public void create(int numComps) {
int i;
c = new Computer[numComps];
for (i = 0; i < numComps; i++) {
c[i] = new Computer();
c[i].id = i+1;
c[i].bet = bet();
c[i].display();
}
displayWinners();
}
public int bet() {
return (int) (Math.random() * 10) + 1;
}
public void display() {
String name = "Computer " + id;
System.out.println(name + " bets " + bet);
}
public void displayWinners() {
System.out.println();
}
public static void main(String[] args) {
Computer c = new Computer();
c.create(5);
}
}
why don't you allocate a variable for an index of the maximum value and a value itself, and keep checking & rewriting the variable as function bet() is executed.
the code below is not properly verified but just have a look over.
public class Computer {
Computer[] c;
private int id;
private int bet;
private List<Integer> maxId;
private int maxBet;
public void create(int numComps) {
int i;
c = new Computer[numComps];
maxId = new ArrayList<Integer>();
maxBet = 0;
for (i = 0; i < numComps; i++) {
c[i] = new Computer();
c[i].id = i+1;
c[i].bet = bet();
c[i].display();
if(c[i].bet > maxBet) {
maxId = new ArrayList<Integer>();
maxId.add(c[i].id);
maxBet = c[i].bet;
}
else if(c[i].bet == maxBet) {
maxId.add(c[i].id);
}
}
displayWinners();
}
public int bet() {
return (int) (Math.random() * 10) + 1;
}
public void display() {
String name = "Computer " + id;
System.out.println(name + " bets " + bet);
}
public void displayWinners() {
System.out.format("Computer %d", maxId.get(0));
if(maxId.size() > 1) {
for(int i=1; i<maxId.size(); i++) {
System.out.format(" and %d", maxId.get(i));
}
}
System.out.format(" with a bet of %d\n", maxBet);
}
public static void main(String[] args) {
Computer c = new Computer();
c.create(5);
}
}
Ok, just for the fun to provide this with a small trick.
You just iterate your array.
Then, I will compare the current bet with the maximum value known using Integer.compare and base on the result, I will either:
r > 0 - clear the list and add the instance to the list
r == 0 - Add the instance to the list
r < 0 - Do nothing
Good to know, the actual value return by the method are simpler [-1, 0, 1], it will matter shortly.
Now, we can see some redondance in adding into the list, to reduce that, we are able to use a switch instead of ifs.
List<Computer> winners = new ArrayList<Computer>();
for ( Computer c : computers ){
int r = Integer.compare(c.getBet(), maxBet);
switch(r){
case 1: //Current bet is higher
maxIds.clear();
maxBet = c.getBet();
case 0: //Current bet is equals
winners.add(c);
case -1: //Current bet is lower (optional line, just for the explanation)
}
}
Since I don't use break, after we clear the list, we will add into it.
Note: A fail-safe should be added in case of Integer.compare implementation changes. The documentation state that it will return any value instead of -1, 0 or 1. But the current implementation is simpler :
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
First of all, I recommend you to split storage and business logic. Move all methods for show Computer class out.
So to find the winners you have to do following steps:
Create a list of computers (you can create an array or a list);
Iterate over the collection once to find the highest bet;
Iterate over the collection second time to filter out all computers with the highest bet.
If you ask such question, then I suppose, that no need of you right now to offer different sorting algorithms or special data structures (they all do the same, but much faster for big input data).
This is one of the possible solutions (I tried to keep it simple):
public class Foo {
public static void main(String[] args) throws IOException {
Computer[] computers = createComputer(5);
int highestBet = getHighestBet(computers);
List<Integer> ids = getIdsWithBet(computers, highestBet);
System.out.println(ids.stream().map(String::valueOf).collect(Collectors.joining(",")));
}
private static int getHighestBet(Computer... computers) {
int max = 0;
for (Computer computer : computers)
max = Math.max(max, computer.getBet());
return max;
}
private static List<Integer> getIdsWithBet(Computer[] computers, int bet) {
List<Integer> ids = new ArrayList<>(computers.length);
for (Computer computer : computers)
if (computer.getBet() == bet)
ids.add(computer.getId());
return ids;
}
// you van use List<Computer>
private static Computer[] createComputer(int total) {
Random random = new Random();
Computer[] computers = new Computer[total];
for (int i = 0; i < computers.length; i++) {
computers[i] = new Computer(i + 1, random.nextInt(10) + 1);
System.out.println(computers[i]);
}
return computers;
}
}
// It's better to use unmodifiable objects if you can
final class Computer {
private final int id;
private final int bet;
public Computer(int id, int bet) {
this.id = id;
this.bet = bet;
}
public int getId() {
return id;
}
public int getBet() {
return bet;
}
#Override
public String toString() {
return "Computer " + id + " bets " + bet;
}
}
import java.util.ArrayList at top of file
```
int maxBet = 0;
ArrayList<Integer> maxIds = new ArrayList<Integer>();
// This is a for each loop, it is saying, for each computer in the list of computers
for ( Computer computer : computers ){
/* if that computer has a higher bet than what we previously thought
was the highest, empty our list and set maxBet to that, and add this
computer to the list of computers that have that bet number */
if (computer.getBet() > maxBet){
maxIds.clear();
maxBet = computer.getBet();
maxIds.add(computer.getId());
// another computer has the same max bet value
} else if ( computer.getBet() == maxBet){
maxIds.add(computer.getId());
}
}
System.out.println("Max Bet: " + maxBet);
System.out.print("Computers with max bet: ");
// for each id in our list of computers that have the max bet
for ( int id : maxIds ){
System.out.print(id + " ");
}
Related
So I refactored a Linear Search code that only uses the main method. My goal is to convert it into an OOP approach. But I have trouble saving the input set of integers.
// LinearSearchDriver.java
import java.util.Scanner;
public class LinearSearchDriver {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
LinearSearch linearSearch = new LinearSearch();
System.out.println("Enter number of elements");
int numElements = in.nextInt();
linearSearch.setNumberOfElements(numElements);
System.out.println("Enter " + numElements + " integers");
for (int count = 0; count < numElements; count++){
int setIntegers = in.nextInt();
linearSearch.setNumberOfIntegers(setIntegers);
}
System.out.println("Enter value to find");
int search = in.nextInt();
linearSearch.findValue(search);
}
}
//LinearSearch.java
public class LinearSearch {
private int c;
private int n;
private int array[];
public void setNumberOfElements(int n) {
this.n = n;
this.array = new int[n];
}
public void setNumberOfIntegers(int y) {
for (c=0; c < n; c++)
array[c] = y;
}
public void findValue(int search) {
for (c = 0; c < n; c++) {
if (array[c] == search) { /* Searching element is present */
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) { /* Searching element is absent */
System.out.println(search + " is not present in array.");
}
}
}
Example output:
But when I input number 1, this is the output:
The program only reads number 2 output which I think, the last number is only the one that is saving to an array.
for (c = 0; c < n; c++) {
array[c] = y;
}
is where things go wrong. You're setting the last value passed to that function for every index in the Array.
You can adress this in several ways:
Pass an Array to the function instead of a single argument.
You can determine the current number of elements in your Array and then append the newest value "manually". See this post.
Or you could simply use a dynamic structure, such as a List and append the element to that.
Here is a rough outline for the 3rd Option:
public class LinearSearch {
private List<Integer> intList;
public LinearSearch() {
}
public void setNumberOfElements(int n) {
intList = new ArrayList<>(n); //Set the capacity here like before.
}
public void setNumberOfIntegers(int y) {
//If you want your List to always only contain the initially allowed number of elements, you could implement
// this logic here, by adding the new value and removing the "oldest" one.
intList.add(y);
}
public void findValue(int search) {
if (!intList.contains(search)) { //You can put this up here and potentially skip the looping.
System.out.println(search + " is not present in array.");
return;
}
for (int n : intList) {
if (n == search) {
System.out.println(search + " is present at location " + intList.indexOf(search) + ".");
return; //Use return to exit the method, break only exits the loop in your example, and you could print both lines.
}
}
}
}
While developing a simple auto generating game of war in my free time, I ran into a "StackOverFlow" error.
Here is my Deck class where the error occurs:
It occurs in my compare() method. Any insight as to what I can do to avoid this error is accepted as I am struggling to understand what can be done to fix this and have little knowledge as to what this error even means besides my class doesn't have recursion done well. Thanks!
import java.util.*;
import java.math.*;
public class Deck
{
private int num = 0;
private int cardnum2 = 0;
private int cardnum = 0;
private int decrease = 0;
private int rnd = 0;
private int winner = 0;
private String suit = " ";
private int suitNum = 0;
private int val = 1;
private String name = "";
private ArrayList<Card> Deck = new ArrayList<Card>();
private Card[] cardCheck = new Card[51];
private ArrayList<Card> play1 = new ArrayList<Card>();
private ArrayList<Card> play2 = new ArrayList<Card>();
public Deck()
{
createDeck();
}
public void createDeck()
{
for(int i = 0; i < 4; i++)
{
val = 1;
suit = " ";
name = " ";
suitNum++;
System.out.println();
System.out.println();
for(int z = 0; z < 13; z++)
{
if(suitNum == 1)
{
suit = "Hearts";
}
if(suitNum == 2)
{
suit = "Diamonds";
}
if(suitNum == 3)
{
suit = "Spades";
}
if(suitNum == 4)
{
suit = "Clubs";
}
if(val == 1)
{
name = "Ace";
}
else if(val == 11)
{
name = "Jack";
}
else if(val == 12)
{
name = "Queen";
}
else if(val == 13)
{
name = "King";
}
else {
name = "";
}
Card myCards = new Card(val, suit, name);
Deck.add(myCards);
System.out.print(myCards + " ");
val++;
}
}
}
public void Deal()
{
int size = 52 / 2;
for(int i = 0; i < size; i++)
{
Random();
for(int z = 0; z < cardCheck.length; z++)
{
if(cardCheck[i] == null)
{
cardCheck[i] = Deck.get(rnd);
play1.add(cardCheck[i]);
System.out.println(play1);
}
else
{
Random();
}
}
}
System.out.println();
System.out.println();
for(int i = 0; i < size; i++){
Deck.remove(play1.get(i));
}
for(int i = 0; i < size; i++){
play2.add(Deck.get(i));
}
for(int i = 0; i < size; i++)
{
System.out.println(play2.get(i));
}
}
public void Random()
{
rnd = (int)(Math.random() * 52) - decrease;
}
public void flip()
{
if(play1.indexOf(cardnum) >= play1.size() || play2.indexOf(cardnum2) >= play2.size())
{
cardnum = (int)(Math.random() * play1.size());
System.out.println(play1.get(cardnum));
cardnum2 = (int)(Math.random() * play2.size());
System.out.println(play2.get(cardnum2));
}
}
public void compare()
{
System.out.println("War!!!\n");
if(play1.get(cardnum).getNum() > play2.get(cardnum2).getNum())
{
System.out.println();
winner = 1;
System.out.println(play1.get(cardnum) + " vs " + play2.get(cardnum2));
play1.add(play2.get(cardnum2));
play2.remove(cardnum2);
System.out.println("Player 1 took the cards!");
System.out.println();
printDecks();
}
if(play1.get(cardnum).getNum() < play2.get(cardnum2).getNum())
{
System.out.println();
winner = 2;
System.out.println(play1.get(cardnum) + " vs " + play2.get(cardnum2));
play2.add(play1.get(cardnum));
play1.remove(cardnum);
System.out.println("Player 2 took the cards!");
System.out.println();
printDecks();
}
if(play1.get(cardnum).getNum() == play2.get(cardnum2).getNum())
{
System.out.println();
System.out.println(play1.get(cardnum) + " vs " + play2.get(cardnum2));
System.out.println("War!!");
winner = 0;
flip();
flip();
flip();
compare();
System.out.println();
printDecks();
}
}
public void playW()
{
while(play1.size() > 0 || play2.size() > 0)
{
flip();
compare();
}
}
public void printDecks()
{
for(int i = 0; i < play1.size(); i++)
{
System.out.print(play1.get(i) + " ");
}
System.out.println();
for(int i = 0; i < play2.size(); i++)
{
System.out.print(play2.get(i) + " ");
}
System.out.println();
System.out.println("Player 1 has: " + play1.size() + " cards");
System.out.println("Player 2 has: " + play2.size() + " cards");
}
}
This is more a comment but it became too long.
There is a lot to say about this code. Use switch case instead of series of if. Or at least use if else. What is the point of a for loop if you use cases inside? What is the 'i' variable for if you then increment yourself a suitNum variable? Don't use capital letter for methods. Only classes. Why does Random edits a variable and returns void? It would be more logical that random() returns the result you want and this way you get free of the useless variable 'rnd'
There is a lot more to say but it is a good start. About your error, in short, a stack overflow means that your program is using too much memory. This is especially common in code that contains an infinite recursive loop. Here, the infinite recursion is due to the compare method called inside the compare method...
and have little knowledge as to what this error even means besides my class doesn't have recursion done well.
Yes, your code has recursion, and it's easy to find. You know that the problem is coming from within the compare method, and so all you have to do is look within that method for compare() and find out where you're having the method call itself.
The solution is not to call the method within itself, and why should it be doing this anyway?
You're having the issue partly because your class structure is broken. The Deck class is class that should represent the structure and behavior of a deck of cards, nothing more and nothing less, It should have methods like public void shuffle(), like public Card Deal(), and such. It should not have any code that directly interacts with the user, and this code should go elsewhere, perhaps in your driver or Game class, or even as separate class(es) entirely.
I'm guessing that you'll also want to have a Hand class, one that holds a player's hand, and perhaps inside of this class, have a compare method that compares the current Hand with another Hand, passed in as a parameter.
You'll also want a Game class should have a game-loop that controls play, that ends when there is a winner or a draw, that holds the Deck, that holds 1 or more Player objects...
e.g.,
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES
}
public enum Value {
//....
}
public class Card {
private Suit suit;
private Value value;
// TODO: constructor, methods including equals, hashCode
}
public class Deck {
private List<Card> cards = new ArrayList<>();
public Card deal() {
return cards.remove(0);
}
public void shuffle() {
Collection.shuffle(cards);
}
//....
}
class Player {
// either use a List in each Player or create a class called hand
private List<Card> hand;
private int cash;
private String name;
private Game game;
// TODO: constructor
// TODO: methods including receiveCard(Card c), List<Card> showHand(),...
}
public class Game {
private Player p1;
private Player p2;
private Deck deck;
private int moneyPot;
import java.util.Scanner;
public class fmax
{
public static void main(String[] args)
{
int max;
max = maxnum();
System.out.println("The max number is: " + max);
}
public static int maxnum()
{
int max = 0, element = 0;
Scanner keyboard = new Scanner(System.in);
int []fmax = new int[10];
for(int i = 0; i < fmax.length; i++)
{
System.out.print("Enter number " + (i+1) + ":");
fmax[i] = keyboard.nextInt();
if(fmax[i] > max)
{
max = fmax[i];
element = i; //the variable i want to be returned
}
}
return max;
}
}
Okay, I am able to return a max value in this program, however, I would like to return the value of the element/index assigned to the max value that I return. How would i go about doing that?
to return two values pack it into some object and return it ;)
public class ReturnedObject{
private Object val1;
private Object val2;
//getters setters
}
public ReturnedObject yourMethod(){
ReturnedObject returnedObject = new ReturnedObject();
returnedObject.setVal1("yourVal1");
returnedObject.setVal2("yourVal2");
return returnedObject;
}
You can pass the values into arrays/objects. (I am not saying that you can return an array).If you pass array into the method as one of the parameters, the values of the array shall remain. You can access the values from there.
Note: If you find yourself in need of returning more than one value using one method, you should consider re-designing your codes.
Arrays.sort() gives and error of:
FiveDice.java:19: error: no suitable method found for sort(int)
Arrays.sort(compNums);
If I take anything out of the for loop, it thinks thee is only 1 number or gives an error. What other sorting options would be usable?
import java.util.*;
public class FiveDice {
public static void main(String[] args) {
int x;
int compNums = 0;
int playerNums;
Die[] comp = new Die[5];
Die[] player = new Die[5];
System.out.print("The highest combination wins! \n5 of a kind, 4 of a kind, 3 of a kind, or a pair\n");
//computer
System.out.print("Computer rolled: ");
for(x = 0; x < comp.length; ++x) {
comp[x] = new Die();
compNums = comp[x].getRoll();
//Arrays.sort(compNums); <--does not work
System.out.print(compNums + " ");
}
//player
System.out.print("\nYou rolled: \t ");
for(x = 0; x < player.length; ++x) {
player[x] = new Die();
playerNums = player[x].getRoll();
System.out.print(playerNums + " ");
}
}
}
die class
public class Die {
int roll;
final int HIGHEST_DIE_VALUE = 6;
final int LOWEST_DIE_VALUE = 1;
public Die()
{ }
public int getRoll() {
roll = ((int)(Math.random() * 100) % HIGHEST_DIE_VALUE + LOWEST_DIE_VALUE);
return roll; }
public void setRoll()
{ this.roll = roll; }
}
Easiest way is to implement Comparable to Die class , set value of roll in constructor of Die not in the getter method and your problem is solved.
public class Die implements Comparable<Die> {
private int roll;
final int HIGHEST_DIE_VALUE = 6;
final int LOWEST_DIE_VALUE = 1;
public Die() {
roll = ((int)(Math.random() * 100) % HIGHEST_DIE_VALUE + LOWEST_DIE_VALUE);
}
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
public int compareTo(Die d) {
return new Integer(d.getRoll()).compareTo(new Integer(this.getRoll()));
}
}
now Arrays.sort(Die[]) will sort the array of Die.
You don't have to use 2 arrays for the sorting. If you implement the Comparable<T> interface, your classes can be sorted by Java Collections API. In your case, Die class can implement Comparable<T> and provide a way for the Java framework to compare dice values.
Take a look at the Java API:
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
In your case:
public class Die implements Comparable<Die>{
int roll;
final int HIGHEST_DIE_VALUE = 6;
final int LOWEST_DIE_VALUE = 1;
public Die() { }
public int computeRoll() {
roll = ((int)(Math.random() * 100) % HIGHEST_DIE_VALUE + LOWEST_DIE_VALUE);
return roll;
}
// I also changed this to store the value
public int getRoll() {
return roll;
}
public void setRoll() { this.roll = roll; }
// This is the method you have to implement
public int compareTo(Die d) {
if(getRoll() < d.getRoll()) return -1;
if(getRoll() > d.getRoll()) return +1;
if(getRoll() == d.getRoll()) return 0;
}
}
Whenever you have a Collection of Dies, like an ArrayList or LinkedList, you simply sort the collection itself. Below is a sample code.
ArrayList<Die> myCollection = new ArrayList<Die>();
myCollection.add(die1);
// more array population code
// ...
Collections.sort(myCollection);
You can't perform sort() on compNums because it is a single value. You declare it as an int value, rather than as an array of integers.
Instead, you should make compNums an array, populate it with the Die roll values, and then perform a sort operation on the resultant array. I believe the following will achieve what you are after.
int[] compNums = new int[5];
...
for(x = 0; x < comp.length; ++x) {
comp[x] = new Die();
compNums[x] = comp[x].getRoll();
}
Arrays.sort(compNums);
// print results
you must pass an array to the Array.Sort(arr) not parameter you must do something like this Array.Sort(int[]compNums);
and if you are using a anonymous type like comp[]compNums you must do it like this
java.util.Arrays.sort(comp[]compNums, new java.util.Comparator<Object[]>() {
public int compare(Object a[], Object b[]) {
if(something)
return 1;
return 0;
}
});
i have a task where i need to find the mode of an array. which means i am looking for the int which is most frequent. i have kinda finished that, but the task also says if there are two modes which is the same, i should return the smallest int e.g {1,1,1,2,2,2} should give 1 (like in my file which i use that array and it gives 2)
public class theMode
{
public theMode()
{
int[] testingArray = new int[] {1,1,1,2,2,2,4};
int mode=findMode(testingArray);
System.out.println(mode);
}
public int findMode(int[] testingArray)
{
int modeWeAreLookingFor = 0;
int frequencyOfMode = 0;
for (int i = 0; i < testingArray.length; i++)
{
int currentIndexOfArray = testingArray[i];
int frequencyOfEachInArray = howMany(testingArray,currentIndexOfArray);
if (frequencyOfEachInArray > frequencyOfMode)
{
modeWeAreLookingFor = currentIndexOfArray;
frequencyOfMode = modeWeAreLookingFor;
}
}
return modeWeAreLookingFor;
}
public int howMany(int[] testingArray, int c)
{
int howManyOfThisInt=0;
for(int i=0; i < testingArray.length;i++)
{
if(testingArray[i]==c){
howManyOfThisInt++;
}
}
return howManyOfThisInt;
}
public static void main(String[] args)
{
new theMode();
}
}
as you see my algorithm returns the last found mode or how i should explain it.
I'd approach it differently. Using a map you could use each unique number as the key and then the count as the value. step through the array and for each number found, check the map to see if there is a key with that value. If one is found increment its value by 1, otherwise create a new entry with the value of 1.
Then you can check the value of each map entry to see which has the highest count. If the current key has a higher count than the previous key, then it is the "current" answer. But you have the possibility of keys with similar counts so you need to store each 'winnning' answer.
One way to approach this is to check each map each entry and remove each entry that is less than the current highest count. What you will be left with is a map of all "highest counts". If you map has only one entry, then it's key is the answer, otherwise you will need to compare the set of keys to determine the lowest.
Hint: You're updating ModeWeAreLookingFor when you find a integer with a strictly higher frequency. What if you find an integer that has the same frequency as ModeWeAreLookingFor ?
Extra exercice: In the first iteration of the main loop execution, you compute the frequency of '1'. On the second iteration (and the third, and the fourth), you re-compute this value. You may save some time if you store the result of the first computation. Could be done with a Map.
Java code convention states that method names and variable name should start with a lower case character. You would have a better syntax coloring and code easier to read if you follow this convention.
this might work with a little modification.
http://www.toves.org/books/java/ch19-array/index.html#fig2
if ((count > maxCount) || (count == maxCount && nums[i] < maxValue)) {
maxValue = nums[i];
maxCount = count;
}
since it seems there are no other way, i did a hashmap after all. i am stuck once again in the logics when it comes to comparing frequencys and and the same time picking lowest integer if equal frequencys.
public void theMode()
{
for (Integer number: intAndFrequencyMap.keySet())
{
int key = number;
int value = intAndFrequencyMap.get(number);
System.out.println("the integer: " +key + " exists " + value + " time(s).");
int lowestIntegerOfArray = 0;
int highestFrequencyOfArray = 0;
int theInteger = 0;
int theModeWanted = 0;
if (value > highestFrequencyOfArray)
{
highestFrequencyOfArray = value;
theInteger = number;
}
else if (value == highestFrequencyOfArray)
{
if (number < theInteger)
{
number = theInteger;
}
else if (number > theInteger)
{
}
else if (number == theInteger)
{
number = theInteger;
}
}
}
}
Completed:
import java.util.Arrays;
public class TheMode
{
//Probably not the most effective solution, but works without hashmap
//or any sorting algorithms
public TheMode()
{
int[] testingArray = new int[] {2,3,5,4,2,3,3,3};
int mode = findMode(testingArray);
System.out.println(Arrays.toString(testingArray));
System.out.println("The lowest mode is: " + mode);
int[] test2 = new int[] {3,3,2,2,1};
int mode2=findMode(test2);
System.out.println(Arrays.toString(test2));
System.out.println("The lowest mode is: " +mode2);
int[] test3 = new int[] {4,4,5,5,1};
int mode3 = findMode(test3);
System.out.println(Arrays.toString(test3));
System.out.println(The lowest mode is: " +mode3);
}
public int findMode(int[] testingArray)
{
int modeWeAreLookingFor = 0;
int frequencyOfMode = 0;
for (int i = 0; i < testingArray.length; i++)
{
int currentIndexOfArray = testingArray[i];
int countIntegerInArray = howMany(testingArray, currentIndexOfArray);
if (countIntegerInArray == frequencyOfMode)
{
if (modeWeAreLookingFor > currentIndexOfArray)
{
modeWeAreLookingFor = currentIndexOfArray;
}
}
else if (countIntegerInArray > frequencyOfMode)
{
modeWeAreLookingFor = currentIndexOfArray;
frequencyOfMode = countIntegerInArray;
}
}
return modeWeAreLookingFor;
}
public int howMany(int[] testingArray, int c)
{
int howManyOfThisInt=0;
for(int i=0; i < testingArray.length;i++)
{
if(testingArray[i]==c){
howManyOfThisInt++;
}
}
return howManyOfThisInt;
}
public static void main(String[] args)
{
new TheMode();
}
}
Glad you managed to solve it. As you will now see, there is more than one way to approach a problem. Here's what I meant by using a map
package util;
import java.util.HashMap;
import java.util.Map;
public class MathUtil {
public static void main(String[] args) {
MathUtil app = new MathUtil();
int[] numbers = {1, 1, 1, 2, 2, 2, 3, 4};
System.out.println(app.getMode(numbers));
}
public int getMode(int[] numbers) {
int mode = 0;
Map<Integer, Integer> numberMap = getFrequencyMap(numbers);
int highestCount = 0;
for (int number : numberMap.keySet()) {
int currentCount = numberMap.get(number);
if (currentCount > highestCount) {
highestCount = currentCount;
mode = number;
} else if (currentCount == highestCount && number < mode) {
mode = number;
}
}
return mode;
}
private Map<Integer,Integer> getFrequencyMap(int[] numbers){
Map<Integer, Integer> numberMap = new HashMap<Integer, Integer>();
for (int number : numbers) {
if (numberMap.containsKey(number)) {
int count = numberMap.get(number);
count++;
numberMap.put(number, count);
} else {
numberMap.put(number, 1);
}
}
return numberMap;
}
}