How to pass array to a java method - java

Here is my code:-
int[] numbers = new int[5];
for (int i = 0; i < numbers.length; i++)
{
System.out.println("Please enter number");
numbers[i] = input.nextInt();
}
System.out.println("Please enter your key");
int k =input.nextInt();
int Low=numbers[0];
int H=numbers[4];
Recursion(k,numbers ,Low , H);
}
how can i pass array to a method ?
i got error in the last line
i tried to make the method void and do all those things inside method but i got error ?

Java always passes arguments by values to method. In case of Arrays/Objects it passes by value as well but here in this case its value is a reference.
Following is the code snippet you can use to pass an array to a method and return it back again.
import java.util.HashMap;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int[] numbers = new int[5];
Scanner input = new Scanner(System.in);
for (int i = 0; i < numbers.length; i++) {
System.out.println("Please enter number");
numbers[i] = input.nextInt();
}
System.out.println("Please enter your key");
int k = input.nextInt();
int Low = numbers[0];
int H = numbers[4];
int[] recursiveResult = recursion(k, numbers, Low, H);
}
private static int[] recursion(int k, int[] numbers, int low, int h) {
// TODO Auto-generated method stub
// Some Operation
return numbers;
}
}

Related

Moving my for loop into a different method and connecting it to main Java

I'm making a program using Java that calculates the sum of the numbers entered; I figured this part out. However, I want to move the for loop into a different method called "Sum", but I keep getting errors and I don't know what to do.
Here is the code thats only in the Main method (it works perfectly fine):
import java.util.Scanner;
public class testing {
public static void main(String args[]){
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one: ");
for(int i=0; i<size; i++){
myArray[i] = in.nextInt();
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: "+ sum);
}
}
However, when I move the for loop into the method known as print, I get a bunch of errors:
import java.util.Scanner;
public class MPA4 {
public static void main(String[] args) {
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int [size];
int sum = 0;
System.out.println("Enter the elements of the array one by one: ");
}
print(sum);
}
public static void print (double []sum){
Scanner in = new Scanner(System.in);
int myArray[] = new int [size];
for(int i=0; i<size; i++){
myArray[i] = in.nextInt();
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: "+ sum);
}
}
Here are all the errors underlined in red:
I'm not sure what I'm doing wrong, any help would be much appreciated!
I changed it as below and it is working.
import java.util.Scanner;
public class MP4 {
public static void main(String[] args) {
System.out.println("Enter the size of the array: ");
Scanner in = new Scanner(System.in);
int size = in.nextInt();
int myArray[] = new int[size];
System.out.println("Enter the elements of the array one by one: ");
for (int i = 0; i < size; i++) {
myArray[i] = in.nextInt();
}
print(myArray, size);
}
public static void print(int[] myArray, int size) {
int sum = 0;
Scanner in = new Scanner(System.in);
for (int i = 0; i < size; i++) {
sum = sum + myArray[i];
}
System.out.println("Sum of the elements of the array: " + sum);
}
}

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

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

trouble calling a method in the same class java

I've been asked to do the following problem:
Implement a method that accepts an array of integers as input and returns the sum of all of the elements in the array as output.
this is what i have(the entire program):
import java.util.*;
public class sumArray{
public static void main(String[] args){
int sum1;
int sum2;
Scanner num = new Scanner(System.in);
int array[]=new int[5]; // Intilized array of size 5
for (int i=0;i<5;i++) // used for loop for user input
{
System.out.println("Please enter integer: ");
array[i]=num.nextInt(); // Assigned users value to array
}
System.out.print("The integers are: ");
for (int i=0;i<5;i++) // for loop to display values
{
System.out.print(array[i]+",");
}
}
public static int sum(int array[]) {
int sum1 = 0;
for (int i=0; i < array.length; i++)
sum1 = sum1 + array[i];
return sum1;
}
}
every time I try to call the method "sum" in the main method it gives me an error. I have tried every possible way I've seen on the internet to call the method. I'm not sure how I'm supposed to call it or if it is an issue because I have an array passed to the method.
Someone please help! and if you see that i've done something incorrectly, please let me know! thanks
public class sumArray{
public static void main(String[] args){
int sum1;
int sum2;
Scanner num = new Scanner(System.in);
int array[]=new int[5]; // Intilized array of size 5
for (int i=0;i<5;i++) // used for loop for user input
{
System.out.println("Please enter integer: ");
array[i]=num.nextInt(); // Assigned users value to array
}
System.out.print("The integers are: ");
for (int i=0;i<5;i++) // for loop to display values
{
System.out.print(array[i]+",");
}
// this works
System.out.println("sum is " + sum(array));
}
public static int sum(int array[]) {
int sum1 = 0;
for (int i=0; i < array.length; i++)
sum1 = sum1 + array[i];
return sum1;
}
}

I don't understand the specific variable type or type of utilization I should have when trying to get this array issue to work

I'm trying to get num to create multiple scenarios and get 10 inputed variables from the user which I will then utilize to print out. Once the variables are printed out I need to average them but I got stuck. Could you give me some tips?
final static int num = 10;
static Scanner scan = new Scanner(System.in);
public static void main (String[]args)
{
int[] list = new int [num];
for(int i = 0; i<=num; i++)
{
System.out.println("Enter an integer");
int num[] = scan.nextInt();
}
System.out.println(Print_it(list) / 10);
}
public static double Print_it(int[] list)
{
int number = 0;
for (int i = 0; i<10; i++)
{
number = number + list[i];
}
return(number);
}
The for loops should be using the correct test. 'i<=num' will cause an exception when i == num.
The "int num[] = scan.nextInt()" statement has illegal syntax.
You should be using 'num' wherever you currently use 10, and it should be named 'NUM' to conform to standard Java naming conventions for constants.
Print_it (which should be named more like 'printIt') is not printing anything.
Here is a better implementation:
import java.util.Scanner;
public class Main {
final static int NUM = 10;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
final int[] list = new int[NUM];
for (int i = 0; i < NUM; i++) {
System.out.println("Enter an integer");
list[i] = scan.nextInt();
}
printIt(list);
}
public static void printIt(int[] list) {
final int length = list.length;
int total = 0;
for (int i = 0; i < length; i++) {
final int n = list[i];
System.out.println(n);
total += n;
}
System.out.println("Average: " + (double)total / length);
}
}

Categories