用于显示循环的Java代码

时间:2014-03-16 14:12:43

标签: java

我一直在制作这个记录制造单位的小程序,这就是它的工作原理

用户输入每个部门制造的单位的值

Dept 1: 1
Dept 2: 5
Dept 3: 2
Dept 4: 3

结果应该是这样的:

Dept 1: *
Dept 2: *****
Dept 3: **
Dept 4: ***

但是,当我尝试使用此代码时,它会为我提供一个null值:

else if(e.getSource()==btnView){
    int num1 = Integer.parseInt(txtdept1.getText());
    int num2 = Integer.parseInt(txtdept2.getText());
    int num3 = Integer.parseInt(txtdept3.getText());
    int num4 = Integer.parseInt(txtdept4.getText());

    for (int i = 0; i < num1; ++i) {
        str += "*";
        txtdept1record.setText(str);
    }

结果如下:

Dept 1: null*

上面的for循环仅适用于dept1。

2 个答案:

答案 0 :(得分:0)

将循环优化为:

for (int i = 0; i < num1; ++i) {
    if( i == 0 ) //i.e. first time
        str = "";            
    str += "*";
}
txtdept1record.setText(str); //outside :-)

但不建议这样做,因此请使用StringBuilder

StringBuilder sb = new StringBuilder();
for (int i = 0; i < num1; ++i) {
    sb.append("*");
}
txtdept1record.setText(str); //outside :-)

您的(万无一失)代码:

...
else if(e.getSource()==btnView){
    int num1 = Integer.parseInt(txtdept1.getText());
    int num2 = Integer.parseInt(txtdept2.getText());
    int num3 = Integer.parseInt(txtdept3.getText());
    int num4 = Integer.parseInt(txtdept4.getText());
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < num1; ++i) {
        sb.append("*");
    }
    txtdept1record.setText(sb.toString());

    sb = new StringBuilder(); //empty it.

    //Same thing (i'll show once)

    for (int i = 0; i < num1; ++i) {
        sb.append("*");
    }
    txtdept2record.setText(sb.toString());
    ...

答案 1 :(得分:0)

String str = "";

开始

我认为你已定义为String str;