【问题标题】:validate input using try catch [duplicate]使用 try catch 验证输入 [重复]
【发布时间】:2023-03-21 11:51:02
【问题描述】:

如果用户没有输入指定的单词,即管理员,我正在尝试通过创建异常错误来验证 java 中的输入文本字段

        String username;
        int phone1;

        @Override
        public void widgetSelected(SelectionEvent e) {          
            try
            {
            phone1 = Integer.parseInt(phone.getText());
            }
            catch (Exception exe)
            {           
                MessageDialog.openError(shell, "Error","Phone number has to be a number");
                return;
            }

            try
            {
            username = namefield.getText();
               if (username!= "admin") {
                    throw (new Exception());
                }           
            }
            catch (Exception exe)
            {   
                MessageDialog.openError(shell, "Error","The username must be admin");
                return;
            }


            labelresult.setText("The name entered is:"+ username );


            labelresult2.setText("The phone entered is:"+ phone1 );

手机用的很完美

用户名呢?我该怎么办?

【问题讨论】:

  • @KarthikeyanVaithilingam 不能完全回答我的问题。因为我说的是try catch。
  • 你确定执行到了 throw 语句。
  • 一般不建议使用异常来控制程序流程。
  • @simonv 我知道不建议这样做。我处于必须使用它的情况。所以我简化了我的问题,以便理解 try catch 语句

标签: java if-statement try-catch


【解决方案1】:

正如@simonv 在评论中提到的,不要使用异常来控制程序流。但是如果你正在学习try-catch,那么你可以试试这个。还要改进您的if 声明。您正在比较字符串对象。所以使用equals()方法如下:

        try
        {
        username = namefield.getText();
           if (!"admin".equals(username)) {
                throw new Exception("YOUR_MESSAGE_HERE");
            }           
        }
        catch (Exception exe)
        {   
            System.out.println(exe);
            return;
        }

【讨论】:

  • 我认为应该是 .equals...而不是 .equal
  • 是 .equals() @krushiovida
【解决方案2】:

你应该使用:

 if(!username.equals("admin")){
 //your code
 }

要比较字符串,您必须使用equals() 方法。

按照simon的建议,推荐使用:

if(!"admin".equals(username)){
 // your code 
}

这样,它就会是 null 安全的。

【讨论】:

  • 我建议反转此等于检查以避免潜在的空指针。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-10
  • 1970-01-01
  • 2017-11-25
  • 1970-01-01
  • 2020-04-02
  • 2023-01-31
  • 1970-01-01
相关资源
最近更新 更多