簡體   English   中英

for循環中的if語句在JAVA中只運行一次

[英]If statement in for loop only running once in JAVA

我試圖做一個 if 語句,每次在字符串中找到動詞“我”或“我”時減去 2 分。 為此,我將字符串拆分為單獨的單詞。 為了測試,我將字符串更改為有 2 個“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);
                
                }

        }
    
    
}

} }

首先,您應該從您的方法verbcount返回評論分數。

其次,您將文本拆分兩次,一次是按單詞邊界 ("\s+"),但在您的方法verbcount ,您按換行符 ("\n") 將其拆分,因此該方法沒有按預期工作。

而不是要檢查的字符串,將words數組傳遞給該方法並且不要再次拆分它!

第三,你的 ifs 是嵌套的,所以s.contains ("I")只會被檢查,如果還有s.contains("me") - 這可能發生,因為你按行分割,但每行只檢查一次。 同樣,一旦你拆分單詞,你將永遠不會進入第二個 if 分支。 if在方法內,將其拉高一個級別以與第一個級別平行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM