Jeg har løst en lignende opgave for sjov, en gang hvor jeg ikke havde så meget at lave. Min løsning tager kun udgangspunkt i et enkelt bogstav, men brugeren kan selv vælge hvilket et han ønsker.
Min kode ser ud som følger:
- import java.util.Scanner;
- public class LetterCount {
-
- private static Scanner reader = new Scanner(System.in);
- private static int frequency = 0;
-
- public static void main(String[] args){
-
- System.out.println("Please type in a line of text!");
- String[] letters = reader.nextLine().trim().toLowerCase().split("");
-
- System.out.println("Which letter do you want to search for?");
- String choosenLetter = reader.nextLine().toLowerCase();
-
- for (int i = 0; i < letters.length; i++){
-
- String letterFromArray = letters[i];
- if (letterFromArray.equals(choosenLetter)) {
- frequency++;
- }
- }
-
- System.out.println("The letter '"+choosenLetter+"' is occuring "+frequency+" times in the text line!");
- System.out.println("This Letter Counter is made by Martin Rohwedder (2010)");
-
- }
- }
et Output kunne være som følger:
Please type in a line of text!
Dette er min seje tekst!
Which letter do you want to search for?
E
The letter 'e' is occuring 6 times in the text line!
This Letter Counter is made by Martin Rohwedder (2010)