PDA

View Full Version : Array help in java(again)




Hylekmi
Mar 12, 2012, 02:48 PM
Hey guys, I am really struggling with this and I need to understand this or I will fail the course. I am making a program that basically inputs scores of athletes and I have an array of user inputed scores. I need to find the highest and lowest of the inputed scores in the array.I already have the user input but I have been having trouble using a for loop to get the highest and lowest scores. I can use a ton of If-else statements to do it but i don't want to because i need to show my teacher that I can do this to get a better grade. If someone could explain how to do this it would be very appreciated.



balamw
Mar 12, 2012, 02:49 PM
Post the code you have.

Typical min/max pseudo code is to load the first value into a temporary variable and use an if statement in the loop to update that value if the next value in the array is higher/lower than the value in the temp variable.

At the end of the loop your temp variable will contain the max/min.

B

Hylekmi
Mar 12, 2012, 02:50 PM
import java.util.Scanner;

public class gymCompetition {
public static void main(String[]args)
{
greetUser();
contest();

}//end Main

public static void contest()
{ String[] names= new String[3];
double sum = 0;
double highest=0;
double lowest=0;
double finalScore=0;


Scanner console = new Scanner (System.in);
System.out.println("Enter the names of the three contestants.");
names[0] = console.next();//brett
names[1] = console.next();//megan
names[2] = console.next();//maggie

//System.out.println(names[0]);
//System.out.println(names[1]);
//System.out.println(names[2]);

double[] score = new double[8];

System.out.println("Enter the judges scores for "+ names[0]);
score[0] = console.nextDouble();
score[1] = console.nextDouble();
score[2] = console.nextDouble();
score[3] = console.nextDouble();
score[4] = console.nextDouble();
score[5] = console.nextDouble();
score[6] = console.nextDouble();
score[7] = console.nextDouble();

for(int i=0;score.length<i;i++)
{
highest=score[i];
}
//Computes the average scores
for (int i=0; i<score.length; i++)
sum += score[i];

double average = (sum*1.0/score.length);

sum=score[0]+score[1]+score[2]+score[3]+score[4]+score[5]+score[6]+score[7];

System.out.println("the average is: "+average);
System.out.println("the highest score is: "+ highest);
System.out.println("the lowest score is: "+ lowest);
System.out.println("the sum is: "+sum);
System.out.println("the final score is: "+finalScore);

}

public static void greetUser()
{
System.out.println("Hello User");
}




}//end Public Class

gnasher729
Mar 12, 2012, 03:03 PM
for(int i=0;score.length<i;i++)
{
highest=score[i];
}


What do you expect this loop to do?

Hylekmi
Mar 12, 2012, 03:04 PM
What do you expect this loop to do?

its not a full loop...its just what i had. But the point is to find the highest value of the array and assign it to a variable.

chown33
Mar 12, 2012, 03:05 PM
score[0] = console.nextDouble();
score[1] = console.nextDouble();
score[2] = console.nextDouble();
score[3] = console.nextDouble();
score[4] = console.nextDouble();
score[5] = console.nextDouble();
score[6] = console.nextDouble();
score[7] = console.nextDouble();


for(int i=0;score.length<i;i++)
{
highest=score[i];
}
//Computes the average scores
for (int i=0; i<score.length; i++)
sum += score[i];

double average = (sum*1.0/score.length);

sum=score[0]+score[1]+score[2]+score[3]+score[4]+score[5]+score[6]+score[7];

System.out.println("the average is: "+average);
System.out.println("the highest score is: "+ highest);
System.out.println("the lowest score is: "+ lowest);
System.out.println("the sum is: "+sum);
System.out.println("the final score is: "+finalScore);

}
Regarding the purple-hilite code: If only there was some way to use a loop, for a single line of code, with only the array index incrementing each time around...

Regarding the first red-hilited code: Really? What is score.length? You should know, because you made the array only a few lines earlier. Then what is the result of the comparison? When will it be true? How many times will the loop execute? These are important questions that you need to work out the answer to.

Regarding the second red-hilited code: What do you expect this to do? At the end of the loop, all you have is the last value assigned to highest. You haven't done anything else. You need to break it down and figure out what you want ONE step of the loop to do (balamw already described it). Then you need to set the correct limits (starting and ending) for the loop, so it actually performs that step the correct number of time.

Regarding the green-hilited code: Why are you repeating this? Didn't you just calculate the sum in a loop?

balamw
Mar 12, 2012, 03:05 PM
Also, is there a reason you are computing sum twice? (EDIT: what chown33 said).

B

Hylekmi
Mar 12, 2012, 03:17 PM
Regarding the purple-hilite code: If only there was some way to use a loop, for a single line of code, with only the array index incrementing each time around...

Regarding the first red-hilited code: Really? What is score.length? You should know, because you made the array only a few lines earlier. Then what is the result of the comparison? When will it be true? How many times will the loop execute? These are important questions that you need to work out the answer to.

Regarding the second red-hilited code: What do you expect this to do? At the end of the loop, all you have is the last value assigned to highest. You haven't done anything else. You need to break it down and figure out what you want ONE step of the loop to do (balamw already described it). Then you need to set the correct limits (starting and ending) for the loop, so it actually performs that step the correct number of time.

Regarding the green-hilited code: Why are you repeating this? Didn't you just calculate the sum in a loop?
import java.util.Scanner;

public class gymCompetition {
public static void main(String[]args)
{
greetUser();
contest();

}//end Main

public static void contest()
{ String[] names= new String[3];
double sum = 0;

double lowest=0;
double finalScore=0;


Scanner console = new Scanner (System.in);
System.out.println("Enter the names of the three contestants.");

for(int i=0;i<3;i++)
{
names[i] = console.next();
}




//System.out.println(names[0]);
//System.out.println(names[1]);
//System.out.println(names[2]);

double[] score = new double[8];

System.out.println("Enter the judges scores for "+ names[0]);

for(int i=0;i<8;i++)
{
score[i]=console.nextDouble();
}


double highest=score[0];
for(int i=1;score.length>i;i++)
{
if(score[0]<highest)
{
highest=score[i];
}
}


//Computes the average scores
for (int i=0; i<score.length; i++)
sum += score[i];

double average = (sum*1.0/score.length);



System.out.println("the average is: "+average);
System.out.println("the highest score is: "+ highest);
System.out.println("the lowest score is: "+ lowest);
System.out.println("the sum is: "+sum);
System.out.println("the final score is: "+finalScore);

}

public static void greetUser()
{
System.out.println("Hello User");
}


Thanks for the constructive sarcasm....:o

balamw
Mar 12, 2012, 03:20 PM
double highest=score[0];
for(int i=1;score.length>i;i++)
{
if(score[0]<highest)
{
highest=score[i];
}
}



What do you think that code does?

Do you get the higher value when you try it?

B

Hylekmi
Mar 12, 2012, 03:28 PM
What do you think that code does?

Do you get the higher value when you try it?

B

It gives me the scores[0] which is wrong.

the temporary variable that you spoke of earlier is highest right?

trunten
Mar 12, 2012, 03:43 PM
It gives me the scores[0] which is wrong.

the temporary variable that you spoke of earlier is highest right?

highest can never be less than score[0] because highest IS score[0]

I think you mean:

double highest=score[0];
for(int i = 1; i < score.length; i++)
{
if(score[i] > highest)
{
highest=score[i];
}
}

edit: You also seem to be using Java in a very procedural way

Hylekmi
Mar 12, 2012, 03:54 PM
edit: You also seem to be using Java in a very procedural way

How am i supposed to use java? Is that bad? Its just the way my mind works i guess? But thanks.

plinden
Mar 12, 2012, 04:08 PM
How am i supposed to use java? Is that bad? Its just the way my mind works i guess? But thanks.

Since Java's an object oriented language, if I were marking this I'd look for some OO concepts.

What are the classes of objects you're dealing with (Contest, Competitor)?

If you have an object of class Contest, what would its members be? What attributes would you assign to Competitor?

Any way of organizing your code to deal with things like that? Could you use a comparator to find the highest scoring competitor?

Do you know how to use the Java API JavaDocs - http://docs.oracle.com/javase/6/docs/api/

Hylekmi
Mar 12, 2012, 04:12 PM
Since Java's an object oriented language, if I were marking this I'd look for some OO concepts.

What are the classes of objects you're dealing with (Contest, Competitor)?

If you have an object of class Contest, what would its members be? What attributes would you assign to Competitor?

Any way of organizing your code to deal with things like that? Could you use a comparator to find the highest scoring competitor?

Do you know how to use the Java API JavaDocs - http://docs.oracle.com/javase/6/docs/api/


I don't know what objects are yet. I am just in java 1. we went over objects briefly but we aren't expected to know them yet. Im still learning and when i take java 2 i should know what your talking about we went over the API a little but we aren't expected to know how to do it in the class i don't think.

balamw
Mar 12, 2012, 04:50 PM
Seems a bit odd to teach Java that way, but it is what it is.

It gives me the scores[0] which is wrong.

the temporary variable that you spoke of earlier is highest right?

What does it do if you change the order of the inputs around a bit? i.e don't put them in in order, put the min and max values somewhere in the middle? trunten has a bit of a hint in the code they posted.

What do you have to change to get the lowest value?

B

Hylekmi
Mar 12, 2012, 06:08 PM
I got it thanks! I was just a little off when he gave it to me. Now my task is to run the scores part 3 separate times for each of the competitors. I learned a lot from what you explained to me. I know now that i need to practice my for loops. all i had to do to get the lowest was flip the < sign. Thanks again!

trunten
Mar 12, 2012, 06:58 PM
I got it thanks! I was just a little off when he gave it to me. Now my task is to run the scores part 3 separate times for each of the competitors. I learned a lot from what you explained to me. I know now that i need to practice my for loops. all i had to do to get the lowest was flip the < sign. Thanks again!

Hi Hylekmi, please to hear that you've worked it out. Although your next challenge would be where objects really make things much easier. Evidently the structure of your course will get to this at a later date but perhaps it'd be worth having a look into it for a bit of extra credit?

Hylekmi
Mar 12, 2012, 07:47 PM
What would be the best way to repeat the code for the 3 contestants. It says directly in the assignment that i have to store the values in an array. Do i just copy and paste the code and make three separate variables for the values(ex.sum of type one,two,three.) or should i make a method that holds everything but the names and have it return the value. Im stuck i just don't know what the best way to do it.

wpotere
Mar 12, 2012, 08:08 PM
If it is a course, that is the way that it is generally taught. They start with the basics (string manipulation, arrays, loops etc...) before they jump into objects. Very normal and no reason to berate the guy over it.

balamw
Mar 12, 2012, 08:11 PM
What would be the best way to repeat the code for the 3 contestants. It says directly in the assignment that i have to store the values in an array. Do i just copy and paste the code and make three separate variables for the values(ex.sum of type one,two,three.) or should i make a method that holds everything but the names and have it return the value. Im stuck i just don't know what the best way to do it.

Did you learn about multi-dimensional arrays?

B

Hylekmi
Mar 12, 2012, 08:15 PM
Did you learn about multi-dimensional arrays?

B

No i didn't.

trunten
Mar 12, 2012, 08:23 PM
If it is a course, that is the way that it is generally taught. They start with the basics (string manipulation, arrays, loops etc...) before they jump into objects. Very normal and no reason to berate the guy over it.

I wasn't berating him at all. I happened to be taught OOP principles first then code, so my experience was obviously different to the way it's generally taught.

Anyway, objects to one side for a second ;) I'd probably go with a 2 dimensional array too.
eg:

