简体   繁体   中英

Why does this code segment only print out 0 in the JLabel?

How can I fix this code segment so that it prints the numbers I input with commas? Example input: 1234, Expected result: 1,2,3,4 .

This code works in a normal file on Netbeans but I am having trouble changing it to fit into a GUI. When I run it it just displays zero on the result JLabel . I can seem to find any method that can help me with this.

private void jButton1ActionPerformed(ActionEvent evt) { 

    Stack stack = new Stack();
    int number = (int) (Integer.parseInt(jTextField1.getText()));
    while (number > 0) {
        stack.push(number % 10);
        number = number / 10;
    }

    while (!stack.empty()) {
        System.out.print(stack.pop());

        if (!stack.empty()) {
            System.out.print(",");
        }
        jLabel2.setText(String.valueOf(number));
    }
}

You should store the result somewhere in order to set the text later.

For example, you can store the characters in a StringBuilder :

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {   
    Stack stack = new Stack();
    int number = (int) (Integer.parseInt(jTextField1.getText()));
    while (number > 0) {
        stack.push(number % 10);
        number = number / 10;
    }
    StringBuilder sb = new StringBuilder();
    while (!stack.empty()) {
        sb.append(stack.pop());
        if (!stack.empty()) {
            sb.append(",");
        }
    }
    jLabel2.setText(sb.toString());
}

The problem is that you're printing the value of number on the label. And at that point number is always equal to 0 . What you want is to print the values in the stack instead. Example:

StringBuilder out = new StringBuilder();
while (!stack.empty()) 
{
    out.append( stack.pop());

    if (!stack.empty()) 
    {
        out.append(",");
    }
}

jLabel2.setText(out.toString());

You set the text of the jlabel always to zero, because "number" will always be zero at this point. But you print the sequence of numbers to the console. You probably want to concatenate them into a string and set the text of the jlabel accordingly. You could use a StringBuilder like this:

StringBuilder sb = new StringBuilder();
while (!stack.empty()) {
    sb.append(stack.pop());

    if (!stack.empty()) {
        sb.append(", ");
    }

    jLabel2.setText(sb.toString())
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM