if语句在for循环中只运行一次在JAVA

If statement in for loop only running once in JAVA

我正在尝试做一个 if 语句,每次在字符串中找到动词 'me' 或 'I' 时减去 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);
                
                }

        }
    
    
}

} }

首先,您应该 return 根据您的方法 verbcount 获得的评分。

其次,您将文本拆分两次,一次按单词边界 ("\s+"),但在您的方法中 verbcount 您按换行符 ("\n") 拆分文本,因此该方法不起作用如预期。

代替要检查的字符串,将 words 数组传递给该方法,不要再次拆分它!

第三,你的 ifs 是嵌套的,所以 s.contains ("I") 只会被检查,如果 s.contains("me") - 这可能发生,因为你按行分割,但每行只检查一次。另外,一旦你拆分单词,你将永远不会进入那一秒 if-branch。 将它拉高一个级别,使其与方法中的第一个 if 平行。