简体   繁体   中英

If statement in for loop only running once in JAVA

Im trying to make an if statement that deducts 2 points for each time the verb 'me' or 'I' is found in a string. To do this I have split the string into separate words. To test I changed the string to have 2x "me". But the score is only deducted once instead of twice (as there are 2 x "me"). Tried adding a while loop but it just kept deducting until negative. Baby language please, I am a beginner coder. Thanks in advance

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);
                
                }

        }
    
    
}

} }

First you should return the review score from your method verbcount .

Second you split the text twice, once by word boundaries ("\s+"), but inside your method verbcount you split it by newlines ("\n") and therefore the method is not working as intended.

Instead of the string to review, pass the words array into that method and don't split it again!

Third your ifs are nested, so the s.contains ("I") will only be checked, if also s.contains("me") - this can happen because you split by lines, but only once per line. Also once you split words, you will never get into that second if-branch. Pull it up one level to be in parallel to the first if inside the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM