Output election winner in the presence of ties - java

I have programmed a working voting system, but it needs a little more decision making involved. The program needs to work if two or more candidates have the same number of votes.
Below is what i have but i think it is very long winded, and it will only work with 2 candidates having the same number of votes. Is there a more efficient way of doing this while working with 2 or more candidates having the same votes.
There are only 5 candidates available in this scenario, but should work if more are added too.
if(numArray[0] == numArray[1]){
System.out.println("\nIn third place: " + Array[3]);
System.out.println("In second place: " + Array[2]);
System.out.println("And the winner is: " + Array[0] + " and " + Array[1]);
}else if(numArray[1] == numArray[2]){
System.out.println("\nIn third place: " + Array[3]);
System.out.println("In second place: " + Array[1] + " and " + Array[2]);
System.out.println("And the winner is: " + Array[0]);
}else if(numArray[2] == numArray[3]){
System.out.println("\nIn third place: " + Array[2] + " and " + Array[3]);
System.out.println("In second place: " + Array[1]);
System.out.println("And the winner is: " + Array[0]);
}else{
System.out.println("\third place: " + Array[2]);
System.out.println("second place: " + Array[1]);
System.out.println("winner is: " + Array[0]);
}

I'd first check what are the scores, highest, second highest, third highest.
And then pick the names which have these values
public static void displayFinalResults(String[] stringArray, int[] numArray){
int highestScore = max(numArray, Integer.MAX_VALUE);
int secondHighestScore = max(numArray, highestScore);
int thirdHighestScore = max(numArray, secondHighestScore);
System.out.println("\nIn third place: ");
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == thirdHighestScore) {
System.out.println(stringArray[i]);
}
}
System.out.println("In second place: ");
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == secondHighestScore) {
System.out.println(stringArray[i]);
}
}
System.out.println("And the winner: ");
for (int i = 0; i < numArray.length; i++) {
if (numArray[i] == highestScore) {
System.out.println(stringArray[i]);
}
}
}
public static int max(int[] scores, int lessThan) {
int max = Integer.MIN_VALUE;
for (int score : scores) {
if (score > max && score < lessThan) {
max = score;
}
}
return max;
}

This is approach I would take. I would create a structure to hold the candidate name and number of votes as tracking that across 2 arrays is complicated and might be confusing. I would also suggest to use different data structures than arrays as the method input, I converted the input in the example into stream of Candidate which has 2 fields name and numVotes:
record Candidate(String name, int numVotes) {
}
public static void displayFinalResults(String[] stringArray, int[] numArray) {
//make sure that 2 arrays match in size
assert numArray.length == stringArray.length;
//zip arrays and convert to the stream of Candidate
var candidates = IntStream.range(0, stringArray.length).mapToObj(i -> new Candidate(stringArray[i], numArray[i]));
//group by number of votes
var groupedByNumVotes = candidates.collect(Collectors.groupingBy(c -> c.numVotes));
//sort by number of votes descending
var sorded = groupedByNumVotes.entrySet().stream().sorted((e1, e2) -> Integer.compare(e2.getKey(), e1.getKey()));
//take first 3 places
var winners = sorded.limit(3).toList();
//Loop through the list of winners with index and print it
for (int i = 0; i < winners.size(); i++) {
//List is indexed from 0 so the place number needs to be increased by one
System.out.println("Place " + (i + 1));
winners.get(i).getValue().forEach(System.out::println);
System.out.println();
}
}

Frankly, there is nothing fundamentally wrong with your approach (except that, by convention, the second place is usually skipped if there is a tie for the first; that is: there are two tied first-place candidates and a third place, but no second place). You just need to add one more case for three tied candidates.
That said, you can slightly shorten the code by merging redundancies in output formatting:
public static void displayFinalResults(String[] names, int[] scores) {
final String[] winners = new String[3];
if (scores[0] == scores[1] && scores[1] == scores[2]) {
winners[0] = String.format("%s, %s and %s", names[0], names[1], names[2]);
} else if (scores[0] == scores[1]) {
winners[0] = String.format("%s and %s", names[0], names[1]);
winners[2] = names[2];
} else if (scores[1] == scores[2]) {
winners[0] = names[0];
winners[1] = String.format("%s and %s", names[1], names[2]);
} else {
System.arraycopy(names, 0, winners, 0, 3);
}
System.out.println();
if (winners[2] != null) System.out.printf("In third place: %s\n", winners[2]);
if (winners[1] != null) System.out.printf("In second place: %s\n", winners[1]);
final String prefix = winners[2] == null && winners[1] == null ? "T" : "And t";
System.out.printf("%she winner is: %s\n", prefix, winners[0]);
}

Related

A very basic java outprint issue

