Printing out selected objects from ArrayList depending on attribute value - java

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.

Related

Output election winner in the presence of ties

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

My program is breaking out of the first for loop after one iteration

Here is my code. It asks user for terms and definitions, then quizzes the user. (It tells the user the term, and the user types in the answer.) The program uses arrays to store the terms and definitions. If the user doesn't get the definition correct, the program asks the user whether they want to study it again. If so, they will type in yes, and the program will store it on a separate array. After the program quizzes the users on all the terms and definitions, round 2 starts, where the program will quiz the user only on the starred definition. The problem is, the code is only running the for loop (that quizzes the user on round 1) once, and then skips onto round 2. Why is that so? I already tried looking at other people's questions and answers, but I can't seem to find the problem in my code.
import java.util.*;
public class Ptcreate {
public static void main(String[] args) {
String term;
String definition;
Scanner userInput = new Scanner(System.in);
System.out.println("How many terms would you like to study?");
int number_terms = userInput.nextInt();
String[] term_array = new String[number_terms];
String[] def_array = new String[number_terms];
String[] star_array = new String[number_terms];
String[] stardef_array = new String[number_terms];
System.out.println("Now, enter the " + number_terms + " terms now.");
for (int i = 0; i < number_terms; i++) {
term_array[i] = userInput.next();
}
System.out.println(
"Now, enter all the definitions, in the correct order such that it matches the order of the terms you entered.");
for (int i = 0; i < number_terms; i++) {
def_array[i] = userInput.next();
}
System.out.println("Ok. Now for the testing!");
for (int i = 0; i <= number_terms; i++) { // the for loop that isn't
// working.
System.out.println("What is definition " + (i + 1));
String answer = userInput.next();
if (answer.equals(def_array[i])) {
System.out.println("Correct");
star_array[i] = "null";
stardef_array[i] = "null";
} else if (!answer.equals(def_array[i])) {
do {
System.out.println("Incorrect.");
System.out.println("Would you like to study this term again? Type y or n.");
String bool = userInput.next();
if (bool.equals("y")) {
star_array[i] = term_array[i];
stardef_array[i] = def_array[i];
} else if (bool.equals("n")) {
star_array[i] = "null";
stardef_array[i] = "null";
}
System.out.println("What is the definition " + (i + 1));
answer = userInput.next();
} while (!answer.equals(def_array[i]));
if (answer.equals(def_array[i])) {
System.out.println(
"Correct"); /*
* when the user finally enters the
* right definition, the program skips
* to the code below
*/
}
}
System.out.println("Now, time for testing definitions you starred!");
for (int z = 0; z < number_terms; z++) {
if (star_array[z].equals("null")) {
break;
} else {
System.out.println("What is the definition of " + star_array[z] + " ?");
String star_answer = userInput.next();
if (star_answer.equals(stardef_array[z])) {
System.out.println("Correct.");
} else if (!star_answer.equals(stardef_array[z])) {
do {
System.out.println("Incorrect. Please try again.");
System.out.println("What is the definition of " + star_array[z] + " ?");
star_answer = userInput.next();
} while (!star_answer.equals(stardef_array[z]));
}
}
}
}
}
}
for (int i = 0; i <= number_terms; i++)
You have number_terms + 1 iterations. Replace with
for (int i = 0; i < number_terms; i++)
The bug is that the for-loop that you have tagged with the comment "the for loop that isn't working" is not looping through all the definitions. This for-loop after handling the first definition it moves on to handling round 2 instead of continuing the loop to the 2nd definition and so on. The fix requires that you place the closing bracket of this for-loop before the print statement "Now, time for testing definitions you starred!" as shown below. I have added the comment "end for-loop to ensure looping of all definitions" at the for-loop closing bracket that I have moved up in the code below. In addition this for loop's iteration condition should be 'i < number_terms' as the previous posters have indicated.
import java.util.*;
public class Ptcreate {
public static void main(String[] args) {
String term;
String definition;
Scanner userInput = new Scanner(System.in);
System.out.println("How many terms would you like to study?");
int number_terms = userInput.nextInt();
String[] term_array = new String[number_terms];
String[] def_array = new String[number_terms];
String[] star_array = new String[number_terms];
String[] stardef_array = new String[number_terms];
System.out.println("Now, enter the " + number_terms + " terms now.");
for (int i = 0; i < number_terms; i++) {
term_array[i] = userInput.next();
}
System.out.println(
"Now, enter all the definitions, in the correct order such " +
"that it matches the order of the terms you entered.");
for (int i = 0; i < number_terms; i++) {
def_array[i] = userInput.next();
}
System.out.println("Ok. Now for the testing!");
for (int i = 0; i < number_terms; i++) { // the for loop that isn't
// working.
System.out.println("What is definition " + (i + 1));
String answer = userInput.next();
if (answer.equals(def_array[i])) {
System.out.println("Correct");
star_array[i] = "null";
stardef_array[i] = "null";
} else if (!answer.equals(def_array[i])) {
do {
System.out.println("Incorrect.");
System.out.println("Would you like to study this term again? Type y or n.");
String bool = userInput.next();
if (bool.equals("y")) {
star_array[i] = term_array[i];
stardef_array[i] = def_array[i];
} else if (bool.equals("n")) {
star_array[i] = "null";
stardef_array[i] = "null";
}
System.out.println("What is the definition " + (i + 1));
answer = userInput.next();
} while (!answer.equals(def_array[i]));
if (answer.equals(def_array[i])) {
System.out.println(
"Correct"); /*
* when the user finally enters the
* right definition, the program skips
* to the code below
*/
}
}
} // end for-loop to ensure looping of all definitions
System.out.println("Now, time for testing definitions you starred!");
for (int z = 0; z < number_terms; z++) {
if (star_array[z].equals("null")) {
break;
} else {
System.out.println("What is the definition of " + star_array[z] + " ?");
String star_answer = userInput.next();
if (star_answer.equals(stardef_array[z])) {
System.out.println("Correct.");
} else if (!star_answer.equals(stardef_array[z])) {
do {
System.out.println("Incorrect. Please try again.");
System.out.println("What is the definition of " + star_array[z] + " ?");
star_answer = userInput.next();
} while (!star_answer.equals(stardef_array[z]));
}
}
}
}
}

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

