-1

I am reading some data from a file and each line is assigned to one cell of the String array. For some reason when I try to print the array after reading the file(lines 8-10), I get nothing printed. When I print the line in the While loop(line 5) I get the line printed correctly.

    1: int count = 0;
    2: String[] s = new String[300];


    3: while(!StdIn.isEmpty()) {
    4:  s[count]=StdIn.readLine();
    5:  System.out.println(s[count]);
    6:  count++;
    7: }

    8:  for(int i=0;i<count;i++) {
    9:   System.out.println(s[i]);
   10: }

Same code using Scanner:

    Scanner in = new Scanner(System.in);

    int count = 0;
    String[] s = new String[300];


    while(in.hasNextLine()) {
        s[count]=in.nextLine();
        System.out.println(s[count]);
        count++;
    }
    for(int i=0;i<count;i++) {
        System.out.println(s[i]);
    }

I can't figure out what's wrong with my code.

Thanks in advance.

EDIT: When the last line has been read, the in.hasNextLine() is not returning anything. It got stuck at the count++. See photo -> DEBUGGER

  • 1
    I see nothing wrong, but without knowing what `StdIn` is or does, we can't see the full picture. Did you try **debugging**? [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173/5221149) – Andreas Dec 09 '17 at 17:12
  • @Andreas added to my question the same code using Scanner if that helps. – Eleni Ioakim Dec 09 '17 at 17:20
  • Can you include in your question the exact output you're getting, and exactly what you want it to be? – Keara Dec 09 '17 at 17:22
  • 2
    You said you are reading text from file, but your edit suggest that you are reading from `System.in`. There is a big difference between both cases. System.in is opened until it will be closed explicitly so `hasNextLine` can't return `false` because user/process can be in the middle of writing to System.in so `hasNextLine` will need to *wait* for data so you are still in first loop. In case of file after it will read last line `hasNextLine` can return false and move on to next loop responsible for printing array content. – Pshemo Dec 09 '17 at 17:23
  • 2
    If you are really reading from file then post proper [mcve] otherwise we can't help you. – Pshemo Dec 09 '17 at 17:26
  • If you are not reading from file but from System.in then this is same problem as explained here: [Why does hasNextLine() never end?](https://stackoverflow.com/q/5653338) – Pshemo Dec 09 '17 at 17:30

2 Answers2

-1

This will only work with a file but when using System.in here the in.hasNextLine() never gives false. You need to provide it with a condition to break the while loop.

Zingerella
  • 440
  • 2
  • 10
-2
8:  for(int i=0;i<count;i++) {

here your error, this should be s.length instead of count

Juan Pablo
  • 124
  • 2
  • 6