double[][] contestantScores = new double[3][8];
for (int contestant = 0; contestant < contestantScores.length; contestant++)
{
for (int score = 0; score < contestantScores[contestant].length; score++)
{
contestantScores[contestant][score] = console.nextDouble();
}
}


edit: Didn't see your reply there. Perhaps have three array variables for each contestant and call them contestantOne, contestantTwo and contestantThree?

elppa
Mar 12, 2012, 08:24 PM
Following on from plinden and for illustration purposes, below is a competitor (athlete).

A competitor has a name, a number of scores, an average score a min score and a max score.


public class Competitor implements Comparable<Competitor>
{
private String name;

private double[] scores;

private double averageScore;

private double minScore;

private double maxScore;

public Competitor()
{

}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public void setScores(double[] scores)
{
this.scores = scores;
averageScore = calculateTotalScore() / scores.length;

// work out the max/min scores
minScore = scores[0];
for(int i = 0; i < scores.length; i++)
{
if(scores[i] < minScore)
{
minScore = scores[i];
}
if(scores[i] > maxScore)
{
maxScore = scores[i];
}
}
}

public double getAvergeScore()
{
return averageScore;
}

private double calculateTotalScore()
{
double sum = 0;
for (int i = 0; i < scores.length; i++)
{
sum += scores[i];
}

return sum;
}

public String toString()
{
return name + "'s lowest score is: "+ minScore + "\n" +
name + "'s highest score is: "+ maxScore + "\n" +
name + "'s average is: " + averageScore;
}

public int compareTo(Competitor thatCompetitor)
{
if(thatCompetitor.getAvergeScore() > getAvergeScore())
{
// that competitor has a higher score
return 1;
}

if(thatCompetitor.getAvergeScore() < getAvergeScore())
{
// this competitor has a higher score
return -1;
}

// scores are equal
return 0;
}
}


