Java:如果(将字符串与整数进行比较)

时间:2014-01-26 23:27:58

标签: java if-statement

我目前正在尝试编写一个简单的输入对话框程序,提示用户输入其名称。我想创建一个if语句,如果用户输入任何数字或特殊字符,则提示用户使用字符a-z并要求重新输入名称。  这是我的代码到目前为止,我不知道如何编写if语句,我得到的错误是无法比拟的数据类型字符串和整数。

public class inputdialogbox {
   public static void main(String[] args)  {
      Scanner user_input = new Scanner( System.in);
      String first_name;      
      first_name = JOptionPane.showInputDialog(null, "Please enter your First Name",
         "User's Name",JOptionPane.QUESTION_MESSAGE);
      int intValue = Integer.parseInt(first_name);
      if (first_name == intValue);

2 个答案:

答案 0 :(得分:0)

您可以学习如何使用正则表达式,也可以检查用户是否输入了无效字符。听起来你要做的就是验证用户输入的字符,这意味着检查字符串中的所有字符都是a-z中的字符集。那么为什么不检查字符是否有效而不是无效和一些可能的整数类型?

了解如何使用charAt迭代字符串的字符http://www.tutorialspoint.com/java/java_string_charat.htm

不要费心将字符串转换为整数,只需循环字符串并检查每个字符是否在允许的列表或范围内。

答案 1 :(得分:0)

正则表达式:[A-Za-z ]+

意味着

[                //Each character must be...
    A-Z          //a capital letter OR
    a-z          //a lower-case letter OR
    __A_SPACE__  //a space
]+               //and there must be between 1 and infinity of these characters

工作示例:

   import  java.util.regex.Pattern;
/**
  <P>{@code java LettersOnlyXmpl}</P>
 **/
public class LettersOnlyXmpl  {
  public static final void main(String[] igno_red)  {
     Pattern pLettersOnly = Pattern.compile("[A-Za-z ]+");
      test(pLettersOnly, "Obama");
      test(pLettersOnly, "Kermit The Frog");
      test(pLettersOnly, "The QuIcK brown FOx JUMPED over the lazy DOg");
      test(pLettersOnly, "23874298374");
  }
   private static final void test(Pattern p_p, String s_name)  {
      System.out.print(s_name + "...");
      if(p_p.matcher(s_name).matches())  {
         System.out.println("Contains only letters and spaces. Good.");
      }  else  {
         System.out.println("ERROR: Must contain letters and spaces only.");
      }
   }
}

输出:

Obama...Contains only letters and spaces. Good.
Kermit The Frog...Contains only letters and spaces. Good.
The QuIcK brown FOx JUMPED over the lazy DOg...Contains only letters and spaces. Good.
23874298374...ERROR: Must contain letters and spaces only.