簡體   English   中英

如何通過循環使程序重置回到開頭

[英]How to make program reset back to the beginning with a loop

我有一個簡單的貨幣轉換程序,該程序允許用戶輸入三個文本字段之一,以便將其金額轉換為USD。 我希望用戶能夠輸入他們想要的多次信息,因此我創建了一個名為continueButtonJButton ,但是我無法正確進行循環並重置程序。

問題:如何編寫循環語句以使該程序從頭開始,從而允許用戶再次輸入數字?

public class MoneyConversionPanel extends JPanel {

    JLabel yenLabel = new JLabel();
    JLabel poundLabel = new JLabel();
    JLabel euroLabel = new JLabel();
    JTextField yenText = new JTextField("Enter Yen amount here:");
    JTextField poundText = new JTextField("Enter Pound amount here:");
    JTextField euroText = new JTextField("Enter Euro amount here:");
    JButton continueButton = new JButton("Click to reset");
    JButton yenButton = new JButton("Convert");
    JButton poundButton = new JButton("Convert");
    JButton euroButton = new JButton ("Convert");
    MoneyConversion userInput;

    public MoneyConversionPanel()
    {

    Dimension dimension = new Dimension(1200,1000);

    setPreferredSize(dimension);

    setBackground(Color.cyan);

    yenButton.addActionListener(new buttonListener());

    add(yenLabel);
    add(poundLabel);
    add(euroLabel);
    add(yenText);
    add(poundText);
    add(continueButton);
    continueButton.setVisible(false);
    add(euroText);
    add(yenButton);
    add(poundButton);
    add(euroButton);

}

    private class buttonListener implements ActionListener
    {
        double conversionDouble;
        NumberFormat costFmt = NumberFormat.getCurrencyInstance();


        @Override
        public void actionPerformed(ActionEvent e) {

    do {

        for(int i = 0; i < 1; i++)
        {
        if(e.getSource() == yenButton)

        {
            userInput = new MoneyConversion(Double.parseDouble(yenText.getText()));
            conversionDouble = userInput.convertYen();
            yenLabel.setText("" + costFmt.format(conversionDouble));
            continueButton.setVisible(true);
        }

        else if(e.getSource() == poundButton)
        {
            userInput = new MoneyConversion(Double.parseDouble(poundText.getText()));
            conversionDouble = userInput.convertPounds();
            poundLabel.setText("" + costFmt.format(conversionDouble));
            continueButton.setVisible(true);
        }

        else if(e.getSource() == euroButton)
        {
            userInput = new MoneyConversion(Double.parseDouble(euroText.getText()));
            conversionDouble = userInput.convertEuro();
            euroLabel.setText("" + costFmt.format(conversionDouble));
            continueButton.setVisible(true);
        }
        }

    } while(e.getSource() == continueButton);
        } 

        }

}

建議:

  • 僅使用一個JTextField輸入窗口。
  • 在此窗口的左側提示一個JLabel。
  • 具有三個轉換JButton,每種貨幣一個
  • 或一個轉換JButton和3個JRadioButtons允許用戶選擇要轉換成哪種貨幣。
  • 無需循環或重置。 只需進行轉換並在每次按下按鈕時顯示它就可以了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM