Skip to content
Advertisement

How to find max number and occurrences

So I’m learn java for the first time and can’t seem to figure how to set up a while loop properly .

my assignment is Write a program that reads integers, finds the largest of them, and counts its occurrences.

But I have 2 problems and some handicaps. I’m not allowed to use an array or list because we haven’t learned that, So how do you take multiple inputs from the user on the same line . I posted what I can up so far . I am also having a problem with getting the loop to work . I am not sure what to set the the while condition not equal to create a sential Value. I tried if the user input is 0 put I cant use user input because its inside the while statement . Side note I don’t think a loop is even needed to create this in the first place couldn’t I just use a chain of if else statement to accomplish this .

 package myjavaprojects2;
import java.util.*;
public class Max_number_count {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner input = new Scanner(System.in);
        int count = 0;
        int max = 1;
        System.out.print("Enter a Integer:");
        int userInput = input.nextInt();    

        while ( userInput != 0) {
           
                        
        if (userInput > max) {
            int temp = userInput;
            userInput = max;
            max = temp;
         } else if (userInput == max) {
             count++ ;
             
             
         }
             
    
        System.out.println("The max number is " + max );
        System.out.println("The count is " + count );
        }
      }
    }

Advertisement

Answer

So how do you take multiple inputs from the user on the same line .

You can use scanner and nextInput method as in your code. However, because nextInt only read 1 value separated by white space at a time, you need to re-assign your userInput varible at the end of while loop to update the current processing value as below.

 int userInput = input.nextInt();    

    while ( userInput != 0) {
      //all above logic
      userInput = input.nextInt();        
    }
Advertisement