So I have to input a list of numbers stored in an array, specify how many int values that are to be stored in the array, and print out the original array plus the list of integers with the maximum and minimum values swapped.
I am not allowed to use library other than java.util.Scanner
So, if I input {1 2 3 4 5 6 7}, I'm supposed to get {7 2 3 4 5 6 1}. Everything in my code works except the swapping part, but I've managed to find the maximum and minimum values, I just don't know how to deal with them. Here's what I got:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter array size (minimum size 7)? ");
int size = in.nextInt();
int [] array = new int [size];
System.out.print("Enter " + size + " distinct integer values to store in the array: ");
int i = 0;
for (i = 0; i < size; i++) {
array[i] = in.nextInt();
}
System.out.println();
System.out.println("Original array:");
for (i = 0; i < size; i++) {
System.out.print(array[i]);
System.out.print("\t");
}
System.out.println(" ");
System.out.println(" ");
System.out.println("Array after swapping the smallest and largest:");
int large = array[0];
int small = array[0];
for (i = 0; i < size; i++) {
if (array[i] > large) {
large = array[i];
}
}
for (i = 1; i < size; i++) {
if (array[i] < small) {
small = array[i];
}
}
int temp = small;
large = large;
large = temp;
for (i = 0; i < size; i++) {
System.out.print(array[i]);
System.out.print("\t");
}
}
int big = 0;and this loopfor (i = 0; i < size; i++) {you never actually change the value ofbiganywhere, so it just stays at0so when you swap [0] for [0] usingtempit remains as 1. Rethink that loop, and assignbigcorrectly any you will solve your issue.array[small] = ishould change tosmall = ias well as your other change wherearray[big] = ishould change tobig = iArrays.sort(array); int tmp = array[array.length - 1]; array[array.length - 1] = array[0]; array[0] = tmp;.