Robert
Robert

Reputation: 47

How many times user repeats an int with input in java

Hello. I am having trouble with a project and am hoping my question will be answered since I am new to the site as an asker. Here is my code, The basic point of this project was to have the user enter integers, have a program that reads the integers and finds its occurrences. I was able to have the if statement find the max number out of all the numbers placed but I am having trouble getting a code that counts how many times the max number was repeated. Should I enter any number it immediately adds 1 to count, then should I add a higher number it keeps adding so should I put 1 1 2 5, it will say:
"max is 5 and count is 4 times."

import java.util.Scanner;
public class project9
{
     public static void main(String[] args)
     {
     int max = 0;
     int count = 0;
     int list = 1;
     Scanner input = new Scanner(System.in);

     System.out.println("Enter numbers for listing: ");
     while(list != 0)
     {
         list = input.nextInt();

         if(list > max)
         {
            max = list;
         }
         if(list == max)
         {
            count++;
         }
      }

      System.out.println("The numbers listed are: " + list);
      System.out.println("The number was " + max + " and it was repeated " + count + " times.");
   }
}

Upvotes: 0

Views: 2259

Answers (1)

user1864610
user1864610

Reputation:

Try this:

 while(list != 0)
 {
     list = input.nextInt();

     if(list > max)
     {
        max = list;
        count = 1;         // reset count when new max is found.
     }
     if(list == max)
     {
        count++;
     }
  }

Upvotes: 1

Related Questions