Return Arrays From Method as a Parameter - java

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

Related

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}

Find minimum pair of numbers whose sum is 15

I am trying to find the minimum pair of numbers to achieve sum of 15. I am creating new array for them and passing that array to method which is adding element of that array and generating true or false. array size will increase if method returns false.
public class FindMinimum {
static int arr[] = { 10, 3, 2, 13 };
static int numArr[] = new int[30];
static int arrLength = 2;
static boolean status = false;
static int number;
public static void main(String args[]) {
for (int i = 0; i < arrLength; i++) {
numArr[i] = arr[i];
}
if (checkPair(numArr)) {
System.out.println("Number found");
} else {
arrLength = arrLength + 1;
System.out.println("Increasing array length by one");
}
}
public static boolean checkPair(int x[]) {
for (int i = 0; i < x.length; i++) {
number = number + x[i];
}
if (number == 15) {
status = true;
for (int i : x) {
System.out.println(i);
}
} else {
status = false;
}
return status;
}
}
Expected result is minimum pair of addition that is "13 ,2"
If I understand correctly need to find minimum pair which always add to 15. If this is correct below code should solve it.
public static void main(String args[]) {
Arrays.sort(arr);
for (int i=0,j=arr.length-1;i<arr.length && j>=0;) {
if ((arr[i]+arr[j])<15) {
/*System.out.println(arr[i]+"-"+arr[last-i]);
break;*/
i++;
} else if ((arr[i]+arr[j])>15) {
j--;
} else {
System.out.println(arr[i]+"-"+arr[j]);
break;
}
}
}
import java.util.Scanner;
public class FindMinimumPair {
static Scanner sc = new Scanner(System.in);
static int userArr[];
static int numArr[]; // New array to take number / pairs from main array to compare with else numbers
// in the main array
static int arrLength = 1; // increase the array length of numArr if pair is more than 2 numbers
static boolean status = false; // check method returns true or false
static int sum;
public static void main(String args[]) {
System.out.println("Sum of pair should be ?");
sum = sc.nextInt();
System.out.println("Enter the lenght of an array");
int userArrLength = sc.nextInt();
userArr = new int[userArrLength];
System.out.println("Enter array integers upto " + userArrLength);
for (int i = 0; i < userArrLength; i++) {
userArr[i] = sc.nextInt();
}
// Loop to read numbers from main array
for (int i = 0; i < userArr.length; i++) {
// Defines the length of new array
numArr = new int[arrLength]; // initialize the new array
// Loop to add numbers into new array
for (int j = 0; j < arrLength; j++) {
numArr[j] = userArr[j]; // add numbers into new array
}
if (check(numArr)) { // call check method and pass new array in it
for (int a : numArr) { // if returns true then print that array (contains the pair)
System.out.print(a + " ");
}
System.out.print(userArr[numArr.length]); // print the last number which is the part of numArr
System.out.println(" is equals to " + sum);
} else {
System.out.println("Numbers not found");
}
arrLength = arrLength + 1; // increase the array length if false
}
}
public static boolean check(int number[]) {
int x = 0;
// Loop to make sum of all numbers of numArr (make it single number)
for (int j = 0; j < number.length; j++) {
x = x + number[j];
}
outer: for (int i = 0; i < number.length; i++) { // loop for elements in numArr array
for (int j = 0; j < userArr.length; j++) { // loop for given array elements
if (x + userArr[j] == sum) { // check each number of given array with the sum of numArr
status = true;
break outer; // breaks outer loop and returns true
} else {
status = false;
}
}
}
return status;
}
}

How Arrays.sort function works?

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.

How do i return arrays to compute total and find the largest value?

I am trying to return the sum of all the values in the the array while also trying to return the largest value to the main method, however, the program states that I have an error at return total and at return number. The error states, "Type mismatch: cannot convert from int to int[]."
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
int myArray[] = new int[10];
for(int i = 0; i <= myArray.length-1; i++ ) {
System.out.println("Enter Number: ");
int nums = number.nextInt();
myArray[i] = nums;
}
int [] sum = computeTotal(myArray);
System.out.println("The numbers total up to: "+sum);
int [] largest = getLargest(myArray);
System.out.println("The largest number is: "+largest);
}
public static int[] computeTotal(int myArray[]) {
int total = 0;
for (int z : myArray){
total += z;
}
return total;
}
public static int[] getLargest(int myArray[]) {
int number = myArray[0];
for(int i = 0; i < myArray.length; i++) {
if(myArray[i] > number) {
number = myArray[i];
}
}
return number;
}
The methods computeTotal and getLargestshould be changed the return types to int. Please refer this:
public static void main(String[] args) {
Scanner number = new Scanner(System.in);
int myArray[] = new int[10];
for(int i = 0; i <= myArray.length-1; i++ ) {
System.out.println("Enter Number: ");
int nums = number.nextInt();
myArray[i] = nums;
}
int sum = computeTotal(myArray);
System.out.println("The numbers total up to: "+sum);
int largest = getLargest(myArray);
System.out.println("The largest number is: "+largest);
}
public static int computeTotal(int myArray[]) {
int total = 0;
for (int z : myArray){
total += z;
}
return total;
}
public static int getLargest(int myArray[]) {
int number = myArray[0];
for(int i = 0; i < myArray.length; i++) {
if(myArray[i] > number) {
number = myArray[i];
}
}
return number;
}
Hope this help.
Probably in java8 there're easier way to get the max and sum.
int sum = Arrays.stream(new int[] {1,2, 3}).sum(); //6
int max = Arrays.stream(new int[] {1,3, 2}).max().getAsInt(); //3

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