2017-10-13 52 views
1

我希望我的应用程序以字符串形式读取任何匹配项。我想将匹配变量存储为字符串

Scanner reader = new Scanner(System.in); 
    System.out.println("Problem 1: Create a heading using h1 tag"); 
    String input = reader.nextLine(); 
    Pattern regex = Pattern.compile("<[a-z][0-9]>"); 
    Matcher m = regex.matcher(input); 
    if(m.find()){ 
     String meme = m.group(0); 
     System.out.println(meme); 
     if(meme == "<h1>"){ 
      System.out.println("Found a string."); 
     } 
     else{ 
      System.out.println("No string found."); 
     } 
    } 
    else{ 
     System.out.println("No closing tag."); 
    } 

例如我
输入<..h1..>(无视点) 但输出总是No string found即使我设置模因== <..h1..>。我怎样才能将其转换为字符串?

回答

1

我觉得你的代码的问题是在这条线

if(meme == "<h1>") 

应该

if(meme.equals("<h1>")) 
+0

正是我所需要的!公认。 – Yupyep

2

的问题是(meme == "<h1>")

因为等号运算符(==)是基于参考而不是值进行比较,所以实际上它比较了两个单独的字符串:meme"<h1>"。相反,使用:

if(meme.equals("<h1>")){ 
+0

补给它卡兰,你打败了我... – phlaxyr

+0

感谢您的帮助!如果我只能接受2回答 – Yupyep

+0

没问题! :-D – phlaxyr

相关问题