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().
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:
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;
}
I'm building a class that takes an array of numbers and has methods to output their min, max and average values as a string representation of the numbers. Here's my constructor for the class:
public RandomArray(int sizeOfArray)/*Constructor: gets array size and populates array with
random numbers*/
{
Random generator = new Random();
size = sizeOfArray;
for (int i = 0;i < size;i++)
{
numbers[i] = generator.nextInt(size + 1);
}
}
I'm getting the array out of bounds exception message when I test this class with a driver program and this constructor is the one causing it. I'm not able to understand how I'm going beyond the size of the array here. Please help! Thanks.
Edit - So just to clear up any confusion I'm posting the entire class below for reference:
public class RandomArray
{
/*A class that contains an array of random numbers and methods that output
the numbers' minimum, maximum and average values. Also includes a method
that outputs a string representation of the numbers.*/
int size, min, max;
String array;
int[] numbers = new int[size];
public RandomArray(int sizeOfArray)/*Constructor: gets array size and populates array with
random numbers*/
{
Random generator = new Random();
size = sizeOfArray;
for (int i = 0;i < size;i++)
{
numbers[i] = generator.nextInt(size + 1);
}
}
public int min_value()
{
for (int i = 0;i < size - 1;i++)
{
min = numbers[i];
for (int k = 1;k < size; k++)
{
if (numbers[k] < min)
{
min = numbers[k];
}
else
{
min = numbers[i];
}
}
}
return min;
}
public int max_value()
{
for (int i = 0;i < size - 1;i++)
{
max = numbers[i];
for (int k = 1;k < size; k++)
{
if (numbers[k] > max)
{
max = numbers[k];
}
else
{
max = numbers[i];
}
}
}
return max;
}
public double average()
{
double avg;
int sum = 0;
for (int i = 0;i < size;i++)
{
sum = sum + numbers[i];
}
avg = sum/size;
return avg;
}
public String toStringArray()//Outputs a string representation of all the numbers in the array
{
for (int i = 0; i < size;i++)
{
array = Integer.toString(numbers[i]) + " ";
}
return array;
}
}
You are initializing the array before you initialize the size variable. The size variable has a default value which is passed into the array constructor and sets the array to that size. to fix the problem just move the initialization of the array into the constructor after the size variable is set.
public class RandomArray
{
/*A class that contains an array of random numbers and methods that output
the numbers' minimum, maximum and average values. Also includes a method
that outputs a string representation of the numbers.*/
int size, min, max;
String array;
int[] numbers;
public RandomArray(int sizeOfArray) {
Random generator = new Random();
size = sizeOfArray;
numbers = new int[size];
for (int i = 0;i < size;i++)
{
numbers[i] = generator.nextInt(size + 1);
}
}
Also I've noticed a bug with the string output method. The array would be overwritten on each iteration. To solve this you must add the array to itself.
public String toStringArray()//Outputs a string representation of all the numbers in the array
{
for (int i = 0; i < size;i++)
{
array = array + Integer.toString(numbers[i]) + " ";
}
return array;
}
Your method is passed the size of the array, but the array definition is not present in your code.
If you need to create the array in the RandomArray method, do something like :
public int[] RandomArray(int sizeOfArray)/*Constructor: gets array size, create and populates array with random numbers*/
{
int[] randomArray = new int[sizeOfArray];
for (int i = 0;i < randomArray.length();i++)
{
numbers[i] = generator.nextInt(size + 1);
}
return randomArray;
}
As you did not provide the entire class code it is hard to see whats going on. However I think you did not initialize the array correctly. If you have a private variable for an array, you should still 'make space' for it, as follows.
private int[] myIntArray; // As class member
myIntArray = new int[3]; // To allocate memory for the array
See the following link, for more info regarding arrays.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
So I was tasked with asking the user to input 10 numbers into an array and then printing the numbers in order and reverse order using a tester class and not just the main.
I'm having problems with how to return the array that has been passed. Here's my code so far:
public class PrintIt
{
static int[] numbers = new int[10];
static int i = 0;
public static int PrintOrder()
{
System.out.println("\nList of numbers in order: \n");
for (int i = 0; i < numbers.length; i++)
{
System.out.println(numbers[i]);
}
return ;
}
public static int PrintReverse()
{
System.out.println("\nList of numbers in reverse order: \n");
for (int i = numbers.length - 1; i >= 0; i--)
{
System.out.println(numbers[i]);
}
return ;
}
}
and the tester class:
import java.util.Scanner;
public class PrintItTester
{
public static void main (String [] args)
{
Scanner input = new Scanner(System.in);
int i = 0;
int[] numbers = new int[10];
System.out.println("\nPlease input " + 10 + " numbers.");
for (i=0; i < numbers.length; i++)
{
PrintIt.numbers[i] = input.nextInt();
}
System.out.print(PrintIt.PrintOrder());
System.out.print(PrintIt.PrintReverse());
}
}
When I run the code with numbers[i] in the return it reads i as being 0 and only outputs the first element in the array. I've looked for a long time and I can't figure this out.
I know, obviously, that there needs to be something returned, but whatever I put doesn't work. For example, when I try to return the array, numbers[i], it only returns the first element because the variable has a value of 0.
You have several problems in your code:
The declaration int[] numbers = new int[10]; in the main is useless. Remove it, and replace numbers.length with PrintIt.numbers.length
Your methods return ints, not arrays. Make them void, and call them without System.out.print.
Remove the unnecessary return statements from the PrintOrder and PrintReverse methods.
This should fix the problem (demo).
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.