我有一個應該獲取輸入的代碼,從第一個輸入中獲取最后兩個字母,然后將第二個輸入與最后兩個字母匹配(例如 glam、slam)。問題是它一直使用 else 陳述句而不是 if 陳述句。模式的構建方式是否存在問題?
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.Scanner;
public class MatchyPattern {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the first word: ");
String fw;
fw = s.nextLine();
String lastTwo = fw.substring(fw.length() - 2);
char[] sub = lastTwo.toCharArray();
var p = Pattern.compile("[a-zA-Z]{1,2}" sub "]");
System.out.print("Enter the second word: ");
String sw;
sw = s.nextLine();
Matcher m = p.matcher(sw);
if (m.matches()){
System.out.println(fw " rhymes with " sw);
}else{
System.out.println("I'm not sure! Sorry!");
}
}
}
uj5u.com熱心網友回復:
似乎您不明白[C@37f8bb67(@ 變化之后的部分)是什么,并且您天真地試圖“關閉”括號。您看到的是默認陣列toString,在代碼中根本沒有任何意義
您可以只用最后一個字符(作為字串)填充模式
var p = Pattern.compile("[a-zA-Z]{1,2}" lastTwo);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/483115.html
