尝试和Catch语句

时间:2014-10-20 20:03:04

标签: java exception try-catch

我想使用try和catch语句,如果有人输入除了单词之外的其他内容。在我以前的经验中,如果没有错误,就很难使用它。如果有人输入一个数字,例如他们的名字,他们就没有错误。无论如何我可以使用try和catch语句吗?

try {
    String firstName, middleInitial, lastName, Firstname;
    char firstNameCase, middleInitialCase, lastNameCase;

    firstName = firstNameInput.getText();
    middleInitial = middleInitialInput.getText();
    lastName = lastNameInput.getText();

    char firstNameLetter = firstName.charAt(0);
    firstNameCase = Character.toLowerCase(firstNameLetter);

    char lastNameLetter = lastName.charAt(0);
    lastNameCase = Character.toUpperCase(lastNameLetter);

    char middleInitialLetter = middleInitial.charAt(0);
    middleInitialCase = Character.toLowerCase(middleInitialLetter);

    String firstNameFinal = Character.toString(firstNameCase);
    String lastNameFinal = Character.toString(lastNameCase);
    String middleInitialFinal = Character.toString(middleInitialCase);

    String monogram = firstNameFinal+lastNameFinal + middleInitialFinal;

    monogramOutput.setText("Your monogram is: " + monogram); 
} catch(I dont know what to put here) {
    JOptionPane.showMessageDialog(mainPanel, "One or more fields contains invalid data","Error Dialog", JOptionPane.ERROR_MESSAGE);
}

2 个答案:

答案 0 :(得分:0)

您是否有任何特定原因要使用Try / Catch方法?

我的意思是下面的代码应该对您的请求做任何事情:

Object helloworld = "";

if( helloworld instanceof String ) {
  // do something String related to helloworld
}

当然,如果你坚持尝试/捕获。

试试看:

catch (Exception ex)

答案 1 :(得分:0)

如果我理解了您的问题,您可以使用Pattern,其中正则表达式\\D+与数字不匹配。

String strFail = "cc1";
String strPass = "abc";
Pattern p = Pattern.compile("\\D+");
System.out.println(strFail + ": " + p.matcher(strFail).matches());
System.out.println(strPass + ": " + p.matcher(strPass).matches());

输出

cc1: false
abc: true