-1

I’m trying to code a simple Java program entering five integers through echo input while using arrays. All I should be able to do is enter five integers, and the program just displays a message preceded by the entered numbers. I would think that all I would need to add would be a correct array variable assignment, but I can’t find it. What does anyone suggest?

what I have so far

DNell
  • 1
  • 3
    Does this answer your question? [How can I store user inputs in an array of integers?](https://stackoverflow.com/questions/59413887/how-can-i-store-user-inputs-in-an-array-of-integers) – smac2020 May 27 '21 at 00:33
  • 2
    Please post text, not links to images of text. – Dave Newton May 27 '21 at 00:39
  • There are multiple issue with your code, it would be better to first go through a tutorial to atleast understand the basics – lyncx May 27 '21 at 00:44
  • [Read int from scanner](https://stackoverflow.com/a/2506109/2478398). [Using arrays](http://tutorials.jenkov.com/java/arrays.html). [Printing arrays](https://stackoverflow.com/a/409795/2478398). Read through those and you should be able to come up with your own answer (and see what's wrong with the code at the moment). – BeUndead May 27 '21 at 00:58

2 Answers2

0

From what I saw in your code, you are trying to use a variable n that has not been declared, the correct one would not be num.length?

You can also use in.nextInt(); for integer values.

0

Note:

  • n is not defined, perhaps you meant to use 5.
  • The array is defined in a C-style, define it like this: int[] arrayVariableName
  • num is an array, so it should be named nums.
  • To get an int from an input, you should call in.nextInt() and not in.next().
  • To print the contents of the array, you should first call Arrays.toString().

The fixed code:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter 5 integers: ");

    int[] nums = new int[5];
    for (int i = 0; i < 5; i++) {
        nums[i] = in.nextInt();
    }

    System.out.println("You entered: " + Arrays.toString(nums));
}
Most Needed Rabbit
  • 2,058
  • 1
  • 4
  • 9