122k views
0 votes
I'm getting stuck in an infinite loop. I'm not sure how to get out of.

Write a method, findMax(), that repeatedly reads in integers until a negative integer is read and keeps track of the largest integer that has been read. findMax() then returns the largest number entered.

Ex: If the input is:

2 77 17 4 -1
the findMax() returns and the program output is:

77
Assume a user will enter at least one non-zero integer.

Note: Your program must define the method:
public int findMax()

import java.util.Scanner; public class Max { public int findMax() { Scanner input = new Scanner(System.in); int max = Integer.MIN_VALUE; int num = input.nextInt(); while (true) { if (num < 0) { break; } if (num > max) { max = num; } } return max; } public static void main(String[] args) { Max test = new Max(); System.out.println(test.findMax()); } }

User Mateo
by
7.6k points

1 Answer

3 votes

Final answer:

The provided code snippet is an implementation of a method named findMax()

Step-by-step explanation:

The provided code snippet is an implementation of a method named findMax() which reads in integers until a negative integer is entered and keeps track of the largest integer entered. The method returns the largest number entered.

To solve the issue of the infinite loop, you need to update the value of the num variable inside the while loop by reading the next integer using input.nextInt(). Otherwise, the loop will run infinitely with the same value num. Add the line num = input.nextInt() inside the while loop, below the if statements.

Here's the corrected code:

public int findMax() {
Scanner input = new Scanner(System.in);
int max = Integer.MIN_VALUE;
int num = input.nextInt();
while (true) {
if (num < 0) {
break;
}
if (num > max) {
max = num;
}
num = input.nextInt();
}
return max;
}

User Akintayo Jabar
by
8.8k points