문제

I am trying to have this program print the topping and crust selected, the way it is set up now, it only prints the name. I tried initializing all the strings to be empty strings "". But no matter what button was clicked, the string was always empty even though the if statments are suppsed to change them.

Here is the code

public void actionPerformed(ActionEvent e) {
    if(e.getSource() == output){    
        String str2, str3, str4, str5;
        String str1 = txtName.getText();
        if(e.getSource() == optThick){
            str2  = "thick crust";
        }
        else if (e.getSource() == optThin){
             str2 = "thin crust ";
        }
        if(e.getSource() == cbCheese){
            str3 = "Cheese ";
        }
        if(e.getSource() == cbOlives){
             str4 = "Olives ";
        }
        if(e.getSource() == cbTomatoes){
             str5 = "Tomatoes ";
        }

        textArea.setText("Name : " + str1 + "\n" + "Crust: " + str2 + "\n" + "Toppings: " + str3 + str4 + str5); 
    }
}
}

올바른 솔루션이 없습니다

다른 팁

if(e.getSource() == output){    
       // code omitted 
}

All of your if statements are inside the outer statement. Is that it ?

In case anyone was wondering, this is how I got it to work.

public void actionPerformed(ActionEvent e) {
    if(e.getSource() == output){    
        String str2 = "", str3 = "", str4 = "", str5 = "";
        String str1 = txtName.getText();
        if(optThick.isSelected()){
            str2  = "Thick crust";
        }
        else if (optThin.isSelected()){
             str2 = "Thin crust ";
        }
        if(cbCheese.isSelected()){
            str3 = "Cheese ";
        }
        if(cbOlives.isSelected()){
             str4 = "Olives ";
        }
        if(cbTomatoes.isSelected()){
             str5 = "Tomatoes ";
        }

        textArea.setText(String.format("Name: %s \nCrust: %s\n Toppings: %s%s%s ",str1, str2, str3, str4, str5)); 
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top