Reputation: 11
How do I pass arrays as parameters and then return arrays from the user defined methods to the main method. Here is part of my code. public static void main(String[] args) { int size, i=0, ch;
//Initializing scanner declaring arrays
Scanner scan= new Scanner (System.in);
int quantity[]=new int[3];
String name[]=new String[3];
double price[]=new double [3];
//do while loop to continue entering items until quantity is 0
do
{
System.out.println("Enter quantity of item, " + "name of item, " + " and price of item, " );
quantity[i]= scan.nextInt();
name[i]=scan.next();
price[i]=scan.nextDouble();
i++;
}while(quantity[i]==0);
//menu for grocery list operations using switch block
System.out.println("1) Add item(s)/n"
+ "2) Remove item(s)/n"
+ "3) view cart/n "
+ "4) Checkout/n "
+ "5) Exit/n");
ch=scan.nextInt();
switch(ch)
{
case 1:
add(quantity[i-1],name[i-1],price[i-1]);
break;
And here is the method add
//method to add item
public static void add(int q,String n,double p )
{
Scanner scan= new Scanner (System.in);
System.out.println("Enter quantity of item, " + "name of item, " + " and price of item, " );
q=scan.nextInt();
n= scan.next();
p=scan.nextDouble();
scan.close();
}
Upvotes: 1
Views: 201
Reputation: 376
Passing arrays as parameters and returning arrays in java is straightforward.
Here is an example:
public static int[] foo(int[] a){
// Do something with a
int[] b = {0,1,2};
return b;
}
But also keep in mind that Java is pass by value, but when you pass an array in as a parameter, it passes the reference (AKA memory address) as a value to the function.
Why is this important? It means that you can manipulate all the values of an array you pass as a parameter and these changes will be noticed in a different method.
Example:
public static void main(String... args){
int b = 5;
foo1(b);
// b is still 5
int[] c = {1,2};
foo2(c);
// c is now {1,10}
}
public static void foo1(int x){
x = 10;
}
public static void foo2(int[] x){
x[1] = 10;
}
Upvotes: 0
Reputation: 21
Instead of passing arrays, you can run the SWITCH STATEMENT inside a FOR LOOP upto the length of the Array.
Upvotes: 0