2015-10-20 52 views
0

我正在研究一个显示“Hello”并接受使用JOptionPane的用户输入的简单程序。我想读取用户输入并将其与显示的单词进行比较。例如,程序将显示“你好”,用户将不得不在文本框中输入一个单词。如果他们键入“你好”,那么将打印“正确”。如果他们没有输入Hello,则会打印“不正确”。为了读取用户输入并比较两个字符串,我需要做什么?将TextField添加到JOptionPane

public static void main(String[] args){ 

    String resp = "Hello"; 

    JOptionPane.showInputDialog(null, resp); 

    String input = ; //what should go here        

    if (resp.compareTo(input) == 0) { 
     JOptionPane.showMessageDialog(null, "Correct!"); 
     } else 
     JOptionPane.showMessageDialog(null, "Incorrect"); 
     } 
    } 
} 
+1

IM相当肯定'JOptionPane.showInputDialog'返回一个字符串,以便使它看起来像'字符串输入= JOptionPane.showInputDialog(NULL, “你好”);' – 3kings

+2

另外,看看[如何制作对话框](http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html) – MadProgrammer

+1

@ 3kings嘿,谢谢你的帮助!它的工作原理 –

回答

4
public static void main(String[] args) 
{ 

String resp = "Hello"; 

String input = JOptionPane.showInputDialog(null, resp);       

if (resp.compareTo(input) == 0) 
    JOptionPane.showMessageDialog(null, "Correct!"); 
else 
    JOptionPane.showMessageDialog(null, "Incorrect"); 
} 
+2

应该在EDT上创建和更新Swing GUI(因此我建议删除方法名称并打开大括号!),否则+1。 OP:如果它有助于解决问题,请[请接受答案](http://meta.stackexchange.com/a/5235/155831)。 –

+0

如果帮助解决问题,请[接受答案](http://meta.stackexchange.com/a/5235/155831)!另请参阅[您的个人资料](http://stackoverflow.com/users/5181166/ryan-hardin)中链接的一些早期问题,并通过接受答案查看哪些问题也可以“最终确定”。 –