Each GymCompetition then contains an array (list) of competitors.

The competitor is responsible for knowing its own name.

The competitor is also responsible for keeping its own score.

You can then greatly simplify your main method.


public static void main(String[] args)
{
GymCompetition competition = new GymCompetition(3);
competition.readCompetiorsNames();
competition.readCompetiorsScores();
competition.printResults();
}


All it does is this:
[1] Sets up a competition with 3x athletes (Competitor).
[2] Reads in their names (as you code was doing before).
[3] Reads in their scores (as you code was doing before).

Here's the good bit:

[4] It then loops through each competitor and asks them to print what they scored (their min, max and average).

As a final feature, the competitors are sorted based on their score. The competitor with the highest score will now the at index 0 in the array. This athlete is the winner.

It's not perfect and there are some improvements which could be made - but I hope it give you some ideas.


import java.util.Scanner;
import java.util.Arrays;

public class GymCompetition
{
private Scanner console;

private Competitor[] comepetitors;

public GymCompetition(int competitorCount)
{
console = new Scanner(System.in);
comepetitors = new Competitor[competitorCount];

for(int i = 0; i < comepetitors.length; i++)
{
// create all of the competitors
comepetitors[i] = new Competitor();
}
}

public static void main(String[] args)
{
GymCompetition competition = new GymCompetition(3);
competition.readCompetiorsNames();
competition.readCompetiorsScores();
competition.printResults();
}

public void printResults()
{
for(int i = 0; i < comepetitors.length; i++)
{
System.out.println(comepetitors[i]);
}

// sort from highest -> lowest
Arrays.sort(comepetitors);
System.out.println(comepetitors[0].getName() + " is the winner!");
}

public void readCompetiorsNames()
{
System.out.println("Enter the names of the contestants.");
for(int i = 0; i < comepetitors.length; i++)
{
comepetitors[i].setName(console.next().trim());
}
}

public void readCompetiorsScores()
{
for(int i = 0; i < comepetitors.length; i++)
{
Competitor thisComepetitor = comepetitors[i];
System.out.println("Enter the judges scores for "+ thisComepetitor.getName());

double[] scores = new double[8];
for(int j = 0 ; j < scores.length; j++)
{
scores[j] = console.nextDouble();
}
thisComepetitor.setScores(scores);
}
}
}

Hylekmi
Mar 12, 2012, 08:38 PM
edit: Didn't see your reply there. Perhaps have three array variables for each contestant and call them contestantOne, contestantTwo and contestantThree?

So your basically saying make 3 separate arrays, one for each contestant and make sum,average,etc unique for all three arrays?

Hylekmi
Mar 12, 2012, 11:29 PM
Thankyou for all of your help guys. After 19 hours of working on two projects I have finally finished. Thank you so much for the help. heres the final code:import java.util.Scanner;

