因此,我撰寫了一個名為 varCount() 的方法,如下所示,它可以計算數學方程式中字母變數的數量。
// This method counts the number of variables in the equation
/* Note: If a variable is a word or a substring with length greater than 1,
then count it as a whole */
public int varCount(){
int count = 0;
for (int i = 0; i < getEquation().length(); i ){
if ((getEquation().charAt(i) >= 65 && getEquation().charAt(i) <= 90)
|| (getEquation().charAt(i) >= 97 && getEquation().charAt(i) <= 122)){
count ;
}
}
return count;
}
這個方法是在一個類里面做的,所以這里使用了私有方程字串屬性的getter方法。
應該由此產生的一個示例是,如果您在字串x 2 = 3上使用該方法,則將有 1 個字母變數,即x,這是計算在內的。經過測驗,該方法回傳了預期的 int 值,并且在該程度上是有效的。
我真正想要完成的是,如果用戶曾經輸入像num這樣的變數,那么該方法應該仍然像第二條評論一樣作業。
在第一次嘗試時,我認為,既然它是一個像num這樣的詞,那么,如果前一個字符被計為一個字母,那么整個單詞將通過只計算第一個字母來計算,如下所示:
// This method counts the number of variables in the equation
/* Note: If a variable is a word or a substring with length greater than 1,
then count it as a whole */
public int varCount(){
int count = 0;
for (int i = 0; i < getEquation().length(); i ){
if ((getEquation().charAt(i) >= 65 && getEquation().charAt(i) <= 90)
|| (getEquation().charAt(i) >= 97 && getEquation().charAt(i) <= 122)){
if (i != 0 && (getEquation().charAt(i-1) >= 65 && getEquation().charAt(i-1) <= 90)
|| (getEquation().charAt(i-1) >= 97 && getEquation().charAt(i-1) <= 122)){
continue;
}
count ;
}
}
return count;
}
問題在于該方法僅導致IndexOutOfBoundsException。
接下來的嘗試是使用regex包修改或替換方法主體,該包使用 Matcher 類的 groupCount() 方法回傳 0,如下所示:
// This method counts the number of variables in the equation
/* Note: If a variable is a word or a substring with length greater than 1,
then count it as a whole */
public int varCount(){
Pattern alphaRange = Pattern.compile("[a-zA-Z]");
Matcher match = alphaRange.matcher(getEquation());
System.out.println(match.groupCount());
return match.groupCount();
}
這種方法我錯過了什么或出了什么問題?
uj5u.com熱心網友回復:
好的,我已經修改了使用正則運算式包的 Pattern 和 Matcher 類的方法,并設法讓程式完全按預期運行。
// This method counts the number of variables in the equation
/* Note: If a variable is a word or a substring with length greater than 1,
then count it as a whole */
public int varCount(){
int count = 0;
Pattern pattern = Pattern.compile("(a-zA-Z)*");
Matcher match = pattern.matcher(getEquation());
if (match.find()){
count = match.groupCount();
}
return count;
}
從邏輯上講,我沒有意識到如果找到匹配項,則需要處理 groupCount() 方法。對于更具體的范圍,我還使用了括號而不是開括號。
不過,讓我想起的是,有時我們可能需要另一雙眼睛。謝謝!
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/470705.html
上一篇:獲取有關檔案夾及其檔案的詳細資訊