Trying to swap min and max values in an array java - java

import java.util.Arrays;
public class Swap
{
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
System.out.print("What is the size of your array? ");
int myArray = console.nextInt();
int[] size = new int[myArray];
int sum = 0;
int max = 0;
int min = 100;
int temp = 0;
for (int i = 0; i < size.length; i++)
{
System.out.print("Array index " + (i) + ": ");
size[i] = console.nextInt();
sum += size[i];
if (size[i] > max) max = size [i];
if (size[i] < min) min = size [i];
}
System.out.println ("\nmaximum value is: " + max);
System.out.println ("\nminimum value is: " + min);
System.out.println (Arrays.toString(size));
temp = size[max];
size[max] = size[min];
size[min] = temp;
System.out.println (Arrays.toString(size));
}
}
I am having trouble swapping the min and max value in the array, I am able to find those values fine, and I even found a way to swap in with the temp variable, but I can't translate that into the array.

You're using max and min as array index to swap your values.That is not correct.Instead you've to keep min and max indexes,and use them to swap in the array. I suggest you to complete your code like that:
import java.util.Arrays;
public class Swap
{
public static void main(String args[])
{
Scanner console = new Scanner(System.in);
System.out.print("What is the size of your array? ");
int myArray = console.nextInt();
int[] size = new int[myArray];
int sum = 0;
int max = 0;
int min = 100;
int maxIndex=0;
int minIndex=0;
int temp = 0;
for (int i = 0; i < size.length; i++)
{
System.out.print("Array index " + (i) + ": ");
size[i] = console.nextInt();
sum += size[i];
if (size[i] > max){
max = size [i];
maxIndex=i;
}
if (size[i] < min) {
min = size [i];
minIndex=i;
}
}
System.out.println ("\nmaximum value is: " + max);
System.out.println ("\nminimum value is: " + min);
System.out.println (Arrays.toString(size));
temp = size[maxIndex];
size[maxIndex] = size[minIndex];
size[minIndex] = temp;
System.out.println (Arrays.toString(size));
}
}

Only the part for max and min.
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int iAtMax = -1;
int iAtMin = -1;
for (int i = 0; i < size.length; i++) {
if (iAtMax == -1 || max < size[i]) {
iAtMax = i;
max = size[i];
}
if (min <= size[i]) {
iAtMin = i;
min = size[i];
}
}
if (iAtMax != -1) {
int temp = size[iAtMax];
size[iAtMax] = size[iAtMin];
size[iAtMin] = temp;
}
You could initialize max and min so that an update in the loop always updates. Then you have to use <= max resp. >= min to update the indices. (See min above) or you can check whether there already is a max and min.
If the array is empty (or size 1) you cannot (resp. need not) swap.

Related

Passing array data to three methods to find average, max and minimum

I want to be able to display the output as three lines of text at the end but I'm getting a really weird output. So for example
"The average is z"
"Min Value: x"
"Max Value: y"
But I am getting this:
Please enter the size of the array:
3
Please enter array elements:
10
The average is 3.
Min Value: 0
Please enter array elements:
20
The average is 10.
Max Value: 20
Min Value: 0
Please enter array elements:
30
The average is 20.
Max Value: 20
Max Value: 30
package arrays;
import java.util.Scanner;
public class AssignmentArrays {
public static void main (String[] args) {
Scanner inputs = new Scanner(System.in);
System.out.println("Please enter the size of the array: ");
int size = inputs.nextInt();
int[] Array = new int[size];
for (int i = 0; i < size;) {
System.out.println("Please enter array elements: ");
int value = inputs.nextInt();
if (value >=100 || value <=0) {
System.out.println("Only values greater than 0 and less than 100 can be accepted.");
}
else {
Array[i] = value;
i++;
average(Array);
getMaxValue(Array);
getMinValue(Array);
}
}
}
public static int average(int[] Array)
{
int sum = 0;
int average;
for (int i = 0; i < Array.length; i++)
sum = sum+Array[i];
{
average=sum/Array.length;
System.out.println("The average is " +average +".");
return average;
}
}
public static int getMaxValue(int[] Array) {
int maxValue = Array[0];
for (int i = 1; i < Array.length; i++){
if (Array[i] > maxValue){
maxValue = Array[i];
System.out.println("Max Value: " + maxValue);
}
}
return maxValue;
}
public static int getMinValue(int[] Array) {
int minValue = Array[0];
for (int i = 1; i < Array.length; i++){
if (Array[i] < minValue) {
minValue = Array[i];
System.out.println("Min Value: " + minValue);
}
}
return minValue;
}
}
Thank you for all your help! I have finished my assignment.
example output: https://i.stack.imgur.com/Doy2d.png :)
package arrays;
import java.util.Scanner;
public class Array_1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner inputs = new Scanner(System.in);
System.out.println("Please enter the size of the array: ");
int size = inputs.nextInt();
int[] Array = new int[size];
for (int i = 0; i < size;) {
System.out.println("Please enter array elements: ");
int value = inputs.nextInt();
if (value >=100 || value <=0) {
System.out.println("Only values greater than 0 and less than 100 can be accepted.");
}
else {
Array[i] = value;
i++;
}
}
Average(Array);
int max;
max = Max(Array);
System.out.println("The maximum is " +max + ".");
int min;
min = Min(Array);
System.out.println("The minimum is " +min + ".");
}
public static void Average(int[] Array) {
int sum = 0;
int average;
for (int i = 0; i < Array.length; i++)
sum = sum+Array[i];
average=sum/Array.length;
System.out.println("The average is " +average +".");}
public static int Max(int[]Array) {
int max= Array[0];
for (int i = 1; i < Array.length; i++) {
if (Array[i] > max) {
max = Array[i];
}
}
return max;
}
public static int Min(int[]Array) {
int min = Array[0];
for (int i = 1; i < Array.length; i++) {
if (Array[i] < min) {
min = Array[i];
}
}
return min;

How to get the minimum and maximum value inside a user-defined array?

I want to get the minimum value and maximum value inside an array. After the user inputs n number of arrays, it will print the minimum and max value inside that array.
Here is an example output
Here is my code so far
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter array size: ");
int n = input.nextInt();
int [] array = new int[n];
int max = getMaxValue(array);
int min = getMinValue(array);
System.out.println("Enter " + n + " elements:");
for (int i = 1; i <= array.length; i++) {
array[i] = input.nextInt();
}
System.out.println("Max Value: " + max);
System.out.println("Min Value: " + min);
} catch (InputMismatchException e) {
System.out.println("INVALID INPUT >> PLEASE INPUT A NUMBER");
}
}
private static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 1; i < array.length; i++){
if (array[i] > maxValue){
maxValue = array[i];
}
}
return maxValue;
}
private static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 1; i < array.length; i++){
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
}
There are a few problems keeping this program from working:
getMinValue and getMaxValue should be called after your input loop
All 3 of your loops index starting from 1, they should start from 0
The input loop repeats until i <= array.length, but it should end at i < array.length
Problem 1 is that these method are called on the empty array.
Problems 2 and 3 will cause an ArrayIndexOutOfBoundsException.
Here's how the corrections would look in your code:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter array size: ");
int n = input.nextInt();
int [] array = new int[n];
System.out.println("Enter " + n + " elements:");
for (int i = 0; i < array.length; i++) {
array[i] = input.nextInt();
}
int max = getMaxValue(array);
int min = getMinValue(array);
System.out.println("Max Value: " + max);
System.out.println("Min Value: " + min);
} catch (InputMismatchException e) {
System.out.println("INVALID INPUT >> PLEASE INPUT A NUMBER");
}
}
private static int getMaxValue(int[] array) {
int maxValue = array[0];
for (int i = 0; i < array.length; i++){
if (array[i] > maxValue){
maxValue = array[i];
}
}
return maxValue;
}
private static int getMinValue(int[] array) {
int minValue = array[0];
for (int i = 0; i < array.length; i++){
if (array[i] < minValue) {
minValue = array[i];
}
}
return minValue;
}
}
There were 3 problems in your code which are as follows:
int max = getMaxValue(array) int min = getMinValue(array) are called in wrong places
when we initialize an int array the default value present in it is0.
So when you had call getMaxValue().
array[0] = 0 is compared with all rest of the values in the array (which are 0) and from all 0 is the maximum.
Same goes for getMinValue().
You have called the function getMaxValue() and getMinValue() without filling the array,with user input.
you should have used a for loop from 0 to array.length.
for(int index = 0 ; index < array.length ; index++){
array[index] = input.nextInt();
}
Has you would have noticed, I have index staring from 0 to array size.
what you did:
for (int i = 1; i <= array.length; i++) {
array[i] = input.nextInt();
}
this will cause ArrayIndexOutOfBoundException Because array indexing starts from 0 to n-1 and you allowed it to run till 1 to n.
Additionally, the finding of min and max can be done in one function.
by keeping the return type as an array.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
try {
System.out.println("Enter array size: ");
int n = input.nextInt();
int [] array = new int[n];
System.out.println("Enter " + n + " elements:"); // <-- changed
for (int i = 0; i < array.length; i++) {
array[i] = input.nextInt();
}
int max_min[] = getMax_MinValue(array); // <- notice this.
System.out.println("Max Value: " + max_min[0]);
System.out.println("Min Value: " + max_min[1]);
} catch (InputMismatchException e) {
System.out.println("INVALID INPUT >> PLEASE INPUT A NUMBER");
}finally {
input.close(); // close the scanner
}
}
// return type changed
private static int[] getMax_MinValue(int[] array) {
int maxValue = array[0];
int minValue = array[0];
for (int i = 0; i < array.length; i++){
if (array[i] > maxValue){
maxValue = array[i];
}
if(array[i] < minValue) {
minValue = array[i];
}
}
int min_max[] = {maxValue,minValue}; // min_max[0] has max value and min_max[1] has min value
return min_max;
}
Output:
Enter array size:
8
Enter 8 elements:
5
23
9
14
45
36
42
39
Max Value: 45
Min Value: 5
This is not an appropriate answer.
However as the implementations of getMaxValue & getMinValue have a slight flaw: empty arrays will raise an ArrayIndexOutOfBoundException.
And especially one might use the Stream classes.
private static int getMaxValue(int[] array) {
return IntStream.of(array).max().orElse(0);
}
private static int getMinValue(int[] array) {
return IntStream.of(array).min().orElse(0);
}
max and min yield an OptionalInt, and for empty arrays one may give a default (orElse).

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 :-)

Program will print largest number and smallest number

I have some trouble when I try to code a program.
double max = 0, min = 0;
int i;
double array[] = new double[10];
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Give the " + (i + 1) + " number");
array[i] = input.nextDouble();
}
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
for (i = 0; i < 10; i++) {
if (array[i] < min) {
min = array[i];
}
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
When I type 10 numbers that include one largest number and one smallest number,
the result is
The Max is : largest number
The Min is : 0.0
Always the Smallest I get the 0.0 whatever I type. No 2 I will type, No 4 I will type as a smallest number (always on separate launch), every time I get 0.0.
Your initial value for minimum is zero, and I assume your data has nothing that is less than zero.
Try setting your min initial value to Double.MAX_VALUE
you Initializing max and min before entering number into the array , when tring to find the max and the min , first enter the numbers to the array then compare them with the array[0].
second thing is that you dont need to for loops to check whether you need to change max or min , you can do it in one for loop .
try this :
double array[] = new double[10];
int i;
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Give the " + (i + 1) + " number");
array[i] = input.nextDouble();
}
double max = array[0], min = array[0];
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
if (array[i] < min) {
min = array[i];
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Two simple corrections:
You just have to set initialized min and max to some values in array. (e.g. array[0] for your problem)
there is no need to 3 for loops to find the min and max, just use one.
see below code:
int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;
System.out.println("Give the " + (1) + " number") ;
array[0] = input.nextDouble();
double max = array[0], min = array[0];
for (i = 1; i < 10; i++)
{
System.out.println("Give the " + (i+1) + " number") ;
array[i] = input.nextDouble();
if(array[i] > max)
max = array[i] ;
if (array[i] < min)
min = array[i];
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Your curly braces are not proper. You are ending the max loop before the SYSOUT.
double max = 0, min = 0;
int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;
for (i = 0; i < 10; i++)
{
System.out.println("Give the " + (i+1) + " number") ;
array[i] = input.nextDouble();
}
max = array[0];
min = array[0];
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
}
for (i = 0; i < 10; i++) {
if (array[i] < min) {
min = array[i];
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Run this. It will give the proper result.

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);

Categories

Resources