public class gymCompetition {
public static void main(String[]args)
{
greetUser();
contest();




}//end Main

public static void contest()
{


String[] names= new String[3];
Scanner console = new Scanner (System.in);
System.out.println("Enter the names of the three contestants.");

String contestant1;
String contestant2;
String contestant3;

contestant1=(names[0] = console.next());
contestant2=(names[1] = console.next());
contestant3=(names[2] = console.next());



System.out.println("Enter the judges scores for "+ contestant1);

double[] score1 = new double[8];
//enters the score
for(int i=0;i<8;i++)
{
score1[i]=console.nextDouble();
}


double contestant1Highest=score1[0];
for(int i = 1; i < score1.length; i++)
{
if(score1[i] > contestant1Highest)
{
contestant1Highest=score1[i];
}
}
double contestant1Lowest=score1[0];
for(int i = 1; i < score1.length; i++)
{
if(score1[i] < contestant1Lowest)
{
contestant1Lowest=score1[i];
}
}

//Computes the average scores
double contestant1Sum = 0;
for (int i=0; i<score1.length; i++)
contestant1Sum += score1[i];

double contestant1Average = (contestant1Sum*1.0/score1.length);

double contestant1FinalScore=(contestant1Sum-contestant1Highest)-contestant1Lowest;
/*
System.out.println("this is the score for competitor: "+contestant1);
System.out.println("the average is: "+contestant1Average);
System.out.println("the highest score is: "+ contestant1Highest);
System.out.println("the lowest score is: "+ contestant1Lowest);
System.out.println("the sum is: "+contestant1Sum);
System.out.println("the final score is: "+contestant1FinalScore);
*/
//***************************************************************************************************
//*********************************CONTESTANT#2******************************************************
//***************************************************************************************************
System.out.println("Enter the judges scores for "+ contestant2);

double[] score2 = new double[8];
//enters the score
for(int i=0;i<8;i++)
{
score2[i]=console.nextDouble();
}


double contestant2Highest=score2[0];
for(int i = 1; i < score2.length; i++)
{
if(score2[i] > contestant2Highest)
{
contestant2Highest=score2[i];
}
}
double contestant2Lowest=score2[0];
for(int i = 1; i < score2.length; i++)
{
if(score2[i] < contestant2Lowest)
{
contestant2Lowest=score1[i];
}
}

//Computes the average scores
double contestant2Sum = 0;
for (int i=0; i<score2.length; i++)
contestant2Sum += score2[i];

double contestant2Average = (contestant2Sum*1.0/score2.length);

double contestant2FinalScore=(contestant2Sum-contestant2Highest)-contestant2Lowest;
/*
System.out.println("this is the score for competitor: "+contestant2);
System.out.println("the average is: "+contestant2Average);
System.out.println("the highest score is: "+ contestant2Highest);
System.out.println("the lowest score is: "+ contestant2Lowest);
System.out.println("the sum is: "+contestant2Sum);
System.out.println("the final score is: "+contestant2FinalScore);
*/
//***************************************************************************************************
//*********************************CONTESTANT#3******************************************************
//***************************************************************************************************


System.out.println("Enter the judges scores for "+ contestant3);

double[] score3 = new double[8];
//enters the score
for(int i=0;i<8;i++)
{
score3[i]=console.nextDouble();
}


double contestant3Highest=score3[0];
for(int i = 1; i < score3.length; i++)
{
if(score3[i] > contestant3Highest)
{
contestant3Highest=score3[i];
}
}
double contestant3Lowest=score3[0];
for(int i = 1; i < score3.length; i++)
{
if(score3[i] < contestant3Lowest)
{
contestant3Lowest=score3[i];
}
}

//Computes the average scores
double contestant3Sum = 0;
for (int i=0; i<score3.length; i++)
contestant3Sum += score3[i];

double contestant3Average = (contestant3Sum*1.0/score3.length);

double contestant3FinalScore=(contestant3Sum-contestant3Highest)-contestant3Lowest;
/*
System.out.println("this is the score for competitor: "+contestant3);
System.out.println("the average is: "+contestant3Average);
System.out.println("the highest score is: "+ contestant3Highest);
System.out.println("the lowest score is: "+ contestant3Lowest);
System.out.println("the sum is: "+contestant3Sum);
System.out.println("the final score is: "+contestant3FinalScore);
*/
String winner;
winner=" ";
if((contestant1FinalScore>contestant2FinalScore)&&(contestant1FinalScore>contestant3FinalScore))
{
winner=contestant1;
System.out.println("The Winner of the gold medal is :"+winner);
}
if((contestant2FinalScore>contestant1FinalScore)&&(contestant2FinalScore>contestant3FinalScore))
{
winner=contestant2;
System.out.println("The Winner of the gold medal is :"+winner);
}

if((contestant3FinalScore>contestant1FinalScore)&&(contestant3FinalScore>contestant2FinalScore))
{
winner=contestant3;
System.out.println("The Winner of the gold medal is :"+winner);
}
if((contestant3FinalScore==contestant1FinalScore)&&(contestant3FinalScore==contestant2FinalScore)||(contestant2FinalScore==contestant1FinalScore)&&(contestant2FinalScore==contestant3FinalScore))
{
System.out.println("There is a Tie!");
}
System.out.println("The final score of: "+contestant1+" is "+contestant1FinalScore);
System.out.println("The final score of: "+contestant2+" is "+contestant2FinalScore);
System.out.println("The final score of: "+contestant3+" is "+contestant3FinalScore);
}//end contest();






public static void greetUser()
{
System.out.println("Hello User");
}
}//end Public Class

elppa
Mar 13, 2012, 04:21 AM
Well done for persevering and getting it finished.

wpotere
Mar 13, 2012, 04:56 AM
Great work! Just remember that loops are there to help you keep from writing lots of code. There are several areas that you could have looped with some variables to cut your code down by about 2/3 making it more efficient. ;)

elppa
Mar 13, 2012, 07:06 PM
Just a few of small things I noticed when looking at your final code - these will hopefully be of some use in the future. I've avoided new concepts you haven't learnt yet (like multi dimensional arrays or objects), so it should be simple enough to follow.

[1] You can write a loop to read in the contestant names. There is no reason to create contestant1, contestant2 and contestant3 as separate variables either - you already have them!

for(int i = 0; i < names.length; i++)
{
names[i] = console.next();
}


[2] The code to read in the scores and then calculate the min, max, average and total scores is duplicated for each contestant. What happens if you need to add a 4th contestant? More duplication!

Want to add 100 contestants? - you'll need a lot of coffee...

Again, another loop can be used:

String[] names= new String[3];
double[] finalScores = new double[3];

for(int i = 0; i < names.length; i++)
{
// code goes here
}


The only thing you need to keep a record of (outside the loop) is the name of each contestant, along with their final score. names[0] is the name of contestant one. finalScores[0] is the score for contestant one etc.

[3] When reading in the scores, you can keep a running record of the min, max and sum at the same time.

double[] score = new double[8];
double highestScore = 0;
double lowestScore = 0;
double sumOfScores = 0;
for(int j = 0; j < score.length; j++)
{
score[i] = console.nextDouble();

if(score[i] < lowestScore)
{
lowestScore = score[i];
}

if(score[i] > highestScore)
{
highestScore = score[i];
}

sumOfScores += score[i];
}


This means you only need calculate the average and final score after the scores have been entered as you already have the min, max and sum:

// calculate the average
double averageScore = (sumOfScores / score.length);

// calculate the total score
finalScores[i] = sumOfScores - highestScore - lowestScore;


[4] Finally the logic to determine the winner can be simplified by (you guessed it!) a loop. All you need do is loop through each score and keep a record of the highest (or if two or more scores match).

// determine the winner, or if there is a tie
String winner = "";
double winningScore = 0;
boolean tie = false;
for(int i = 0; i < finalScores.length; i++)
{
if(finalScores[i] > winningScore)
{
// we have a new winning score
winningScore = finalScores[i];
winner = names[i];
tie = false;
}
else if(finalScores[i] == winningScore)
{
// score matches current best score
tie = true;
}
}


And then:

if(!tie)
{
System.out.println("The Winner of the gold medal is: " + winner);
}
else
{
System.out.println("There is a Tie!");
}

wpotere
Mar 13, 2012, 07:13 PM
Yeah, kinda didn't want to post up all of that as this is homework. ;)

elppa
Mar 14, 2012, 04:11 AM
Reading between the lines I assumed that it had already been handed in...

If the same task is set next year and someone is enterprising enough to find this - well, good luck to them. :)