How Arrays.sort function works? - java

I am new to java programming and i am trying to sort arrays using Arrays.sort() function. After using Arrays.sort(array),I am printing the final sorted array.
For example:
Input : 1 3 2 4
Output comes as : 0 0 0 0.
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
public class TestClass {
public static final int MAX_SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n,temp,count;
int[] array = new int[MAX_SIZE];
n = input.nextInt();
for(int i = 0 ; i < n ; ++i) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for(int i = 0 ; i < n ; ++i) {
System.out.print(array[i]+" ");
}
}
}

You have initialized you array to hold 20 integers but you input only 5. Hence the first 15 elements will be 0 followed by the numbers you have inputted once the array is sorted.
To fix the issue you can initialize the array with n instead of MAX_SIZE as shown below:-
n = input.nextInt();
int[] array = new int[n];

Set the size of the array to match what your input should be, not to the maximum allowed size:
public class TestClass {
public static final int MAX_SIZE = 20;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n, temp, count;
n = input.nextInt();
if (n > MAX_SIZE) {
//handle error somehow
}
int[] array = new int[n];
for (int i = 0; i < n; ++i) {
array[i] = input.nextInt();
}
Arrays.sort(array);
for (int i = 0; i < n; ++i) {
System.out.print(array[i] + " ");
}
}
}

When you initialize an array in Java it gets default value of 0 for primitive int:
int[] array = new int[MAX_SIZE];
The fact that you are not seeing your desired input of 1,2,3,4 is a separate problem with your Scanner code.

Related

Return Arrays From Method as a Parameter

public static void find( int[] numbers) {
int[] range = new int[5];
for(int i=0; i<numbers.length; i++)
{
if(numbers[i]>=10 && numbers[i] <= 20)
{
range[i]=range[i]+numbers[i];
}
}
}
I want to write a method that find the numbers between 10 and 20 in a array and assign them to another array. this is expected and this is what I got.
{ 0 0 0 } are between 10 - 20 how can I fix this ?
public static void read( int[] numbers) {
Scanner input = new Scanner(System.in);
for( int i=0; i<numbers.length;i++)
{
System.out.print("Number["+i+"] => ");
numbers[i] = input.nextInt();
}
input.close();
}
This is the read() method that reads numbers from user and assign to an array.
public static void print( int[] numbers, int[]range) {
System.out.println("Number = { "+ numbers[0]+" "+numbers[1]+" "+numbers[2]+" "+numbers[3]+" "+numbers[4]+" }");
System.out.println("{ "+range[0]+" "+range[1]+" "+range[2]+" } "+" are between 10 - 20 ");
}
And this is the print(x,y) method that prints the numbers and range arrays.
My main method is:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[5];
read( numbers );
int[] range = new int[5];
find( numbers );
print(numbers, range);
The numbers array must include 3 numbers between 10-20.
Solution
Change the return type of your function to int[]
precalculate the size of your ranges array with counter
store the values which are in your range in the range array
return the range array
Note dont use the i running variable also for your range array, if you do so when not every value is in your range the result array will have gaps meaning values with the value of zero.
In the read function you should return the readed-in values to use it then in your find function
public static int[] read(int size) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[size];
for(int i=0; i < size; i++)
{
System.out.print("Number["+(i+1)+"] => ");
numbers[i] = input.nextInt();
// to remove the new line character
input.nextLine();
}
input.close();
return numbers;
}
import java.util.*;
public class MyClass {
public static void main(String args[]) {
int[] values = MyClass.read(10);
int[] result = MyClass.find(values);
// result is now the return value of the find method
// you can parse it now to another method of your choice
System.out.println(Arrays.toString(result));
}
public static int[] find(int[] numbers) {
int counter = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] >= 10 && numbers[i] <= 20) {
counter++;
}
}
int[] range = new int[counter];
int counter2 = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] >= 10 && numbers[i] <= 20) {
range[counter2] = numbers[i];
counter2++;
}
}
return range;
}
public static int[] read(int size) {
Scanner input = new Scanner(System.in);
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
System.out.print("Number[" + (i+1) + "] => ");
numbers[i] = input.nextInt();
// to remove the new line character
input.nextLine();
}
input.close();
return numbers;
}
}
1. You need to return the 'range' array in the 'find' function because otherwise, it isn't accessible.
2. You need another variable say 'j' to point to the indices of the 'range' array.
The same variable can't be used for both the 'numbers' array and the 'range' array.
3. It will be better to pass the size of the 'numbers' array through the 'read' function and then read the array using the 'read' function.
Functions:
find() function:
public static int[] find( int[] numbers) {
int[] range = new int[5];
int j = 0;
for(int i=0; i<numbers.length; i++)
{
if(numbers[i]>=10 && numbers[i] <= 20)
{
range[j]=range[j]+numbers[i];
j++;
}
}
return range;
}
read() function:
public static int[] read( int n) {
int[] numbers = new int[n];
Scanner input = new Scanner(System.in);
for( int i=0; i<numbers.length;i++)
{
System.out.print("Number["+i+"] => ");
numbers[i] = input.nextInt();
}
input.close();
return numbers;
}
print() function[Remains same]:
public static void print( int[] numbers, int[]range) {
System.out.println("Number = { "+ numbers[0]+" "+numbers[1]+" "+numbers[2]+" "+numbers[3]+" "+numbers[4]+" }");
System.out.println("{ "+range[0]+" "+range[1]+" "+range[2]+" } "+" are between 10 - 20 ");
}
Main function accordingly:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] numbers = read(n);
int[] range = find(numbers);
change(numbers);
print(numbers, range);
}

