'Attempting to fill an array with console input, but every other element is assigned a blank value
I am trying to create an array and fill it with input from the console that is then output in reverse order, however it keeps assigning blank values to every other element. This is causing fewer lines from the console to be read than I would like. Additionally, this is causing lines to be "skipped" during output. The values in the array look like ["a", "", "b", "", "c"] when I would like them to look like ["a", "b", "c", "d", "e"].
To clarify I want to input values for five Strings through the console and output them on consecutive lines. Currently, I can only input three because two of the elements are filled with "" . Additionally, this is causing spacing problems in the output.
Here is my code:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String[] list = new String[5];
for(int i = 0; i < list.length; i++) {
list[i] = reader.readLine();
} for(int i = list.length - 1; i >=0; i--) {
System.out.println(list[i]);
}
Here is an image of my code partially running through a debugger. I am using IntelliJ IDEA Community Edition.
Solution 1:[1]
See there might be a problem with your debugger because your code is absolutely correct. I have run the code on eclipse IDE and it is showing the desired input. Output: enter image description here
However, if you want the array to be printed within square brackets add this line of code,
System.out.print('[');
for(int i = list.length - 1; i >=0; i--) {
System.out.print(list[i]+" ");
}
System.out.print(']');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Harshank Bansal |
