-1

I have written a small program to improve my Java skills. I am trying to get the list of names and print the same using while loop. But the while loop which gets input is not terminating upon reaching the limit. My while condition looks okay. But I'm not sure, what is going wrong. Here is the code:

import java.io.DataInputStream;
import java.io.IOException;

public class MyTestProgram {

public static int count;
public static DataInputStream din;
public static String names[];

public static void main(String[] args) throws NumberFormatException, IOException {
    din = new DataInputStream(System.in);
    int counter = 0;
    System.out.print("Enter the numer of persons: ");
    count = Integer.parseInt(din.readLine());
    names = new String[count];
    System.out.println("Enter the names one by one:");
    while (counter < count) {
        names[counter] = din.readLine();
        counter = counter++;
    }
    System.out.println("List of names entered:");
    while (counter < count) {
        System.out.println(names[counter]);
        counter = counter++;
    }
}
}
Alex K
  • 8,269
  • 9
  • 39
  • 57
  • 2
    What do you think `counter = counter++;` does? – Sotirios Delimanolis Jan 27 '15 at 04:11
  • Is debugging a lost art, known only to the crusty old guys hunched over their green screen VT100 terminals under an incandescent light bulb with manuals on the bookshelves? Not even a `println` to see what values the variables are going through? – John3136 Jan 27 '15 at 04:14
  • If another gold badge sees this, [this](http://stackoverflow.com/questions/3831341/why-does-this-go-into-an-infinite-loop) is a better duplicate. – Sotirios Delimanolis Jan 27 '15 at 04:15
  • 1
    That's not the only problem with the code: also the counter variable is not reset between loops, so even if counter++ is used correctly, then the second loop will output nothing. – brendan Jan 27 '15 at 04:30

1 Answers1

2

For starters, change the way you increament the counter variable.

Just use:

counter++;

Since counter = counter++;, Increments counter, and returns what counter was before the increment, which gets assigned to counter. Here is the explanation.

Also reset your counter variable once first loop is completed.

Community
  • 1
  • 1
Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126