[英]JOptionPane.showMessageDialog keeps reappearing
我的代碼應確保用戶僅輸入二進制字符串。 如果我輸入正確的二進制數(1、0),一切都會按順序進行。 但是,當我輸入錯誤的數字(字母或0和1以外的數字)時,會出現JOptionPane.ShowMessageDialog並顯示錯誤消息,並且當我單擊“確定”或“交叉”按鈕時,它將再次出現。 因此,要關閉該應用程序,我必須使用進程管理器殺死“ java.exe”。
這是我的應用程序的完整代碼:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Bn extends JFrame {
private JLabel l1;
private JLabel l2;
private JLabel l3;
private JTextField tf;
private JButton oc;
private JButton hd;
private JButton dc;
public Bn() {
setTitle("Binary Conversion");
setSize(350 , 190);
setResizable(false);
setLocation(720 , 200);
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout(FlowLayout.CENTER, 25, 10));
l1 = new JLabel(">>>>>>>>BINARY CONVERSION<<<<<<<<");
l2 = new JLabel("Enter The Number:");
l3 = new JLabel(" Convert to: ");
tf = new JTextField(25);
oc = new JButton("Octal");
hd = new JButton("Hexa Decimal");
dc = new JButton("Decimal");
add(l1); // Binary conversion
add(l2); // Enter The Number
add(tf); // Text Field
add(l3); // Conver to
add(oc); // Octal
add(hd); // Hexa Decimal
add(dc); // Decimal
oc.addActionListener(new cvr());
hd.addActionListener(new cvr());
dc.addActionListener(new cvr());
setVisible(true);
}
void res()
{
int b = 0;
String num = tf.getText();
int i , l;
l = num.length();
char ch;
do
{
for (i=0 ; i<l ; i++)
{
b = 0;
ch = num.charAt(i);
if (Character.isDigit(ch) && (ch == 48 || ch == 49))
b=1;
else
{
JOptionPane.showMessageDialog(null, "Please enter a binary number (1 , 0)");
}
}
}
while(b != 1);
}
void occ()
{
res();
String num = tf.getText();
long dec = Long.parseLong(num,2);
String oct = Long.toOctalString(dec);
JOptionPane.showMessageDialog(null, "Octal equivalent is: "+ oct);
}
void hdc()
{
res();
String num = tf.getText();
long dec = Integer.parseInt(num,2);
String hex = Long.toHexString(dec);
JOptionPane.showMessageDialog(null, "Hexa Decimal equivalent is: "+ hex);
}
void dcc()
{
res();
String num = tf.getText();
long decimal = 0, temp, i = 0;
temp = Long.parseLong(num);
while (temp != 0) {
long r = temp % 10;
long value = r * (int)Math.pow(2, i);
i++;
decimal = decimal + value;
temp /= 10;
}
JOptionPane.showMessageDialog(null, "Decimal equivalent is: "+ decimal);
}
private class cvr implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == oc)
{
occ();
}
if (e.getSource() == hd)
{
hdc();
}
if (e.getSource() == dc)
{
dcc();
}
}
}
public static void main(String args[])
{
Bn obj = new Bn();
}
}
JOptionPane的代碼位於void res()
方法中。 如何關閉此對話框窗格,以便重新輸入輸入值?
刪除do {} while循環
do
{
for (i=0 ; i < l ; i++)
{
b = 0;
ch = num.charAt(i);
if (Character.isDigit(ch) && (ch == 48 || ch == 49))
b=1;
else
{
JOptionPane.showMessageDialog(null, "Please enter a binary number (1 , 0)");
}
}
}
while(b != 1);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.