This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I have a program here that calculated the median of a certain amount of elements entered by a user; however I want to display the sorted list at the end of the program. You can see that I have sorted the elements but I can't think of any ways to display the sorted array at the end. Thanks in advance.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("How many numbers do you want a median of?");
int num = sc.nextInt();
System.out.println("Enter the numbers: ");
int [] array = new int [num];
for (int i = 0 ; i < array.length; i++ ) {
array[i] = sc.nextInt();
}
int median = median(array);
System.out.println(median+" is a median of entered numbers.");
}
public static int median (int [] array) {
int n = array.length;
int temp;
for (int i=0; i < n-1; i++) {
for(int j=1; j < n-i; j++) {
if (array [j-1] > array [j]) {
temp = array [j-1];
array [j-1] = array [j];
array [j] = temp;
}
}
}
int median;
if (n % 2 == 0) {
median = (array [n/2-1]);
}
else {
median = array [(n/2)];
}
return median;
}
}
In the function
public static int median (int [] array)
you pass array by reference. That means that the result of your sorting will be visible in main. You are sorting the array in place.
At the end of main, simply setup a loop that prints each element of the array.
If I understood correctly, you need just to print an array? After your int median(int []) method is called, the array is already sorted. You just print it like:
for(int i = 0; i < array.length; i++)
System.out.println(array[i]);
The array var is an Object (all arrays are objects in Java), so you send through the method call just the pointer to the object, not a copy of the object.
Hope that helps.
Related
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 3 months ago.
I am trying to sort an array in descending order. The size of the array comes from user input, and then the contents of the array come from user input. Then the array is passed to a function that sorts it. The issue is that, instead of printing a sorted array, it prints [I#5caf905d. Through print statements, I have pinpointed the problem to the scanner picking up [I#5caf905d as the final value from user input, coming right after all the correct inputs. I don't know where this value came from, and I also don't understand why it is printed by the function as if it were the entire array. All help is appreciated!
Here is my code. Input is: 5 10 4 39 12 2.
import java.util.Scanner;
public class LabProgram
{
public static void sortArray (int [] myArr, int arrSize)
{
int temp;
int i;
for (i = 0; i < arrSize - 1; i++)
{
if (myArr[i] < myArr[i + 1])
{
temp = myArr[i];
myArr[i] = myArr[i + 1];
myArr[i + 1] = temp;
}
}
System.out.println(myArr);
}
public static void main(String[] args)
{
Scanner scnr = new Scanner (System.in);
int [] myArr;
int arrSize;
int i;
arrSize = scnr.nextInt();
myArr = new int[arrSize];
for (i = 0; i < arrSize; i++)
myArr[i] = scnr.nextInt();
sortArray (myArr, arrSize);
}
}
You should use one of the simpliest sorting algorithm e.g. Selection Sort:
public static void selectionSortDesc(int[] arr) {
for(int i = 0; i < arr.length; i++) {
// k index with max value
int k = i;
// find k with max value
for(int j = i; j < arr.length; j++) {
if(arr[k] < arr[j])
k = j;
}
// swap current element with the max value
swap(arr, i, k);
}
}
private static void swap(int[] arr, int i, int j) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = arr[i];
}
By the way, you should not mix sorting and printing the array. It's better to split these parts.
This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 2 years ago.
static int[] fun1(int[] ar){
int[] auxarray = new int[ar.length];
int j = ar.length;
for (int i = 0; i < ar.length; i++) {
auxarray[j - 1] = ar[i];
j = j - 1;
}
return ar;
}
I have tried to implement a swap method to modify the same array, but it didn't work (tested with a void method and printed the result inside it: same as the initial array)
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.print("Please enter the size of the array: ");
size = input.nextInt();
array = new int[size]; //array and size are declared private static globally
for(int i = 0; i<size; i++){
array[i] = input.nextInt();
}
System.out.println("Your reversed string is:");
int[] reversedarray = fun1(array);
for(int i = 0; i < size; i++){
System.out.print(reversedarray[i] + ' ');
}
}
This returns 3334353637.. in all cases. Any solution or any idea on what I have done wrong?
error is in your fun1
You are returning a wrong array
What you can consider as an enhancement
You can simply swap the elements in the same array only iterate half the length of the array
static int[] fun1(int[] ar){
int size = ar.length, temp;
for (int i = 0; i < size/2; i++) {
temp = ar[i];
ar[i] = ar[size-1-i];
ar[size-1-i] = temp;
}
return ar;
}
You are returning the wrong array,ar instead of auxarray
Return auxarray instead of ar.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm running into an issue with my code and I can't figure out what's wrong. Basically the project I'm working on wants me to use static methods to perform a few different tasks using arrays. What I'm stuck on now, specifically, is printing my array.
The first thing I had to do was ask the user for the size of their array, and then have them input the data. After, I'm supposed to take the minimum value and maximum value, and then swap them. I'm pretty sure my code it right, but when I call the method I'm running into an error. This is what I have so far and I keep getting an error on lines 42 (beginning of swap method), 66 and 69:
public class ArraysStaticMethods {
static int[] array;
static public int arraySize;
static public int max;
static public int min;
//will create an array with user's input
private static int[] readInputs(int arraySize){
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the length of your array: ");
arraySize = keyboard.nextInt();
array = new int[arraySize];
for (int i = 0; i <= array.length - 1; i++) {
System.out.print("Enter an integer: ");
int num = keyboard.nextInt();
array[i] = num;
}
//to test
System.out.println("Your array before:");
System.out.println(Arrays.toString(array));
return array;
}
//finds index of max and min values and swaps them
public static int[] swap(int[] array){
max = array[0];
min = array[0];
int maxIndex = 0;
int minIndex = 0;
for(int index = 1; index < array.length; index++){
if (array[index] > max){
max = array[index];
maxIndex = index;
}
if (array[index]<min) {
min = array[index];
minIndex = index;
}
}
array[maxIndex] = min;
array[minIndex] = max;
System.out.println("Your array after:");
System.out.println(Arrays.toString(array));
return array;
}
public static void displayOutputs(){
readInputs(arraySize);
swap(array);
}
public static void main(String[] args) {
displayOutputs();
}
}
You're never actually assigning the result of readInputs() to array, since you are hiding it inside that method. You're returning the local version, but not using that one either.
Instead of
int[] array = new int[arraySize];
at line 17, just do
array = new int[arraySize];
OR you can change your displayOutputs() method to assign the result of readInputs() to array, before passing it to swap().
This question already has answers here:
Efficient swapping of elements of an array in Java
(13 answers)
Closed 6 years ago.
I will in this method descending order number integer
package sortarray;
public class start {
public static void main(String[] args) {
int [] numb={10,12,8,6,2};
sortarray(numb);
}
public static void sortarray(int [] input){
int max=input[0];
int [] sortmax=input;//i don't know how this array sortmax initialized first
for (int i=0;i<input.length;i++)
if(max<input[i]){
max=input[i];
sortmax[i]=max;//this array is not work
}
for (int j=0;j<sortmax.length;j++)
System.out.print(" "+sortmax[j]);
}
}
but into this method, (sortmax) is not work why?
I understand you want to keep some kind of history of max'es?
sortmax is just referencing to your input array, everything you do on sortmax you do on input. You need to do this:
int[] sortmax = new int[input.length];
instead of int[] sortmax = input;.
You can always use the Arrays.sort() for this, but if the goal is to learn sorting, a brute force (slow for large vectors) sorter could look like this:
public void sort(int[] array){
int[] tempArray = new int[array.length]
int max;
int index;
for(int k = 0; k < array.length; k++){
for(int i = 0; i < array.length; i++){
if(max < array[i]){
max = array[i];
index = i;
}
}
tempArray[k] = array[index];
array[index] = Integer.MIN_VALUE;
}
array = tempArray;
}
CONTEXT
I've been trying to fix this part of my program for a while now without much success. I essentially want to sort a String [] where each element is in the format: name:number (i.e. john:32).
PROGRESS
So far, my code splits each element and adds it to an equivalent int []. I then attempt to compare the elements in the int [] with selection sort and swap the elements in the String [].
PROBLEM
I'm getting java.lang.ArrayIndexOutOfBoundsException for my String [], which is called scores. Why is this?
scores = sort(scores); //ArrayIndexOutOfBoundsException here
public static String [] sort(String [] A) {
//equivalent array containing only integer part of score[i]
int[] tempArray = new int[A.length];
//populate tempArray
for(int i = 0; i < A.length; i++) {
//acquire numerical part of element
//ArrayIndexOutOfBoundsException here********
int num = Integer.parseInt(A[i].split(":")[1]);
//add to array
tempArray[i] = num;
}
/* Selection Sort: descendinG */
//compare elements (integer) in tempArray
for(int i = 0; i < tempArray.length; i++){
int index = i;
//search for integers larger for above index
for(int j = i+1; j < tempArray.length; j++ ){
if(tempArray[j] > tempArray[index]){
index = j;
}}
//swap elements in scores-array (String)
String temp = A[index];
A[index] = A[i];
A[i] = temp;
}
return A;
}
I agree with #shmosel
This can probably help you rooting out the bad apple
String scoreSplit[] = A[i].split(":");
if (scoreSplit.length() == 2){
int num = Integer.parseInt(A[i].split(":")[1]);
}
else{
system.out.println("Bad apple with "+ scoreSplit[0]); //some kind of logging
}