简体   繁体   中英

How to count if a specific string matches while iterating through a loop in java?

This is for a past homework assignment that I wasn't able to complete in time. I am a new programmer struggling with this method of the program CharacterSearch. I'm stuck on which boolean logic to use for my if statement, as well as how to find matches in the phrase using the pre-defined character variable. And example test is: character = "x" , phrase = "Xerox". Whereas X and x are different. The expected output should be count = 1. Edit: This problem should be answered without using arrays or lists.

 /**
 * Counts and returns the number of times the letter for this class 
 * occurs in the phrase. The class is case sensitive. 
 */
public int letterCount(String phrase)
{  
    Scanner jf = new Scanner(phrase);
    count = 0;
    for (int i = phrase.length(); i > 0; i--)
    { 
        jf.findInLine(character);         
        if(jf.hasNext())
        {
            count++;
            jf.next(); 


        }             
    }
    return count;
}

There you go:

/**
 * Counts and returns the number of times the letter for this class 
 * occurs in the phrase. The class is case sensitive. 
 */
public int letterCount(String phrase)
{
    int count = 0;
    // for every character in phrase ...
    for (int i = 0; i < phrase.length(); i++)
    { 
        // ... if it is the right one ...
        if(phrase.charAt(i) == character)
        {
            // ... increment the counter
            count++;
        }
    }
    return count;
}

You don't need any Scanner, and the code is fairly easy, readable and comprehensible.

Pretty much a duplicate of Simple way to count character occurrences in a string

I can't leave a comment yet because my rep is too low but I wanted to give you a solution you could use.

public int letterCount(String phrase)
{
    count = 0;
    for (int i = 0 ; i < phrase.length(); i++)
    {   
        String myLetter = phrase.substring(i, i + 1);
        if (myLetter.equals(character))
        {             
            count++;
        }
    }
    return count;
}

I figured out that I was iterating in the wrong direction, but more importantly I was not declaring a sub-string to check if my character matched the individual letters within the phrase.

Use String's substring with a compare().

public int letterCount(String phrase, String match)
{  
    int count = 0;
    for(int i=0;i<phrase.length()-1;i++){  //-1 avoid out-of-bound exception
        String letter = phrase.substring(i, i+1);
        if(letter.compareTo(match) == 0){
            count++;
        }
    }   

    return count;
}

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