0

I am tryng to make a simple counter that counts the number of times a character is present in a string, but I'm doing something wrong. When i try to print the counter it repeats a number of times.

import java.util.Scanner;

public class Uppgift5 {

public static void main(String[] args) {

    int counter = 0;

    Scanner scanner = new Scanner(System.in);

    System.out.println("What string do you want to search: ");
    String string = scanner.nextLine();

    System.out.println("What letter do you want to count? ");
    String letter = scanner.nextLine();


    for(int i=0; i<string.length(); i++ ) {
        if (string.charAt(i) == letter.charAt(0)){
            counter++; 
        }

        System.out.println("This string has " + counter + " " + letter);

    }
}
}

3 Answers 3

6

Place the

System.out.println("This string has " + counter + " " + letter);

outside of the loop and you're done.

Sign up to request clarification or add additional context in comments.

Comments

1

Place System.out.println("This string has " + counter + " " + letter); outside the for loop

Comments

0

The code should be...

int counter = 0;

Scanner scanner = new Scanner(System.in);

System.out.println("What string do you want to search: ");
String string = scanner.nextLine();

System.out.println("What letter do you want to count? ");
String letter = scanner.nextLine();


for(int i=0; i<string.length(); i++ ) {
    if (string.charAt(i) == letter.charAt(0)){
        counter++; 
    }

 }

System.out.println("This string has " + counter + " " + letter);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.