Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

find max value in loop

Options
  • 15-12-2014 2:19pm
    #1
    Registered Users Posts: 1,454 ✭✭✭


    This has been wrecking my had last two days. Someone please put me out of my misery. I am trying to find the largest total earnings entered from the loop. In orange is the piece of code that should work but for some reason it is only giving me the last earnings input.

    while( count <= noOfComp)
    {

    print("Enter Company: ");
    companyName = kb.nextLine();

    print("Number of hires: ");
    noOfHires = kb.nextInt();
    kb.nextLine();

    //calculations
    totalEarnings = noOfHires * 2500 + 10000;
    System.out.println("Total Earnings from Big Sales Corp are :" + totalEarnings);

    large = totalEarnings;
    if(totalEarnings > large )
    {
    large = totalEarnings;
    }



    allTotalEarnings += totalEarnings;
    count++;

    }



Comments

  • Registered Users Posts: 8,229 ✭✭✭LeinsterDub


    Every time you loop you set large = totalEarnings thus totalEarnings > large is never true . set large =0 outside the loop


  • Registered Users Posts: 1,454 ✭✭✭bogwalrus


    Every time you loop you set large = totalEarnings thus totalEarnings > large is never true . set large =0 outside the loop



    This is just typical of me now. I spend two days trying to figure this out and the second I post looking for help i end up figuring it out.

    I had large =0 already outside the loop but the one thing I did not try is to have large = totalEarnings also outside the loop. This has fixed my issue but now I am presented with a new problem.

    I actually need the name of the company rather than its total earnings so need to figure how the max value can get me the particular company name.

    thanks!


  • Closed Accounts Posts: 7,967 ✭✭✭Synode


    Put another variable called biggest or something (biggest = "") outside the while loop to store the name of the company with the largest sales. Then add a line to the if statement

    if(totalEarnings > large )
    {
    large = totalEarnings;
    biggest = companyName;
    }


  • Registered Users Posts: 1,454 ✭✭✭bogwalrus


    I must thank you both LeinseterDub and Synode. There was no need for me to have large = totalEarnings as having large = 0 would have done the job.


    It all works great now but I need to look over it to make sure I understand why.

    Thanks again!!!:D


Advertisement