繁体   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