Reputation: 47
import java.util.Scanner;
import java.util.List;
import java.util.Arrays;
import java.util.*;
public class Exercise16 {
public static void main(String[] args) {
System.out.println("Please enter a sequence of positive integers");
Scanner user_input = new Scanner(System.in);
String user_string = user_input.nextLine();
boolean hasNegativeOne = user_string.contains("-1");
if (hasNegativeOne){
String[] sequence = user_string.split(" ");
int[] numbers = new int[sequence.length];
for (int i = 0; i < sequence.length;i++) {
numbers[i] = Integer.parseInt(sequence[i]);
}
// Method for getting the maximum value
int max_value = 0;
for(int i=0; i<numbers.length; i++){
if (numbers[i] > max_value){
max_value = numbers[i];
}
}
// Method for getting the minimum value
int min_value = 0;
for(int i=0; i<numbers.length; i++){
if (numbers[i] < min_value){
min_value = numbers[i];
}
}
System.out.println("The maximum value is: " +max_value);
System.out.println("The minimum value is: " +min_value);
}
}
}
Hi everyone, I am developing a program where the user inputs a sequence of positive integers. My program is supposed to display the maximum and minimum value. However, whenever I run the program, the minimum value is always set as 0, even if the inputted sequence doesn't contain a 0. How can I change this? Also, I included the "if (numbers[i] > -1){" line as my program isn't allowed to accept negative numbers. Thank you in advance.
Upvotes: 2
Views: 445
Reputation: 635
It's better to initially set you max_value
and min_value
to numbers[0]
. In this case you will correctly process both cases as your default value is also valid as it is a part of user input. If there will be elements greater than (or less than) first element of array you will reassign it
if (numbers.length != 0) {
int max_value = numbers[0];
int min_value = numbers[0];
for (int i = 1; i < numbers.length; i++) {
int num = numbers[i];
if (num > max_value) {
max_value = num;
}
if (num < min_value) {
min_value = num;
}
}
System.out.println("The maximum value is: " + max_value);
System.out.println("The minimum value is: " + min_value);
} else {
// process empty user input
}
Upvotes: 1
Reputation: 486
min_value starts at 0. You can't accept negative numbers. Then you try to say:
if(number[i] < min_value)
If you can't accept negative numbers no number will be less than 0.
Upvotes: 2
Reputation: 53809
Try to initialize your minimum to something like Integer.MAX_VALUE
.
Upvotes: 2