Array is only printing the last stored value and array element removal only replaces element

Does anyone know why is that when I print the last message ("report header..etc etc") the count on the list updates, but I'm only printing the last person's input values?
Also, how can I make so that only if the person has 30 or more credits or less than 90 will their name and credits be stored in the array, otherwise do nothing with the inputs?
Lastly, in the 'admin review' prompt portion, if I type in a name that matches an input, it should remove that name, but in my current code it only replaces the name with what I entered..
final int MAX_ON_LIST = 50;
String[] stuName = new String[1];
int[] numCredits = new int[1];
int currentSize = 0;
String question = JOptionPane.showInputDialog("Are you done entering students? (Enter 'Y' or 'N')");
while (question.equalsIgnoreCase("n")) {
for (int i = 0; i < stuName.length; i++) {
do {
try {
stuName[i] = JOptionPane.showInputDialog("Enter student name:");
currentSize++;
}
catch (NumberFormatException e) {
stuName[i] = "";
}
if (stuName[i].equals("")) {
JOptionPane.showMessageDialog(null, "Name cannot be blank");
}
} while (stuName[i].equals(""));
}
for (int i = 0; i < numCredits.length; i++) {
do {
try {
numCredits[i] = Integer.parseInt(JOptionPane.showInputDialog("Enter # of completed credits:"));
}
catch (NumberFormatException e) {
numCredits[i] = -1;
}
if (numCredits[i] < 0) {
JOptionPane.showMessageDialog(null, "# of credits can't be less than 0");
}
} while (numCredits[i] < 0);
}
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
question = JOptionPane.showInputDialog("Are you done entering students? (Enter 'Y' or 'N')");
}
String nxtQuestion = JOptionPane.showInputDialog("Are you done with the admin. review? (Enter 'Y' or 'N')");
while (nxtQuestion.equalsIgnoreCase("n")) {
String searchValue = JOptionPane.showInputDialog("Enter a name:");;
int position = 0;
boolean found = false;
while (position < stuName.length && !found) {
if (stuName[position].equalsIgnoreCase(searchValue)) {
found = true;
}
else {
++position;
}
}
if (found) {
stuName[1] = stuName[currentSize - 1];
--currentSize;
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
}
else {
JOptionPane.showMessageDialog(null, "Name not on list");
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
}
nxtQuestion = JOptionPane.showInputDialog("Are you done with the admin. review? (Enter 'Y' or 'N')");
}
if (nxtQuestion.equalsIgnoreCase("y"));
{
JOptionPane.showMessageDialog(null,
"Report Header\n\n" + "# of student's on list: " + currentSize + "\nNames: " + Arrays.toString(stuName) +
"\nCredits: " + Arrays.toString(numCredits));
}
I'm not sure why you go through all the pain of using arrays here while List (ArrayList or LinkedList) would suit your needs much better. I'm assuming this is some sort of a task where you must use arrays. Otherwise the whole code should be rewritten.
As correctly mentioned above, arrays don't change size - both of your arrays always have size of 1 all the time. This also results in index out of bounds exception if you enter more than one student and then in admin you enter the name of last student.
The name of last student is the only name saved, that's why it's the only name printed.
In order to only store person with credit >=30 and <=90 you can use a simple if.
Also note the code in the final part of your program:
if (nxtQuestion.equalsIgnoreCase("y"));
{
// Do something
}
Due to semicolon right after if the if is doing nothing.
The part in curly braces (where I've put "Do something" comment) will always get executed, it's separate from the if. (Java allows you to put blocks of code in curly braces in order to limit scope of local variables).
P.S. Here's a slightly better version (at least it works):
public static void main(String[] args) {
final int MAX_ON_LIST = 50;
final int bottomCreditsLimit = 30;
final int topCreditsLimit = 90;
String[] stuName = new String[0];
int[] numCredits = new int[0];
String question = JOptionPane.showInputDialog("Are you done entering students? (Enter 'Y' or 'N')");
while (question.equalsIgnoreCase("n") && stuName.length < MAX_ON_LIST) {
String stuNameInput = "";
do {
stuNameInput = JOptionPane.showInputDialog("Enter student name:").trim();
if (stuNameInput.equals("")) {
JOptionPane.showMessageDialog(null, "Name cannot be blank");
}
} while (stuNameInput.equals(""));
int numCreditsInput = -1;
do {
try {
numCreditsInput = Integer.parseInt(JOptionPane.showInputDialog("Enter # of completed credits:").trim());
if (numCreditsInput < 0) {
JOptionPane.showMessageDialog(null, "# of credits can't be less than 0");
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Please input integer value");
}
} while (numCreditsInput < 0);
if (numCreditsInput >= bottomCreditsLimit && numCreditsInput <= topCreditsLimit) {
stuName = Arrays.copyOf(stuName, stuName.length + 1);
stuName[stuName.length - 1] = stuNameInput;
numCredits = Arrays.copyOf(numCredits, numCredits.length + 1);
numCredits[numCredits.length - 1] = numCreditsInput;
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
}
question = JOptionPane.showInputDialog("Are you done entering students? (Enter 'Y' or 'N')");
}
String nxtQuestion = JOptionPane.showInputDialog("Are you done with the admin. review? (Enter 'Y' or 'N')");
while (nxtQuestion.equalsIgnoreCase("n")) {
String searchValue = JOptionPane.showInputDialog("Enter a name:").trim();
int position = -1;
for (int i = 0; i < stuName.length; i++) {
if (stuName[i].equalsIgnoreCase(searchValue)) {
position = i;
break;
}
}
if (position >= 0) {
stuName[position] = stuName[stuName.length - 1];
stuName = Arrays.copyOf(stuName, stuName.length - 1);
numCredits[position] = numCredits[numCredits.length - 1];
numCredits = Arrays.copyOf(numCredits, numCredits.length - 1);
} else {
JOptionPane.showMessageDialog(null, "Name not on list");
}
JOptionPane.showMessageDialog(null, Arrays.toString(stuName) + "\n" + Arrays.toString(numCredits));
nxtQuestion = JOptionPane.showInputDialog("Are you done with the admin. review? (Enter 'Y' or 'N')");
}
JOptionPane.showMessageDialog(null, "Report Header\n\n" + "# of student's on list: " + stuName.length + "\nNames: " + Arrays.toString(stuName)
+ "\nCredits: " + Arrays.toString(numCredits));
}
Each of your arrays has a single element. Every time you add a name, you're putting it into the same position in the array.
String[] stuName = new String[1];
int[] numCredits = new int[1];
This loop always has exactly one pass, with i = 0.
for (int i = 0; i < stuName.length; i++) {
Alternatives include:
Create a java.util.List of students, which grows as needed with each call to List.add().
Create a java.util.Map of students from name to value.
The for loop pre-compiles so you need to set stuName to something before engaging the loop.

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!

Categories