JOption的变量显示2次

时间:2018-10-19 08:26:13

标签: java joptionpane

我想在最后显示变量toPay。

示例我向变量toPay输入了0,之后它将再次调用main(args),然后我将输入4,但输出为

JOption“要付款:28”是正确的,但是在我关闭JOptionpane之后,再次弹出一些消息,并显示JOption“要付款0”

package Payphone;

import java.util.Scanner;
import javax.swing.*;
public class Try {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int toPay=0;

    int n = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter calltime"));
    if (n<=0) {
        toPay = 0;
    JOptionPane.showMessageDialog(null,"Error!");
    Try.main(args);

    }else if (n<=3){
        toPay =20;
    }else{
       toPay =n - 3;
       toPay =(toPay*3)+20;
    }
    JOptionPane.showMessageDialog(null,"Babayadan mo: "+toPay,"PAYCHECK",JOptionPane.PLAIN_MESSAGE);
}
}

1 个答案:

答案 0 :(得分:0)

发生此错误是因为此时您正在再次调用程序Try.main(args);,所以当发生错误时,请设置toPay = 0;,然后显示错误消息,但是最后一行再次调用JOptionPane ,因此在正确执行第一个JOptionPane之后,程序仍将执行最后一个JOptionPane并显示“ Babayadan mo:0”。

要纠正这种情况,您必须结束程序或执行以下操作:

import javax.swing.JOptionPane;

public class Try {

    private static int n;

    public static void main(String[] args) {
        babayadan();
    }

    public static void restart() {
        JOptionPane.showMessageDialog(null, "Error!");
        n = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter calltime"));
    }

    public static void babayadan() {
        n = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter calltime"));

        while(n <= 0) {
            restart();
        }

        int toPay = 0;
        if (n <= 3){
            toPay = 20;
        }else {
            toPay = n - 3;
            toPay =(toPay * 3) + 20;
        }
        JOptionPane.showMessageDialog(null, "Babayadan mo: " + toPay, "PAYCHECK", JOptionPane.PLAIN_MESSAGE);
    }
}