0

I have made a program that asks:

The length of the array:

and the elements of the Array:

And then the program will multiply the elements.

My question is, how would I prompt the user to just enter the elements of the array without asking for the length and then stop when I type -1? Would I need to use an array list? Here is my code so far.

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Length of the array: "); //Prompt User for length
        int number = Integer.parseInt(input.next());

        System.out.print("The elements of your array: "); //Prompt User for elements
        int[] myArray = new int[number];
        for(int i = 0; i < number; i++){
            myArray[i] = Integer.parseInt(input.next());
        }
          System.out.printf("The multiplication is %d.", multiplication(myArray, myArray.length - 1) ); //End Statement     
    }        
    static int multiplication(int[] array, int startIndex) {
        if (startIndex == 0) 
            return(array[startIndex]); 
        else
            return (array[startIndex] * multiplication(array, startIndex - 1));
    }       
}

Any help would be appreciated.

waynus
  • 3
  • 1
  • 1
    Yes, you would need to us an array list since it is a data structure which grows as you put more elements into it. This way you can get rid of the array initialisation mechanic and replace your array access code with an array list access code (basically replace `[index]` with `.get(index)`). – npinti May 22 '20 at 09:29

2 Answers2

0

Yes we can use ArrayList and Array too.Here is an example with ArrayList.

    List<Integer> list = new ArrayList<Integer>();
    Scanner input = new Scanner(System.in);
    System.out.print("The elements of your array: ");
    boolean flag = true;
    while (flag) {
        int val = input.nextInt();
        if (val > 0) {
            list.add(val);
        } else {
            flag = false;
            System.out.println(list);
        }
    }
VIKRAM
  • 74
  • 7
0

First the code, then the explanation (appears after the code, below).

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class MultiplyRecurse {
    private static int multiplication(int[] array, int startIndex) {
        if (startIndex == 0) 
            return(array[startIndex]); 
        else
            return (array[startIndex] * multiplication(array, startIndex - 1));
    }

    /**
     * @param args
     */
    public static void main(String[] args) {

        @SuppressWarnings("resource")
        Scanner stdin = new Scanner(System.in);

        String quit = "Q";
        List<Integer> list = new ArrayList<>();
        String line = null;
        while (!quit.equalsIgnoreCase(line)) {
            try {
                System.out.print("Enter a number (or 'Q' to quit): ");
                line = stdin.nextLine();
                if (!line.equalsIgnoreCase(quit)) {
                    list.add(Integer.valueOf(line));
                }
            }
            catch (NumberFormatException xNumberFormat) {
                System.out.println("Not a number. Please try again.");
            }
        }
        int[] myArray = list.stream().mapToInt(i->i).toArray();
        System.out.printf("The multiplication is %d.%n",
                          multiplication(myArray, myArray.length - 1));
    }
}

In java int is a primitive. If you look at the code for class ArrayList you will see that it contains a member named elementData which is an array of Object. Hence you can't create an ArrayList object that contains an array of int, so you need to use Integer instead.

Note that if the user enters a number larger than MAX_VALUE, the code Integer.valueOf(line) will throw NumberFormatException.

Your multiplication() method requires a int[] argument, so you need to convert your ArrayList<Integer> to a int[]. The line of code that achieves this is taken from this stackoverflow question:

How to convert List to int[] in Java?

EDIT

Due to OP's comment

List<Integer> numbers = new ArrayList<>();
System.out.print("Enter numbers: ");
while (input.hasNextInt()) {
    int number = input.nextInt();
    if (number == -1) {
        break;
    }
    numbers.add(Integer.valueOf(number));
}
int[] myArray = numbers.stream().mapToInt(i->i).toArray();
System.out.printf("The multiplication is %d.%n",
                  multiplication(myArray, myArray.length - 1));

Sample run:

Enter numbers: 8 4 -1 <ENTER>
The multiplication is 32.

After typing -1, hit <ENTER> (on the keyboard).

Abra
  • 11,631
  • 5
  • 25
  • 33