Find Max in Sequence from Input - Problem with negative integers

Viewed 51

I'm quite new on Java and I'm facing an issue in this excercise: Write a method, findMax(), that repeatedly reads in integers until a 0 integer is read and keeps track of the largest integer that has been read. findMax() then returns the largest number entered.

My problem is that my code (below) is working when the input contains at least one positive integer but it is not working when the input contains only negative integers:

import java.util.Scanner;

public class FindMaxInSeq {
    public static int max() {

        Scanner scanner = new Scanner(System.in);
        int maxSoFar = 0;
        int currValue;

        do {
            currValue = scanner.nextInt();

             if (currValue > maxSoFar) {
                maxSoFar = currValue;
            }
        }
            while (currValue != 0);

            return maxSoFar;}


    public static void main(String[] args) {

        System.out.println("Test your code here!\n");

        FindMaxInSeq test = new FindMaxInSeq();
        System.out.println(test.max());
    }
}

2 Answers

When your default maxSoFar value 0 and you input only negative integers, they can't be max. Also do {} while in last iteretion set 0 to max value. Try this:

public static int max() {

    Scanner scanner = new Scanner(System.in);
    int maxSoFar = Integer.MIN_VALUE; 
    int currValue = scanner.nextInt();

    while (currValue != 0) {
        if (currValue > maxSoFar) {
            maxSoFar = currValue;
        }

        currValue = scanner.nextInt();
    }
    
    return maxSoFar == Integer.MIN_VALUE ? currValue : maxSoFar;

 }

I've found the following solution that solves my issue:

import java.util.Scanner;

public class FindMaxInSeq {
public static int max() {

    // Put your code here
    Scanner scanner = new Scanner(System.in);
    int maxSoFar = Integer.MIN_VALUE;
    int currValue;

    do {
        currValue = scanner.nextInt();

        if (currValue == 0);

         else if (currValue > maxSoFar) {
            maxSoFar = currValue;
        }
    }
        while (currValue != 0);

        return maxSoFar;
   }


public static void main(String[] args) {

    System.out.println("Test your code here!\n");

    // Get a result of your code
    FindMaxInSeq test = new FindMaxInSeq();
    System.out.println(test.max());
}
}
Related