Adam Adam - 1 month ago 7
Java Question

Want to get array from method in java

I am building a java program, which does the following functions:


  1. get input from user

  2. place intergers into array

  3. add 10000 to each integer in array.



The problem: can't get the array from plus(int arr[]), and print them inside main().

public class inputToArray {

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

for(int i=0; i<10; i++) {
int num = scan.nextInt();

insertToArray(num);
}


}
public static void insertToArray(int getNum) {

int array[] = new int[10];

for(int i=0; i<array.length; i++) {

array[i] = getNum;
}

plus(array);

}
public static int[] plus(int arr[]) {

for(int i=0; i<arr.length; i++) {

arr[i] += 10000;
}

return arr;
}

}

Answer Source

You made some mistakes :

  • your create a new array for each new int, and you want at the end to have all of thme in the same ? not very easy
  • you use arrays in method, but you never take them back

To match with your requirements :

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    int array[] = new int[10];

    for (int i = 0; i < 10; i++) {
        int val = scan.nextInt();
        array = insertToArray(val, array, i);   //"please insert val at place i in array"
    }
    array = plus(array);

    System.out.println(Arrays.toString(array));
}

public static int[] insertToArray(int getNum, int arr[], int place) {
    arr[place] = getNum;
    return arr;
}

public static int[] plus(int arr[]) {
    for (int i = 0; i < arr.length; i++) {
        arr[i] += 10000;
    }
    return arr;
}

Just put something more compact :

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int array[] = new int[10];
    for (int i = 0; i < 10; i++)
        array[i] = 10000 + scan.nextInt();       
    System.out.println(Arrays.toString(array));
}