I want a specific command to print on the same line but it prints on different lines and I can't figure out a simple fix for it.
package lab10;
import java.util.Scanner;
public class PrintArray {
public static void main(String[] args) {
int numItems;
int[] items;
Scanner scan = new Scanner (System.in);
System.out.println("Enter the number of items");
numItems = scan.nextInt();
items = new int [numItems];
if (items.length > 0);{
System.out.println("Enter the value of all items"
+ "(seperated by space):");
for (int i = 0; i < items.length; ++i) {
int val = scan.nextInt();
items[i]= val;
}
}
for (int i = 0; i < items.length; ++i) {
if (i== 0) {
System.out.println("The values are:" + items[i]);
}else {
System.out.println("The values are:" + items[i] + "," + " ");
}
}
}
}
Expected result:
Enter the number of items
3
Enter the value of all items(separated by space):
1 2 3
The values are:1, 2, 3
Actual result:
Enter the number of items
3
Enter the value of all items(separated by space):
1 2 3
The values are:1
The values are:2,
The values are:3,
Instead of i == 0 you want items.length == 0, and "is" not "are". Also, you'll need additional logic to handle joining the values (and use System.out.print to avoid printing a newline). Like,
if (items.length != 0) {
System.out.print("The values are: ");
}
for (int i = 0; i < items.length; ++i) {
if (items.length == 1) {
System.out.print("The value is: " + items[i]);
} else {
if (i != 0) {
System.out.print(", ");
}
System.out.print(items[i]);
}
}
System.out.println();
I think this approach may be cleaner.
StringJoiner joiner = new StringJoiner(", ", "The values are:", "");
if (items.length > 0){
System.out.println("Enter the value of all items"
+ "(seperated by space):");
for (int i = 0; i < items.length; ++i) {
int val = scan.nextInt();
items[i]= val;
joiner.add(items[i]);
}
}
System.out.println(joiner.toString());
BTW, at this line
if (items.length > 0);{
the semicolon(;) should not be there.

How to print out information from data used in arrays?

My code asks for a user to enter how many wins, losses, and ties 6 different sports teams have gotten throughout a season. How can I make it so that once all the information has been received, it will print out how many wins, ties, and losses each team have gotten, as well as displaying the total amount of each?
Code:
package SMKTeamStandings;
import java.util.Scanner;
public class SMKTeamStandings {
public static Scanner in = new Scanner(System.in);
public static int number(int max, int min) {
int teamchoice = 0;
for (boolean valid = false; valid == false;) {
teamchoice = in.nextInt();
if (teamchoice >= min && teamchoice <= max) {
valid = true;
} else {
System.out.println("Please enter a different value.");
}
}
return teamchoice;
}
public static boolean finished(boolean[] completedArray) {
int i = 0;
boolean done;
for (done = true; done == true;) {
if (completedArray[i++] == false) {
done = false;
}
}
return done;
}
public static void main(String[] args) {
int teamChoice = 0, gamesNum;
String[] sportteams = {"Basketball", "Football",
"Hockey", "Rugby",
"Soccer", "Volleyball"};
boolean[] completed = new boolean[sportteams.length];
int[][] Outcome = new int[64][sportteams.length];
for (boolean done = false; done == false;) {
for (int i = 0; i < sportteams.length; i++) {
System.out.print(i + 1 + " - " + sportteams[i]);
if (completed[i] == true) {
System.out.println(" - Finished");
} else {
System.out.println();
}
}
System.out.print("\nChoose a team from the list above:");
teamChoice = number(6, 1);
teamChoice--;
System.out.print("\nHow many games total did the " + sportteams[teamChoice]
+ " team play this season?: ");
gamesNum = in.nextInt();
System.out.format("\n %10s %10s %10s %10s %10s \n\n", "", "Possible Outcomes:",
"1 - Win",
"2 - Tie",
"3 - Loss");
for (int wintieloss = 0; wintieloss < gamesNum; wintieloss++) {
System.out.print("\nEnter the outcome for game "
+ (wintieloss + 1) + ": ");
Outcome[wintieloss][teamChoice] = number(3, 1);
}
System.out.println("\n");
completed[teamChoice] = true;
done = finished(completed);
If I understood you correctly, you just want to output the data you got from the user. To do that you could go through the data array using a for loop and accessing the data using indices.
for(int team = 0; team < sportteams.length; team++) { // for each team
System.out.println((team + 1) + " - " + sportteams[team]); // output the team
int game = 0; // index of the current game
while(Outcome[game][team] != 0) { // while there is data
System.out.print("Game " + (game + 1) ": " + Outcome[game][team] + " "); // print the data
game++; // increment the index
}
System.out.println("Total games: " + game); // print the last index == total number of games
System.out.println();
}

Printing out selected objects from ArrayList depending on attribute value

I have a method for printing out Athletes results in a competition. This method prints out the highest scores for the input category. The problem is that it prints out every result for every athlete. I only want it to print out the highest value each athlete has gotten for the input category. Ive searched far and wide for an answer but cannot find out to how to do it with my limited knowledge. So my question is: How to only print out the highest value from 1 athlete so I get a real scoreboard?
void typeOutHighScores() {
ArrayList<Athlete> athletes= AthleteList.getArrayList();
Collections.sort(resultlist);
String categoryToShow = null;
System.out.println("Which category would you like to show highscores for?");
categoryToShow = scanner.nextLine();
categoryToShow = normalize(categoryToShow); //Just makes all letters small with first letter as capital.
category matchedCategory= null;
ArrayList<category> categories = CategoryList.getArrayList();
for (int i = 0; i < categories.size(); i++) {
category c = categories .get(i);
if (c.categoryName().equals(categoryToShow)) {
matchedCategory= c;
break;
}
}
if (matchedCategory== null) {
System.out.println("Couldn't find " + categoryToShow + ".");
} else {
System.out.println("Resultatlist for " + categoryToShow + ": ");
for (int i = 0; i < resultlist.size(); i++) {
Athlete matched = null;
int order = 0;
Result res = resultlist.get(i);
if (res.categoryName().equals(categoryToShow)) {
for (int x = 0; x < athletes.size(); x++) {
Athlete del = athletes.get(x);
if (res.athleteStartNumber() == del.startNumber()) {
matched = del;
order = i + 1;
System.out.println(order + ". " + matched.surName() + " " + matched.lastName()
+ " has the result: " + res.categoryValue());
break;
}
}
}
}
}
}
Consider this:
Map<Athlete,Double> athleteResults = new HashMap<Athlete,Double>();
And instead of printing each athlete you do
if(!athleteResults.containsKey(matched) //no score yet
|| athleteResult.get(matched) < res.categoryValue()) { //higher score
athleteResult.put(matched, res.categoryValue());
}
Then afterwards iterate the map and print the results.
Good luck.

Storing user input to an array java

I know this question have been asked a lot of times, but I still could not solve the problem. The problem is that I have to store an user input and print out a value.
For example, there are 4 people, person1, person2, person3 and person4. If I vote for person1, the vote number of person1 becomes 1 and the others remain 0. Then if I vote for person2, the vote number of person2 becomes 1 and person1 is also 1.
I can compile the code. But then if I vote for person1, the output becomes 4. and if I then vote for person2, the output of person2 becomes 4 and vote for person1 went back to 0. I am a complete beginner in programming and got stuck at this program for 4 whole days so any help is greatly appreciated. Thank you very much in advance.
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
public static void main (String[] args)
{
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Initialize String Arrays
String[] person = new String[4];
person[0] = "person1";
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
int[] votescount = new int[4];
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
int i;
for (i=0; i<votescount.length; i++)
{
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
} // end for loop
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
When you do this:
for (i=0; i<votescount.length; i++){...
} // end for loop
The loop happens 4 times. This means that this bit is happening 4 times:
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
which means the vote count goes up by 4!
get rid of your for loop:
for (i=0; i<votescount.length; i++)
and make persons and votescount global and static.
This is the updated code:
import javax.swing.*; // import swing lib for i/o
public class Arrays4
{
static String[] person = new String[4];//these have been made global and static
static int[] votescount = new int[4];
public static void main (String[] args)
{
// Initialize String Arrays
person[0] = "person1";//these have been moved so that it is only called once
person[1] = "person2";
person[2] = "person3";
person[3] = "person4";
// Initialize int Arrays
votescount[0] = 0;
votescount[1] = 0;
votescount[2] = 0;
votescount[3] = 0;
voteperson();
voterepeat();
System.exit(0);
} // end method main
public static int voteperson()
{
// Declare String Variables
String userinput;
userinput = JOptionPane.showInputDialog
("Please tell us which painting you think is the best."+"\n"+
"Vote 1 "+person[0]+"\n"+
"Vote 2 "+person[1]+"\n"+
"Vote 3 "+person[2]+"\n"+
"Vote 4 "+person[3]);
int answer = Integer.parseInt(userinput);
System.out.println(answer);
int i;
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
else if (answer == 2)
{
votescount[1] = votescount[1]+1;
}
else if (answer == 3)
{
votescount[2] = votescount[2]+1;
}
else if (answer == 4)
{
votescount[3] = votescount[3]+1;
}
else
{
}
JOptionPane.showMessageDialog
(null, "The current votes are" + "\n" +
votescount[0] + " :" + person[0] + "\n" +
votescount[1] + " :" + person[1] + "\n" +
votescount[2] + " :" + person[2] + "\n" +
votescount[3] + " :" + person[3]);
return 0;
}
public static void voterepeat()
{
for (int j=1; j<=4; j++)
{
int repeat;
repeat = voteperson();
System.out.println(j);
}
}
}
First you do,
int[] votescount = new int[4];
then, you do
for (i=0; i<votescount.length; i++)
{
}
So, that loop iterates 4 times.
and inside the loop, you do,
if (answer == 1)
{
votescount[0] = votescount[0]+1;
}
and that's why, your count is up by 4!

How to assign a random number a string value in my program

as the title suggests I am doing a program for homework that is a slot machine. I have searched around and I am pretty satisfied that the program works correctly enough for me. The problem Im having is on top of generating the random numbers, I am supposed to assign values for the numbers 1-5 (Cherries, Oranges, Plums, Bells, Melons, Bars). Then I am to display the output instead of the number when my program runs. Can anyone get me pointed in the right direction on how to do this please?
import java.util.Random;
import java.util.Scanner;
public class SlotMachineClass {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int Coins = 1000;
int Wager = 0;
System.out.println("Steve's Slot Machine");
System.out.println("You have " + Coins + " coins.");
System.out.println("Enter your bet and press Enter to play");
while (Coins > 0)
{
int first = new Random().nextInt(5)+1;
int second = new Random().nextInt(5)+1;
int third = new Random().nextInt(5)+1;
Wager = input.nextInt();
if(Wager > Coins)
Wager = Coins;
System.out.println(first + " " + second + " " + third);
if(first == second && second == third)
{ Coins = Coins + (Wager * 3);
System.out.println("You won " + (Wager * 3) + "!!!!" + " You now have " + Coins + " coins.");
System.out.println("Enter another bet or close program to exit");}
else if((first == second && first != third) || (first != second && first == third) || (first != second && second == third))
{ Coins = Coins + (Wager * 2);
System.out.println("You won " + (Wager * 2) + "!!!" + " You now have " + Coins + " coins.");
System.out.println("Enter another bet or close program to exit");}
else {Coins = Coins - Wager;
System.out.println("You Lost!" + "\nPlay Again? if so Enter your bet.");}
}
while (Wager == 0)
{
System.out.println("You ran out of coins. Thanks for playing.");
}
}
}
If you have an int and want to have some String associated with that, there are a couple of ways to do that.
The first one is to have an array of Strings and look them up.
public static String[] text = new String[] {"Cherry", "Bell", "Lemon", "Bar", "Seven"};
public String getNameForReel(int reelValue) {
return text[reelValue];
}
// And to call it...
System.out.println(getNameForReel(first)); //etc...
Or, you can do it in a switch statement (I don't prefer this, but you might):
public String getNameForReel(int reelValue) {
switch(reelValue) {
case 0: return "Cherry";
case 1: return "Bell";
case 2: return "Lemon";
case 3: return "Bar";
case 4: return "Seven";
}
}
You need a lookup table:
String[] text = new String[] {"Cherry", "Bell", "Lemon", "Bar", "Seven"};
Then you can just do
System.out.println(text[first] + " " + text[second] + " " + text[third]);
without creating more methods.
The non-array solution most likely to be used a by new programmer in an intro course would be a nested if-else:
String fruitToPrint = "";
if (num == 0)
fruitToPrint = "Cherries";
else if (num == 1)
fruitToPrint = "Oranges";
else if (num == 2)
fruitToPrint = "Plums";
else if (num == 3)
fruitToPrint = "Bells";
else if (num == 4)
fruitToPrint = "Melons";
else if (num == 5)
fruitToPrint = "Bars";
else
System.out.println("Couldn't assign fruit from num=" + num);
System.out.println("The corresponding fruit was " + fruitToPrint);
Create an array:
String[] s = {Cherries, Oranges, Plums, Bells, Melons, Bars};
Then you can print s[num-1] instead of num (where num is the random int). E.g. if your random int came out to be 2, print s[2-1] i.e. s[1] which will be Orange.
Here's an alternative solution to the question which I think follows best programming practices. This is probably even less allowed for your assignment than an array, and will be a dead giveaway that you got your answer on StackOverflow, but the problem would lend itself to using an enum type with an int->enum mapping:
enum Fruit {
Cherries(1),
Oranges(2),
Plums(3),
Melons(4),
Bars(5);
private static final Map<Integer, Fruit> lookupMap = new HashMap<Integer, Fruit>();
static {
for (Fruit fruit : Fruit.values()) {
lookupMap.put(fruit.getLookup());
}
}
static Fruit fromLookup(int lookup) {
return lookupMap.get(lookup);
}
private final int lookup;
private Fruit(int lookup) {
this.lookup = lookup;
}
int getLookup() {
return lookup;
}
}
void printEnumExample() {
int fruitToPrint = 4;
System.out.println(Fruit.fromLookup(fruitToPrint)); // <- This will print "Melons"
}

Categories