java arrays random scanner class

I am stuck in my beginner java course and am trying to get my array to print out with the user's input on randomly selected index's. With the code I have so far it will only print out an index with all 0's such as this "{0, 0, 0, 0, 0, 0}"
Here is the prompt:
Create an empty int array of size 6.
Create a method called populateArray that will pass an array, use random class to choose a random index and prompt the user to enter a value, store the value in the array. Note: Generate 6 random index numbers in an attempt to fill the array.
Create a method called printArray that prints the contents of the array using the for each enhanced loop.
Here is my code:
public class ChangeUp {
public static void main(String[] args) {
int[] array = new int[6];
System.out.println("Please enter 6 numbers to add to a list.");
populateArray(array);
printArray(array);
}
public static void populateArray(int[] array) {
Random r = new Random();
Scanner input = new Scanner(System.in);
int rArray = r.nextInt(array.length);
int i = 0;
for (i = rArray; i <= array.length; i++) {
i = input.nextInt();
}
}
public static void printArray(int[] array) {
System.out.print("{" + array[0]);
for (int i = 1; i < array.length; i++) {
System.out.print(", " + array[i]);
}
System.out.println("}");
}
}
for (int i = rArray; i <= array.length; i++) {
i = input.nextInt();
}
Here is your problem. You assign the value(s) to i, not to elements of the array.
Turn:
i = input.nextInt();
into:
array[i] = input.nextInt();
You do not change any values of array. You can do it with array[i] = value where i is index which value you want to change.
Here is example of what populateArray would looks like:
public static void populateArray(int[] array) {
Random r = new Random();
Scanner input = new Scanner(System.in);
int i = r.nextInt(array.length);
array[i] = input.nextInt();
}
You did not assigne input values to the array: array[i] = ....
I would recommend you to not randomly insert an elements, but just fill an array and then shuffle it.
public class ChangeUp {
public static void main(String... args) {
int[] arr = new int[6];
System.out.format("Please enter %d numbers to add to a list:\n", arr.length);
populateArray(arr);
printArray(arr);
}
public static void populateArray(int... arr) {
Scanner scan = new Scanner(System.in);
List<Integer> tmp = new ArrayList<>(arr.length);
for (int i = 0; i < arr.length; i++)
tmp.add(scan.nextInt());
Collections.shuffle(tmp);
int i = 0;
for (int val : tmp)
arr[i++] = val;
}
public static void printArray(int... arr) {
System.out.println(Arrays.stream(arr)
.mapToObj(String::valueOf)
.collect(Collectors.joining(", ", "{", "}")));
}
}
Demo:
Please enter 6 numbers to add to a list:
1
2
3
4
5
6
{4, 3, 1, 5, 2, 6}

Why is using an object array a better idea in this code?

Our assignment was to solve the Hackerrank question on arraylist without using 2D arrays or lists. Basically, you would need to input multiple arrays of different sizes and display an element based on the input of (array number, position). My implementation seemed to work just fine for my test cases but failed 4/6 of Hackerrank's test cases. Our lecturer's code (of course) worked perfectly. But what I fail to understand, is advantage of his approach:
My Code ::
import java.io.PrintStream;
import java.util.Scanner;
class arraylist {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int NoOfLines = sc.nextInt();
int[] input = new int[20000];//To store all input arrays one after the other in one 1D array.
int[] index = new int[NoOfLines];//Starting positions of each array input.
int[] NoOfArrayElements = new int[NoOfLines];//Sizes of each corresponding input array.
int position = 0;
int count = 0;
int arrayelementpos = 0;
//Store the input and note the size of each array and the index position.
for (int i = 0; i < NoOfLines; i++) {
int arrarLength = sc.nextInt();
NoOfArrayElements[arrayelementpos++] = arrarLength;
index[position++] = count;
for (int j = 0; j < arrarLength; j++)
input[count++] = sc.nextInt();
}
//Code to input queries (array no, element position)
int NoOfQueries = sc.nextInt();
int[] result = new int[NoOfQueries];
int pos = 0;
for (int i = 0; i < NoOfQueries; i++) {
int arrayNo = sc.nextInt();
int element = sc.nextInt();
if ((arrayNo > NoOfLines) || element > NoOfArrayElements[arrayNo - 1]) {
System.out.println("ERROR!");
continue;
}
pos = index[arrayNo - 1] + element - 1;
System.out.println("THE ELEMENT IS ::" + input[pos]);
}
}
}
My lecturer's code ::
import java.io.*;
import java.util.*;
public class arraylistsolved {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Object [] store=new Object[n];
for(int i=0; i<n;i++){
int d=sc.nextInt();
int [] ar=new int[d];
for(int j=0;j<d;j++) {
ar[j]=sc.nextInt();
}
store[i]=ar;
}
int q=sc.nextInt();
for(int i=0;i<q;i++){
int array=sc.nextInt()-1;
int element=sc.nextInt()-1;
Object obj=store[array];
int [] retrieve = (int []) obj;
if(array>n||element>retrieve.length-1)
System.out.println("ERROR!");
else
System.out.println(retrieve[element]);
}
}
}
As mentioned, both the codes are working for small test cases, but mine breaks down for very large ones for some reason. You can try copy-pasting the code here: https://www.hackerrank.com/challenges/java-arraylist/problem

Why is the scanner function not working?

So this code takes the value of n and returns a list of divisors as well as the total number of divisors. If I remove the Scanner declaration and its assignment to int n and simply give int n a value, the code runs perfectly.
However, as it is, it returns this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Program.main(Program.java:25)
I have no idea what the problem is.
import java.util.Scanner;
public class Program{
static int n;
static int x = 1;
static int [] arr = new int[n];
static int q = 0;
static int g = 0;
static int p = 1;
static int count;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
while(x <= n){
arr [q] = p; //assigns value to each array index
g = n%arr[q]; // stores value of remainder
q++;
p++;
x++;
if (g == 0){ //counts and displays each time remainder = 0
count++;
System.out.println(q);
}
}
System.out.println(count + " Divisors");
}
}
The size of arr is declared when n still holds no value(before the size is inputted). Do this:
import java.util.Scanner;
public class Program {
static int n;
static int x = 1;
static int [] arr; //no size set
//...
//Other variables
//...
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
arr = new int[n]; //Now the size is set to the inputted number.
while(x <= n) {
//...
//Other code to find divisors
//...
}
}
}
You need to name the size of arr after you input the n, otherwise the size is set to 0, causing the ArrayIndexOutOfBoundsException.
This line:
arr[q] = p;
Is what actually caused the error. arr[q] couldn't hold a value, because there was no arr[q]. the array had no size, so it couldn't hold any members.
static int n;
...
static int [] arr = new int[n];
You do not give n a value, so it defaults to 0. Therefore, you initialize arr as an array of length 0. That is why you get Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0. It's because your array is size 0, so even index 0 is out of bounds of the array.
If you don't know n until you read from the Scanner you should change your code to:
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int [] arr = new int[n];
...
}
Change your while condition from
while(x <= n)
to
while(x < n)
< means strict less than, so you start from 1, and not get the out of bounds
Edit:
Also as #CodingNinja said, you have to change the and define a int value to the size of the array, by default is 0:
public static void main(String[] args){
static int n;
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
static int [] arr = new int[n];
while(x <= n){
arr [q] = p; //assigns value to each array index
g = n%arr[q]; // stores value of remainder
q++;
p++;
x++;
if (g == 0){ //counts and displays each time remainder = 0
count++;
System.out.println(q);
}
}
System.out.println(count + " Divisors");
}

Random Shuffling an array of integers in Java [duplicate]

This question already has answers here:
Random shuffling of an array
(31 answers)
Closed 6 years ago.
This is my first time with arrays.
I should prompt the user to enter 5 array values and then display them in random order.
I am quite confused, since it's my first time doing this.
Anyway, my code is here.
import java.util.*;
public class Test {
public static void main(String[] args) {
int myArray[] = new int[5];
System.out.println("Please enter 5 numbers: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length - 1; i--) {
int j = (int) (Math.random() * (i + 1));
myArray[i] = input.nextInt();
System.out.println("The numbers are: ");
System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
System.out.println(myArray[3]);
System.out.println(myArray[4]);
int temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
System.out.println("The numbers, shuffled, are: ");
System.out.println(myArray[0]);
System.out.println(myArray[1]);
System.out.println(myArray[2]);
System.out.println(myArray[3]);
System.out.println(myArray[4]);
}
}
}
Thank you everyone for your support.
A - Explanation
Let's say you take the input values in order as {'1','2','3','4','5'}. What shuffling is corrupting the order randomly, so you have to change the position of elements randomly.
In the demo code,
swapArrayElement swaps the elements those that positions are passed as parameters.
getRandom returns a random value between 0 and the range which passed to the method as a parameter.
shuffleArray shuffles the array by changing the positions of elements randomly. Please notify that there is an additional boolean isShuffled[] array and it is boolean because we have to keep the track of positions whether they are shuffled or not.
isArrayShuffled method, checks that if all positions are shuffled or not.
B - Demo Code
import java.util.Scanner;
public class Test {
public static final int ARRAY_LENGTH = 5;
public static void main(String[] args) {
int myArray[] = new int[ARRAY_LENGTH];
Scanner input = new Scanner(System.in);
System.out.println("Please enter 5 numbers: ");
for(int i = 0; i < myArray.length; i++)
myArray[i] = input.nextInt();
System.out.println("\nThe numbers are: ");
printIntArray(myArray);
shuffleArray(myArray);
System.out.println("\nThe numbers, shuffled, are: ");
printIntArray(myArray);
input.close(); // no memory leaks!
}
// method for printing array
public static void printIntArray(int[] array) {
for(int i = 0; i < array.length; i++)
System.out.printf("%2d ", array[i]);
System.out.printf("%n"); // use %n for os-agnostic new-line
}
// method for shuffling array
public static void shuffleArray(int[] array) {
int range = array.length;
boolean isShuffled[] = new boolean[range]; // store which positions are shuffled
while(!isArrayShuffled(isShuffled)) {
int positionSrc = getRandom(range);
int positionDst = getRandom(range);
swapArrayElement(array, positionSrc, positionDst);
isShuffled[positionSrc] = true;
isShuffled[positionDst] = true;
}
}
public static int getRandom(int maxRange) {
return (int)(Math.random()*maxRange);
}
public static void swapArrayElement(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static boolean isArrayShuffled(boolean[] isShuffled) {
for(int i = 0; i < isShuffled.length; i++)
if(isShuffled[i] == false)
return false;
return true;
}
}
C - Demo Output
Please enter 5 numbers:
1 2 3 4 5
The numbers are:
1 2 3 4 5
The numbers, shuffled, are:
4 2 5 1 3
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class Test {
public static void shuffle(int[] arr) {
Random rnd = ThreadLocalRandom.current();
for (int i = arr.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
int t = arr[index];
arr[index] = arr[i];
arr[i] = t;
}
}
public static void main(String[] args) {
int myArray[] = new int[5];
System.out.println("Please enter 5 numbers: ");
Scanner input = new Scanner(System.in);
for (int i = 0; i < myArray.length; i++) {
System.out.println("Enter " + (i + 1) + ". number: ");
myArray[i] = input.nextInt();
}
System.out.println("The numbers are: ");
for (int j2 = 0; j2 < myArray.length; j2++) {
System.out.println(myArray[j2]);
}
shuffle(myArray);
System.out.println("The numbers, shuffled, are: ");
for (int j2 = 0; j2 < myArray.length; j2++) {
System.out.println(myArray[j2]);
}
}
}

Categories