JAVA: String inside the String

This project is outside of Codecademy, but I am stuck within this:

Write a program that asks the user to enter two Strings, and prints the number of times that the second String appears within the first StThis text will be blurredring. For example, if the first String is “banana” and the second is “an”, the program prints 2.

Below is my code so far

Summary

```

Summary

import java.util.Scanner;

Summary

/**

Summary

*

Summary

* @author ChrisVo

Summary

*/

Summary

public class Assignment4 {

Summary

/**

Summary

* @param args the command line arguments

Summary

*/

Summary

public static void main(String[] args) {

Summary

// TODO code application logic here

Summary

Summary

Scanner answer = new Scanner(System.in);

Summary

//Prompt the user to enter a string

Summary

System.out.println(“Enter a word:”);

Summary

String input = answer.nextLine();

Summary

//Ask the user to enter a second String

Summary

//look at index method of string

Summary

System.out.println(“Enter another word:”);

Summary

String input2nd = answer.nextLine();

Summary

```

Please relocate this topic to the Community>Corner Bar section of the forums.

I can only move to community, I couldn’t find corner bar anywhere

You got it. Thanks. :slight_smile:

I’m not entirely sure how to help you, but I think this might help a bit. It covers how to check character occurrences within a string. You might be able to adapt it to multiple characters.

1 Like

I can only get 1 letter a to work so far

    //Ask the user to enter a second String
        //look at index method of string
        System.out.println("Enter another word:");
        String input2nd = answer.nextLine();
        int counter = 0;
        for(int i=0; i<input.length(); i++) {
            if(input.charAt(i) == input2nd.charAt(0)) {
                counter++;
                
            } 
        }
        System.out.println(input2nd + " appears " + counter + " times.");

so if i type banana for the first string
the second string is an
but the number come out as “3” because of character a instead of 2 for “an”

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.