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?
Asked
Active
Viewed 134 times
-1
-
3Does 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
-
2Please 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 Answers
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.

Vinicius Lustosa
- 34
- 5
0
Note:
n
is not defined, perhaps you meant to use5
.- The array is defined in a C-style, define it like this:
int[] arrayVariableName
num
is an array, so it should be namednums
.- To get an
int
from an input, you should callin.nextInt()
and notin.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 Noble Rabbit
- 2,728
- 2
- 6
- 12