Java array minimum element within for-loop - java

OK, I have been at it for a long time now. I have looked after similar problems here in stack-overflow and I still can't make it work. I need to find the maximum values within an array and minimum values. Trying to find the minimum is the problem. I have literately tried everything from writing separate methods and so on and still the output in 0. Here is what I have tried:
import java.util.Scanner;
class ArrayMin {
public static void main(String args[]) {
#SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
int a[] = new int[10];
int max = a[0];
int min = a[0];
System.out.println("Enter elements of array :");
for (int i = 0; i < 10; i++) {
a[i] = scanner.nextInt();
if (i == 9)
break;
}
for (int i = 1; i < a.length; i++) {
if (a[i] > max)
max = a[i];
else if (a[i] < min)
min = a[i];
}
System.out.println("Result is max is :" + (max)); //if I input 1-10, output is 10
System.out.println("Result is min is :" + (min)); //whatever number I input the output is always 0
}
}

When you declare your array, it's initialized to all zeroes. Then you assign the min to your first element, which is zero. Presumably all values are >= to 0 once they're assigned, so the min is still zero, but the max is correct.
Establish your max and min after the for loop where you assign input values to the array.
for (int i = 0; i < 10; i++) {
a[i] = scanner.nextInt();
if (i == 9)
break;
}
// Moved HERE.
int max = a[0];
int min = a[0];

Replace this.
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
...
for (int i = 0; i < a.length; i++) {
if (a[i] > max)
max = a[i];
if (a[i] < min)
min = a[i];
}
...

Related

print max num in an array in java

import java.util.Scanner;
public class maxnuminarray {
public static void main(String[] args) {
int temp;
System.out.print("please insert the size for array:");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
int[] nums = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("please insert your desired nums:");
nums[i] = input.nextInt();
}
for (int i = 1; i < size; i++)
for (int j = 0; j < size - i; j++)
if (nums[i] > nums[i + 1]) {
temp = nums[i];
nums[i] = nums[i + 1];
nums[i + 1] = temp;
}
System.out.print(nums[size - 1]);
}
}
Though it gets all the values for the array, it still doesn't print the max number which is the last num in the array.
The error I get for size=5:
Exception in thread "main": java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
at maxnuminarray.main(maxnuminarray.java:15)
Once you read in the values, iterate over the array like this.
int max = Integer.MIN_VALUE;
for (int n : nums) {
max = Math.max(max, n);
}
You're trying to get a value with an index that doesn't exist. For instance, at if (nums[i] > nums[i + 1]). Let's say you have 3 numbers in total, your array size will be 3, but your index starts at 0.
Index 0
Index 1
Index 2
5
10
21
If you try to get i + 1 when i = 2 you get an error since i = 3 does not exist.
Also, if you're trying to get the largest number out of the array, you only need to go through the array once.
int[] nums = new int[]{1, 10, 3};
int max = nums[0];
for (int i = 1; i < nums.length; i++)
if (max < nums[i])
max = nums[i];
Or you can use Collections with the Integer[] array.
int max = Collections.max(Arrays.asList(num));
If you are just looking to find the maximum in the array, #Nouredine's code should do the trick.
Your code is comparing consecutive numbers one by one through the array, and swapping them in a bubble sort kind of way.
But if you are really looking to move the maximum in the array to the last position in the array, you can use this piece of code.
The issue in your code is you are accessing 5th index in an array of size 5, where only 0,1,2,3,4 are allowed.
for (int i = 1; i < size; i++)
if (nums[i - 1] > nums[i]) {
temp = nums[i - 1];
nums[i - 1] = nums[i];
nums[i] = temp;
}
}
import java.util.Scanner;
public class maxnuminarray {
public static void main(String[] args) {
int temp;
System.out.print("please insert the size for array:");
Scanner input = new Scanner(System.in);
int size = input.nextInt();
int[] nums = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("please insert your desired nums:");
nums[i] = input.nextInt();
}
int max = nums[0];
for (int i = 1; i < size; i++)
if(max < nums[i])
max = nums[i];
}
System.out.println("Max " + max);
}

Analasys program max and min and mode and graphing histogram

Hi in my program I want to display the average number, largest number, lowest number, and the mode in the array. So far only my average works and my methods for min and max both = the first number I enter. For example if I say I want to enter 3 numbers and I put 12, 15,and 6. The min and max will both output 12 since it's the first number entered and that's wrong so please help. Here's my code.
int amount;
System.out.println(" Enter the amount of numbers you would like to enter: ");
amount = scan.nextInt();
int [] arr = new int [amount];
int outcome = 1;
for (int i = 0; i < arr.length; i++){
System.out.println("Enter a number 1 through 50");
outcome = scan.nextInt();
arr [i] = outcome;
}
System.out.println(" ");
System.out.println( " The average is" );
System.out.println(average(arr));
System.out.println(" ");
System.out.println( " The lowest value in the array is " );
System.out.println(min(arr));
System.out.println(" ");
System.out.println( " The largest value in the array is " );
System.out.println(max(arr));
System.out.println(" ");
}
public static double average ( int [] arr) {
double sum = 0;
int value = arr.length;
for ( int i = 0; i < arr.length; i++){
sum += arr [i];
}
sum = sum / value;
return sum;
}
public static int min (int [] arr) {
int shortest = 0;
int smallest = 100;
int length = arr.length;
for ( int i = 0; i < arr.length; i ++ ) {
if ( length < smallest)
shortest += arr[i];
smallest = arr.length;
}
return shortest;
}
public static int max (int [] arr) {
int largest = 0;
int biggest = 0;
int length = arr.length;
for ( int i = 0; i < arr.length; i ++ ) {
if ( length > largest)
biggest += arr[i];
largest = arr.length;
}
return biggest;
}
}
This would be pretty straightforward. The reason both your min and max methods return 12 is because you set both largest and smallest to arr.length and thus immediately stop the for-loop after only one run. Also, there are far easier implementations for this kind of problem. Try doing something along these lines:
public int getMax(int[] arr)
{
int max = arr[0]; //To have a baseline
for(int i = 1; i < arr.length; i++)
{
if(arr[i] > max)
{
max = arr[i];
}
}
return max;
}
public int getMin(int[] arr)
{
int min = arr[0]; //To have a baseline
for(int i = 1; i < arr.length; i++)
{
if(arr[i] < min)
{
min = arr[i];
}
}
return min;
}
This is both far more readable and easier to execute. Just ask if you have any questions :-)

User input and array analysis

I have a CountInRange Java program that accepts an integer array, also asks the user to input the minimum and maximum value. Then outputs the count of elements from the array that fall between the minimum and maximum values.
Why is it not working?
int [] num ={1, 21, 34, -54, 12, 15, 35};
int count = 0;
int i = 0;
int j = 0;
int min;
int max;
System.out.println("Enter minimum: ");
min = input.nextInt();
System.out.println("Enter maximum: ");
max = input.nextInt();
for (i = 0; i < num.length; i++){
for (j = 0; j < num.length; j++) {
if (num[i] >= min || num[i] <= max) {
count++;
}
}
}
System.out.println("There are "+count+" elements whose values fall between the maximum and the minimum value");
}
The inner for loop is not needed in the least and you should get rid of it.
Also you need to make the conditional and instead of or so it should look something like this:
for (i = 0; i < num.length; i++){
if (num[i] >= min && num[i] <= max) { //AND INSTEAD OF OR
count++;
}
}
You were testing if the number is >= min OR num <= max which means if one of these is true it will return true so if your limit was min = 4 and max = 5 and num = 12 it would return true because 12 >= 4.

How am I able to display the largest and the smallest number from the array of the user's input?

Can somebody help me what's wrong with my codes I'm having trouble with the displaying the largest and the smallest part in the array. Sorry I'm completely new with java. Thanks a bunch
package problem6;
import java.util.Scanner;
public class Problem6 {
public static void main(String[] args) {
int input;
int min = 0;
int max = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many numbers do you want to enter?");
input = keyboard.nextInt();
int array[] = new int[input];
for (int i = 0 ; i < array.length; i++ ) {
System.out.println("Enter number: ");
array[i] = keyboard.nextInt();
}
{
if (input > max)
{
max = input;
}
else if (input <= min)
{
min = input;
}
}
System.out.print("\nLargest: " + max);
System.out.print("\nSmallest:" + min);
}
}
Post you read the value, you need to iterate over the array and try to use your logic of mix/max comparison like:
int min = Integer.MAX_VALUE;//change your assignment of 0 as numbers can be negative
int max = Integer.MIN_VALUE;
for (int number : array) {//use separate for loop or use the same for loop to which you add numbers in array.
if (number > max) {
max = input;
}
else if (number < min) {
min = input;
}
}
With using the same for loop:
int min = Integer.MAX_VALUE;//change your assignment of 0 as numbers can be negative
int max = Integer.MIN_VALUE;
for (int i = 0 ; i < array.length; i++ ) {
System.out.println("Enter number: ");
array[i] = keyboard.nextInt();
if (array[i] > max) {
max = array[i];
}
else if (array[i] < min)
{
min = array[i];
}
}
The errors were
an extra pair of braces, and 2. comparing input-size instead of array elements with min and max.
The probable working code is shown below :-
package problem6;
import java.util.Scanner;
public class Problem6 {
public static void main(String[] args) {
int input;
int min = 0;
int max = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("How many numbers do you want to enter?");
input = keyboard.nextInt();
int array[] = new int[input];
for (int i = 0 ; i < array.length; i++ ) {
System.out.println("Enter number: ");
array[i] = keyboard.nextInt();
if (array[i] >= max)
{
max = array[i];
}
else if (array[i] <= min)
{
min = array[i];
}
}
System.out.print("\nLargest: " + max);
System.out.print("\nSmallest:" + min);
}
}
You can even try this.
int max=array[0], min=array[0];
for(int x=0; x<array.length; x++){
max = array[x]>max?array[x]:max;
min = array[x]<min?array[x]:min;
}
Set the first array element as min and max first.
You need to have this code:
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int i = 0 ; i < array.length; i++ ) {
if (array[i]> max)
{
max = array[i];
}
else if (array[i] <= min)
{
min = array[i];
}
}
System.out.print("\nLargest: " + max);
System.out.print("\nSmallest:" + min);

Code is printing out largest subscript of the array when it should be printing maximum and minimum

I'm trying to print the largest and smallest values on an array, as well as their respective subscripts. I'm running into a problem where my code, though printing the highest and lowest values of the array, is returning the largest subscript (regardless of value) for both maximum and minimum arrays. The problem lies somewhere in the for loops, below.
int max = arrayOfNumbers[0];
int min = arrayOfNumbers[0];
int indexMax = 0;
int indexMin = 0;
for (int i = 0; i < arrayOfNumbers.length; i++) {
if (max < arrayOfNumbers[i])
max = arrayOfNumbers[i];
indexMax = i;
}
for (int i = 0; i < arrayOfNumbers.length; i++) {
if (min > arrayOfNumbers[i])
min = arrayOfNumbers[i];
indexMin = i;
This should work:
int max = arrayOfNumbers[0];
int min = arrayOfNumbers[0];
int indexMax = 0;
int indexMin = 0;
for (int i = 0; i < arrayOfNumbers.length; i++) {
if (max < arrayOfNumbers[i]) {
max = arrayOfNumbers[i];
indexMax = i;
}
}
for (int i = 0; i < arrayOfNumbers.length; i++) {
if (min > arrayOfNumbers[i]) {
min = arrayOfNumbers[i];
indexMin = i;
}
}
You forgot to put both lines after the ifs into braces. Each time the code inside the loops executed, the current index had been written into both indexMax and indexMin, and that's why after the loops finished, they contained the "largest subscript".

Categories

Resources