0

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.

Uwe Allner
  • 3,399
  • 9
  • 35
  • 49
  • It does not seem to work correctly to me. My understanding is that this array should have five elements each of which I can fill with a String I input through the console. Because every other element is filled with nothing I can only make three inputs from the console. – user19165983 May 21 '22 at 08:22
  • this looks to be similar to your situation. I m not sure why, but on my IDE your code works fine. https://stackoverflow.com/a/72327845/16034206 – experiment unit 1998X May 21 '22 at 08:35
  • Run it at the console of your OS instead. Let us know what happens – g00se May 21 '22 at 11:33
  • I ran it using the Command Prompt on Windows. It worked perfectly fine. Strange. It does seem to be a problem with IntelliJ IDEA – user19165983 May 21 '22 at 19:09
  • @user19165983 I recently updated my IntelliJ IDEA and your error started occurring on my device too. Definitely the error is with IntelliJ and version dependant as well. – experiment unit 1998X May 22 '22 at 09:10

1 Answers1

0

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(']');

enter image description here

Harshank Bansal
  • 2,798
  • 2
  • 7
  • 22