【问题标题】:How to do: if input not valid, display error with JOptionPane?怎么办:如果输入无效,则使用 JOptionPane 显示错误?
【发布时间】:2018-09-03 14:28:44
【问题描述】:

我在创建程序时遇到了一点麻烦,如果输入数据将出现下一个输入,如果不输入则会出现警告消息。

import javax.swing.*;
public class JoptionInputDialogBisa {
    public static void main (String [] args)
    {
        JOptionPane jop = new JOptionPane ();

        String nama = JOptionPane.showInputDialog(null,"Masukkan Nama : ");
        double tb = Double.parseDouble(JOptionPane.showInputDialog(null,"Masukkan Tinggi Badan : "));
        double bbi = (tb-100)*0.9;
        String cetak = "Dsts User\nNama : "+nama+"\nTinggi Badan :"+tb+" cm\nBerat Badan Ideal : "+bbi+" kg";
        jop.showMessageDialog(null,cetak,"Hasil Berat Badan Ideal",jop.INFORMATION_MESSAGE);
    }
}

【问题讨论】:

    标签: java swing validation joptionpane


    【解决方案1】:

    您可以执行以下操作,当然这在处理错误的高度数字输入方面并不完整。

    public static void main(String[] args) throws IOException {
        final String nama = getInputForMessage("Masukkan Nama : ");
        final double tb = Double.parseDouble(getInputForMessage("Masukkan Tinggi Badan : "));
        final double bbi = (tb - 100) * 0.9;
        final String cetak = "Dsts User\nNama : " + nama + "\nTinggi Badan :" + tb + " cm\nBerat Badan Ideal : " + bbi + " kg";
        JOptionPane.showMessageDialog(null, cetak, "Hasil Berat Badan Ideal", JOptionPane.INFORMATION_MESSAGE);
    }
    
    private static String getInputForMessage(String inputMessage) {
        while (true) {
            final String result = JOptionPane.showInputDialog(null, inputMessage);
            if (!result.trim().isEmpty()) return result;
            JOptionPane.showMessageDialog(null, "Please try again.", "Invalid Input!", JOptionPane.WARNING_MESSAGE);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-04
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多