How to understand the location of the largest number out of an input series?

I do not understand how to locate the largest number from a series of numbers entered by a user.

I created a MaxSentinel.java that prompts the user to enter numbers one by one. MaxSentinel breaks its cycle when a negative one is detected.

I need to modify the previous code and create MaxSentinel2.java.

The task at hand is to check for a valid first entry. Then allow the user to enter as many numbers as desired.

If an invalid number is entered, print "Invalid entry." Prompt the user again until a valid number is entered.

Once a negative one is detected, the program stops and prints the largest number entered.


import java.util.*;

public class MaxSentinel2 {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("This program allows you to enter a series of numbers.");
        System.out.println("Enter -1 when you are finished entering your numbers and");
        System.out.println("the program will print the largest number entered.");
        System.out.println("Enter your first number, please.");
        System.out.print("Next integer (-1 to quit)? ");
        input.nextInt();
        while (!input.hasNextInt()) {
            System.out.println("You have entered an invalid response.");
            System.out.println("Enter your first number, please.");
            input.nextInt();
        }
        int number = input.nextInt();
        int sum = 0;

        while (number != -1) {
            sum += number;
            while (!input.hasNextInt()) {
                System.out.println("You have entered an invalid response.");
                System.out.println("Enter your first number, please.");
                input.nextInt();
            }
            number = input.nextInt();
        }
        int max = 0;
        if (max < number) {
            max++;
        }
        System.out.println("The largest number entered was: " + max);
    }
}


Read more here: https://stackoverflow.com/questions/64940587/how-to-understand-the-location-of-the-largest-number-out-of-an-input-series

Content Attribution

This content was originally published by Megan Louise Downey at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: