循环不终止。继续获得输入

时间:2015-01-27 04:11:03

标签: java

我写了一个小程序来提高我的Java技能。我试图获取名称列表并使用while循环打印相同的名称。但是获得输入的while循环在达到限制时不会终止。我的情况看起来还不错。但我不确定,出了什么问题。这是代码:

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++;
    }
}
}

1 个答案:

答案 0 :(得分:2)

首先,改变你增加计数器变量的方式。

只需使用:

counter++;

counter = counter++;开始,增加counter,并返回增量前counter的内容,并将其分配给counterHere is the explanation.

首次循环完成后,还要重置计数器变量。