简体   繁体   中英

How to do: if input not valid, display error with JOptionPane?

I am having a little trouble when creating a program where if entered the data will appear next input and if not input will appear with warning message.

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);
    }
}

You can do something like below, of course this is not really complete in a sense of handling bad numeric input for height.

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);
    }
}

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