How to display the min and max elements of an array? - java

I've been trying to solve this problem for quite some time now. I'm trying to display the min and max elements of an array, but the min always remains at 0. Here's the code that explains my issue:
public class ArrExs {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("enter the array capacity (min 1, max 20): ");
int n = input.nextInt();
while(n <= 0 || n > 20) {
System.out.print("enter a valid number and try again: ");
n = input.nextInt();
}
int[] nums = new int[n];
maxAndMin(nums);
}
public static void maxAndMin(int[] numbers) {
Scanner input = new Scanner(System.in);
System.out.println("enter your array elements: ");
int min = numbers[0];
int max = numbers[0];
for(int i = 0; i < numbers.length; i++) {
numbers[i] = input.nextInt();
max = (numbers[i] > max) ? numbers[i] : max;
min = (numbers[i] < min) ? numbers[i] : min;
}
System.out.print("min = " + min + ", max = " + max);
}
}
The output:
enter the array capacity (min 1, max 20): 3
enter your array elements:
2
3
4
min = 0, max = 4
The min always remains at 0, I've tried to edit the code multiple times but I get the same result.

I've encountered this problem before and watched a video where the instructor's logic is to set the "Min" and "Max" to the first number entered by the user. Then there comes the relational operator to decide which is minimum and maximum.

The problem is on the line where you do int min = numbers[0]; because numbers is an empty array (all of the values are 0). Since min starts at 0 and nothing in the array is less than 0 then min will remain 0 forever.
Try making min start as a high value such as int.MaxValue and see if that fixes your problem.

Related

Print odd numbers in a descending order

The program needs to take an odd number and output it in a descending order
For example: if the input is 11 the output needs to be 11 , 9 , 7 , 5 , 3, 1.
I tried using a for loop but I can only seem to get it to work with even numbers not odd numbers
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = input.nextInt();
for (int i = number - 1; i >= 0; i--) {
if (i % 2 == 0) {
int descend = i;
System.out.println(descend + " ");
}
}
}
The output is the number in descending order but as even only. If I add a 1 into the descend variable the numbers would seem to descend in an odd manner but its not ideal.
This line returns true if the number is even:
if (i % 2 == 0) {
If you want to know when the number is odd:
if (i % 2 != 0) {
Also, why are you starting your count at 1 less than the input value:
int i = number - 1;
I think you want to do this:
for (int i = number; i > 0; i--) { // tests for numbers starting at the input and stopping when i == 0
Just replace (i%2==0) to (i%2==1)
Asking if the number % 2 is equal to zero is basically asking if the number is even, so what you really have to do is ask if the number % 2 is not equal to zero, or equal to 1
if (i % 2 != 0) {
int descend = i;
System.out.println(descend + " ");
}
Also, there's no need to subtract 1 from the user input so your for loop can be written like this
for (int i = number; i >= 0; i--) {
if (i % 2 == 0) {
int descend = i;
System.out.println(descend + " ");
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an an odd number: ");
int number = input.nextInt();
while(number%2==0){
System.out.print("Number must be odd number:" +
"(Ex:1, 3,5)\nTry again: ");
number=input.nextInt();
}
for (int i = number; i >= 0; i--) {
if(number%2!=0){
System.out.println(number);}
number-=1;
}
}

Largest Occurrence Count

Im new to programming and am stumped on this problem, Ive tried a few different ways with no success.
Implement (source code) a program (name it LargestOccurenceCount) that read from the user positive non-zero integer values, finds the largest value, and counts it occurrences. Assume that the input ends with number 0 (as sentinel value to stop the loop). The program should ignore any negative input and should continue to read user inputs until 0 is entered. The program should display the largest value and number of times it appeared
Scanner reader = new Scanner(System.in);
int num = 0;
int array[] = null;
while ((num = reader.nextInt()) != 0) {
System.out.println("Enter a positive integer (0 to quit): ");
num = reader.nextInt();
array[num] = num;
}
Sample run 1:
Enter positive integers (0 to quit): 3 4 5 -9 4 2 5 1 -5 2 5 0
Largest value: 5
Occurrences: 3 times
The program should output the largest value entered and the number of times it was entered before 0 is entered.
You can use the following snippet:
// part of reading the values from command line and
// putting them into this array is omitted
int[] array = ...;
int biggest = 0;
int occurance = 0;
for(int num : array) {
if(num > biggest) {
biggest = num;
occurance = 0;
}
if(num == biggest) {
occurance++;
}
}
System.out.printf("Biggest number %s occured %s times.%n", biggest, occurance);
As mentioned in the comment, I've omitted the part where you read the values from the command line, as that doesn't seem to be your problem.
Another solution which does the reading directly, and without the need of an array and all inside one loop:
Scanner scanner = new Scanner(System.in);
int biggest = 0;
int occurance = 0;
int num;
while (true) {
System.out.print("Enter a number: ");
// this may throw an Exception if the users input is not a number
num = Integer.parseInt(scanner.nextLine());
if(num == 0) {
// user entered a 0, so we exit the loop
break;
}
if(num > biggest) {
biggest = num;
occurance = 1;
} else if(num == biggest) {
biggest++;
}
}
System.out.printf("Biggest number %s occured %s times.%n", biggest, occurance);
Split your problem into two parts.
1. Find the largest value
int findLargest(int[] array) {
assert array.length > 0;
int result = array[0];
for (int element : array) {
if (element > result) {
result = element;
}
}
return result;
}
... and find it in the array
int countOccurences(int[] array, int value) {
int occurences = 0;
for (int element : array) {
if (element == value) {
occurences++;
}
}
return occurences;
}
Note that array should have at least one element;
If there is no requirements to use array only, you can use ArrayList for storing user inputs
List<Integer> list = new ArrayList<>();
while ((num = reader.nextInt()) != 0) {
System.out.println("Enter a positive integer (0 to quit): ");
num = reader.nextInt();
list.add(num);
}
Then if you are good with stream api, there is quite concise solution:
Map.Entry<Integer, Long> lastEntry = list.stream()
.collect(groupingBy(Function.identity(), TreeMap::new, counting()))
.lastEntry();
System.out.println(
"Largest value: " + lastEntry.getKey() +
" Occurrences: " + lastEntry.getValue() + " times");

min value in array keeps printing 0? Java (but no zero in the .txt file as a number)

my code below works fine except for the minimum value. I cannot figure out why the min value keeps printing zero? The numbers in the .txt file its pulling from are: 2 6 9 35 2 1 8 8 4. It's as if its not recognizing that numbers[0] = 2. However max works fine and its the same code just reversed? Any help is appreciated.
import java.io.*;
import java.util.*;
class Thirteen{
public static void main(String [] args) throws IOException{
int count = 0;
Scanner keys = new Scanner(System.in);
Scanner keystwo;
System.out.println("Please enter an input file name");
String filename = keys.next();
File infile = new File(filename);
keystwo = new Scanner(infile);
System.out.println("Please enter an output filename");
String outputfile = keys.next();
File outfile = new File(outputfile);
FileOutputStream outstream = new FileOutputStream(outfile);
PrintWriter display = new PrintWriter(outstream);
while(keystwo.hasNext()){
count++;
int numbers [] = new int [count];
int max = numbers[0];
int min = numbers[0];
int average = 0 ;
int sum = 0;
int counttwo = 0;
while(keystwo.hasNext()){
counttwo++;
//add numbers to array
for(int A = 0; A < numbers.length; A++){
numbers[A] = keystwo.nextInt();
sum = sum+ numbers[A];
}
// output numbers into txt file
for(int item : numbers){
display.println(item);
}
for(int C: numbers){
if(C < min){
min = C;
}
}
for(int B : numbers){
if(B > max){
max = B;
}
}
average = sum / counttwo;
}//end while
System.out.println("The total numbers in the array: " + counttwo );
System.out.println("The maximum value is: " + max);
System.out.println("The minimum value is: " + min);
System.out.println("The average value is: " + average);
display.println("The total numbers in the array: " + counttwo );
display.println("The maximum value is: " + max);
display.println("The minimum value is: " + min);
display.println("The average value is: " + average);
}//end first while
keystwo.close();
display.close();
}
}//end
It's because of your start value for min, which is going to be 0. Instead, set it to Integer.MAX_VALUE and you will get a proper min.
You are setting the minimum to 0:
min = numbers[0]; //numbers[0] is 0, since you haven't initialized it
You need to define the minimum as:
min = Integer.MAX_VALUE; //the largest possible value that int can have, so every other int is bigger
Also, it's advisable to do the same with your max. In this case it's not as important, but if you happen to have negative values in the .txt file, then max won't work either. To make sure that both minimum and maximum are correct, initialize the min as explained above, and the max to
max = Integer.MIN_VALUE;

How to Pass This Test Case?

I'm creating the program that determines the largest and smallest number is a series of numbers entered by the user. I've created several tests cases for my code and they all work out, but it fails the most simple test case. When the user inputs a single number. For instance, if the user sets the terminating value to be 25, then enters -1, and finally enters the terminating the value, the output should be
Largest: -1 and Smallest: -1. However, my code will output Largest: 0 and Smallest: -1 -- I why this happens (because I initialized the max value to be 0 before running the loop), but how can I fix this?
Here's my code...
Scanner scan = new Scanner(System.in);
// Declaration variables
double min;
double max = 0;
System.out.println("Enter terminating number: ");
double terminator = scan.nextDouble();
System.out.println("Enter a number: ");
double num = scan.nextDouble();
min = num;
if (num == terminator) {
System.out.println("There must be one number in the list.");
// break;
} else {
while (num != terminator) {
System.out.println("");
num = scan.nextDouble();
if ((num < min) && (num != terminator)) {
double temp = min;
min = num;
max = temp;
} else if ((num > min) && (num != terminator)) {
max = num;
} else {
max = min;
}
}
System.out.println("Largest: " + max);
System.out.println("Smallest: " + min);
}
Instead of initializing max = 0, do max = num just like you already do with min.
It's not clear why you're initializing max differently from min; when a single number has been entered, it's both the minimum and the maximum. Right now, the only code that modifies max is within the loop that reads numbers beyond the first, so the first number has no effect on it.

Java: min method for array with random ints and inputted count

The full assignment was to create a number of methods, e.g. getMode and getAverage, to compute stats for an array with randomly-generated numbers and user-inputted ceiling max, floor min, and sample size. All of my other methods seem to work, but every time I try returning the populated set's min value, I get 0--even if the inputted min was something higher.
Here's my code:
import java.util.Random;
public class Stats extends Main
{
int sampleSize;
double count;
double ave;
double sum;
int mode;
int evenCount;
int oddCount;
int countMatching;
int counter;
int target;
int match;
//Method: return the sample set's max value
public int getMax(int sampleSize, int[] data)
{
int max = Integer.MAX_VALUE;
max = data[0];
for(int i = 0; i < sampleSize; i++)
{
if (data[i] > max)
max = data[i];
}
return max;
}
//Method: return the min value
public int getMin(int sampleSize, int[] data)
{
int min = Integer.MIN_VALUE;
min = data[0];
for(int i = 0; i < sampleSize; i++)
{
if (data[i] < min)
min = data[i];
}
return min;
...
And the main program:
import java.util.Random;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
int stats;
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the Stats Program!");
System.out.println();
System.out.println("Enter sample size: ");
int sampleSize = keyboard.nextInt();
System.out.println();
System.out.println("What is the sample set's minimum? ");
int min = keyboard.nextInt();
System.out.println();
System.out.println("What is the sample set's maximum? ");
int max = keyboard.nextInt();
System.out.println();
Stats g = new Stats();
System.out.println("Main Menu");
System.out.println();
System.out.println("1) Get max value");
System.out.println("2) Get min value");
System.out.println("3) Get the mean");
System.out.println("4) Get the mode");
System.out.println("5) Get the count of even numbers");
System.out.println("6) Get the count of odd numbers");
System.out.println("7) Display the sample set");
System.out.println("8) Return the count of numbers in the sample set that match the input parameter");
System.out.println("9) Exit");
System.out.println();
stats = keyboard.nextInt();
//Constructor: use an RNG to generate sampleSize integers between minValue and maxValue. Store the numbers in an array named 'data'.
int[] data = new int[sampleSize];
for (int i = 0; i < sampleSize; i++)
{
Random rand = new Random();
data[i] = rand.nextInt((max - min + 1) + min);
}
while (stats != 9)
{
if (stats == 1)
{
g.getMax(sampleSize, data);
System.out.println("Max is: " + g.getMax(sampleSize, data));
System.out.println();
}
else if (stats == 2)
{
g.getMin(sampleSize, data);
System.out.println("Min is: " + g.getMin(sampleSize, data));
System.out.println();
}
...
Any idea why my program isn't returning appropriate min values (equal to or above what the user inputs)? The max seems to come out fine--sometimes it's below the user's inputted max, and most often it's equal. I've looked at other questions re. min/max and arrays with random numbers, but haven't been able to apply their solutions to my own problem.
Thanks in advance!
Look at this part of your code:
for (int i = 0; i < sampleSize; i++)
{
Random rand = new Random();
data[i] = rand.nextInt((max - min + 1) + min);
}
First wrong thing is that you create a new random number generator in each iteration. You should create it before the loop and just use it in the loop.
But that's the less important issue. The more important one is the way you run rand.nextInt(). Suppose your min is 3 and your max is 7. Then (max - min + 1) + min gives you 8. And this means you are calling rand.nextInt(8), which will give you a number such that 0 ≤ number < 8.
The method Random.nextInt(int n) gives you back a number such that 0 ≤ number < n. So if you want a number such that 3 ≤ number < 8, you'll need it to give you something between 0 and 5, and add that to 3. This means:
rand.nextInt(max - min + 1) + min;
It looks almost like what you wrote, but the extra pair of parentheses made all the difference. You can't just stick parentheses anywhere. The first parenthesis after the name of a method defines that method's parameters, and in your case, it caused the + min to become part of the parameter to nextInt.
One more thing: your class should not extend Main. They are not related in any way, your Stats is not a kind of Main, right?
Your min method seems to work well, maybe there is no number in your array that is less than 0.
This answer is not exactly to make your actual method work but is just a suggestion for a much easier way to do this.
You could use Collections and Commons Lang to find the min/max of an array and to convert a primitive array to a List.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang.ArrayUtils;
public class tst {
public static void main(String[] args) {
int[] arr = {1, 23, 43, 2, 4, 5, 5, 1, 2, 3};
List lst = Arrays.asList(ArrayUtils.toObject(arr));
System.out.println(Collections.min(lst));
System.out.println(Collections.max(lst));
}
}
This will output min:1 and max:43.
This is a good solution to consider if you are not forced to use primitive arrays and do everything by yourself.
Hope it helps :)
Please change you random nextInt function on how you get the random value.
it should be
data[i] = rand.nextInt(max - min + 1) + min;
not data[i] = rand.nextInt((max - min + 1) + min);

Categories