Array help in java(again)

Discussion in 'Mac Programming' started by Hylekmi, Mar 12, 2012.

  1. macrumors regular

    #1
    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.
     
  2. Moderator

    balamw

    Staff Member

    #2
    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
     
  3. macrumors regular

    #3
    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];
    	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
     
  4. macrumors G5

    gnasher729

    #4
    What do you expect this loop to do?
     
  5. macrumors regular

    #5
    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.
     
  6. macrumors 603

    #6
    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?
     
  7. Moderator

    balamw

    Staff Member

    #7
    Also, is there a reason you are computing sum twice? (EDIT: what chown33 said).

    B
     
  8. macrumors regular

    #8
    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];
    	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....:eek:
     
  9. Moderator

    balamw

    Staff Member

    #9
    What do you think that code does?

    Do you get the higher value when you try it?

    B
     
  10. Hylekmi, Mar 12, 2012
    Last edited: Mar 12, 2012

    macrumors regular

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

    the temporary variable that you spoke of earlier is highest right?
     
  11. macrumors regular

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

    I think you mean:

    Code:
            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
     
  12. macrumors regular

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

    plinden

    #13
    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/
     
  14. macrumors regular

    #14

    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.
     
  15. Moderator

    balamw

    Staff Member

    #15
    Seems a bit odd to teach Java that way, but it is what it is.

    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
     
  16. macrumors regular

    #16
    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!
     
  17. trunten, Mar 12, 2012
    Last edited: Mar 12, 2012

    macrumors regular

    #17
    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?
     
  18. macrumors regular

    #18
    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.
     
  19. Guest

    #19
    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.
     
  20. Moderator

    balamw

    Staff Member

    #20
    Did you learn about multi-dimensional arrays?

    B
     
  21. macrumors regular

    #21
    No i didn't.
     
  22. macrumors regular

    #22
    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:
    Code:
    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?
     
  23. elppa, Mar 12, 2012
    Last edited: Mar 12, 2012

    macrumors 68040

    elppa

    #23
    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.

    Code:
    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.

    Code:
    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.

    Code:
    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);
    		}
    	}
    }
    
     
  24. macrumors regular

    #24
    So your basically saying make 3 separate arrays, one for each contestant and make sum,average,etc unique for all three arrays?
     
  25. macrumors regular

    #25
    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:
    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
    
     

Share This Page