我試圖做一個 if 陳述句,每次在字串中找到動詞“我”或“我”時扣 2 分。為此,我將字串拆分為單獨的單詞。為了測驗,我將字串更改為 2x “me”。但是分數只被扣除一次而不是兩次(因為有 2 x “我”)。嘗試添加一個while回圈,但它一直在扣除直到負數。寶貝語言請,我是一個初學者編碼器。提前致謝
public static void main(String[] args) { //getWordLength() { // Checking word length. Less than 6 means reviewer can't weigh out positives and negatives
// TODO Auto-generated method stub
int ReviewScore = 30;
String Review = "me I me, from Montreal";
String[] words = Review.split("\\s ");
System.out.println("Word Count is: " words.length);
int wordlength = Integer.valueOf(words.length);
if (wordlength< 6) {
ReviewScore -=4; // deducts 4pts if review less than 6 words
System.out.println("Score is " ReviewScore);
}
verbCount( ReviewScore,Review);
}
public static void verbCount (int ReviewScore, String Review) { //Count verbs 'I' or 'me'
for (String s : Review.split("\n") ) { // splits review into separate words
if (s.contains("me" )){ // Checks for 'me' or 'I'
ReviewScore -= 2;
System.out.println("Score is " ReviewScore); // deducts by 2 pts
if ( s.contains ("I")) {
ReviewScore -= 2;
System.out.println("Score is " ReviewScore);
}
}
}
} }
uj5u.com熱心網友回復:
首先,您應該從您的方法回傳審查分數verbcount。
其次,您將文本拆分兩次,一次按單詞邊界(“\s ”),但在您的方法中verbcount,您將其拆分為換行符(“\n”),因此該方法無法按預期作業。
而不是要查看的字串,而是將words陣列傳遞給該方法并且不要再次拆分它!
第三,您的 if 是嵌套的,因此s.contains ("I")只會檢查 if 也是s.contains("me")- 這可能是因為您按行拆分,但每行僅一次。同樣,一旦您拆分單詞,您將永遠不會進入第二個 if 分支。將其向上拉一級以與if方法內的第一級平行。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/444582.html
上一篇:我如何訂購線是正確的?
