Подсчет совпадающих символов в строке - PullRequest
0 голосов
/ 17 октября 2019

Меня попросили создать программу, которая запрашивает у пользователя два ввода, оба из которых должны быть сохранены в виде строк. Первый ввод может быть одним или несколькими словами, а второй ввод должен быть одним единственным символом. После того, как пользователь введет оба ввода, программа должна посчитать, сколько раз, если таковые имеются, единственный чартер появляется в первой строке. После завершения итерации первой строки программа должна вывести количество экземпляров второй строки. Пример:

"В тесте есть 1 вхождение 'e'."

Программа должна использовать цикл while и строковые значения. Это решение, которое у меня есть на данный момент, согласно параметрам, установленным профессором

public static void main(String[] args) {
        String inputEntry; // User's word(s)
        String inputCharacter; // User's sole character
        String charCapture; // Used to create subtrings of char
        int i = 0; // Counter for while loop
        int charCount = 0; // Counter for veryfiying how many times char is in string
        int charCountDisplay = 0; // Displays instances of char in string
        Scanner scan = new Scanner(System.in);

        System.out.print("Enter some words here: "); // Captures word(s)
        inputEntry = scan.nextLine(); 

        System.out.print("Enter a character here: "); // Captures char
        inputCharacter = scan.nextLine();

        if (inputCharacter.length() > 1 ||  inputCharacter.length() < 1) // if user is not in compliance
        {
            System.out.print("Please enter one character. Try again.");
            return; 
        } 
         else if (inputCharacter.length() == 1) // if user is in compliance
         {
          while( i < inputEntry.length()) // iterates through word(s)
           {
              charCapture = inputEntry.substring(charCount); // Creates substring of each letter in order to compare to char entry
                    if (charCapture.equals(inputCharacter))
                    {
                        ++charCountDisplay;

                    }

                    ++charCount;  
                    ++i;
            }

          System.out.print("There is " + charCountDisplay + 
                  " occurrence(s) of " + inputCharacter + " in the test.");

         }



        }

Эта итерация имеет ошибку. Вместо того чтобы считать все экземпляры переменной inputCharacter, она считает до одного, независимо от того, сколько экземпляров появилось в строке. Я знаю, что проблема в этой части кода:

while( i < inputEntry.length()) // iterates through word(s)
           {
              charCapture = inputEntry.substring(charCount); // Creates substring of each letter in order to compare to char entry
                    if (charCapture.equals(inputCharacter))
                    {
                        ++charCountDisplay;

                    }

                    ++charCount;  
                    ++i;
            }

Я просто не могу точно определить, что я делаю неправильно. Мне кажется, что переменная charCountDisplay обнуляется после каждой итерации. Разве этого не следует избегать, объявляя переменную в самом начале? ... Я один растерянный парень.

Ответы [ 3 ]

2 голосов
/ 17 октября 2019

Это неправильно

charCapture = inputEntry.substring(charCount);

не возвращает one char

попробуйте использовать inputEntry.charAt(charCount)

Еще один совет - определить ваши переменныеближе к тому месту, где вы их используете, а не к началу вашего метода, например:

String inputEntry; 
inputEntry = scan.nextLine(); 

Еще лучше было бы сделать inline

String inputEntry = scan.nextLine(); 

Это сделает ваш код намного более лаконичными читаемый.

Более краткий способ сделать ваш код:

Scanner scan = new Scanner(System.in);

System.out.print("Enter some words here: "); // Captures word(s)
String inputEntry = scan.nextLine(); 

System.out.print("Enter a character here: "); // Captures char
String inputCharacter = scan.nextLine();

// validate

// then

int len = inputEntry.length();
inputEntry = inputEntry.replace(inputCharacter, "");
int newlen = inputEntry.length();
System.out.format("There is %d occurrence(s) of %s in the test.%n", 
                                            len - newlen, inputCharacter);

output

Enter some words here: scarywombat writes code
Enter a character here: o
There is 2 occurrence(s) of o in the test.
1 голос
/ 17 октября 2019

inputEntry.chars (). Filter (tempVar -> tempVar == inputCharacter) .count () даст вам количество вхождений символа в строке.

String inputEntry = "text";
char inputCharacter = 'x';
System.out.print("There is " + inputEntry.chars().filter(tempVar -> tempVar == inputCharacter).count() + " occurrence(s) of " + inputCharacter + " in the text " + inputEntry + ".");
1 голос
/ 17 октября 2019

Вот полный MVCE :

пакет com.example.countcharacters;

/**
 * EXAMPLE OUTPUT:
 * Enter some words here: 
 * How now brown cow
 * Enter a character here: 
 * abc
 * Please enter one character. Try again.
 * Enter a character here: 
 * o
 * There are 4 occurrence(s) of o in the text How now brown cow.
 */
import java.util.Scanner;

public class CountCharacters {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        // Captures word(s)
        String inputEntry;
        System.out.println("Enter some words here: "); 
        inputEntry = scan.nextLine(); 

        // Captures char
        char inputCharacter;    
        while (true) {
            System.out.println("Enter a character here: ");
            String line = scan.nextLine();
            if (line.length() == 1) {
                inputCharacter = line.charAt(0);
                break;
            } else {
                // if user is not in compliance
                System.out.println("Please enter one character. Try again.");
            }
        } 

        // iterates through word(s)
        int charCountDisplay = 0;
        int i = 0;
        while(i < inputEntry.length())  {
            char c = inputEntry.charAt(i++);
            if (c == inputCharacter) {
                ++charCountDisplay;
            }
        }

        // Print results
        System.out.print("There are " + charCountDisplay + 
            " occurrence(s) of " + inputCharacter + 
            " in the text " + inputEntry + ".");
    }

}

ПРИМЕЧАНИЯ:

  • Вы можетеиспользуйте "char" и "String.charAt ()", чтобы упростить ваш код.
  • В общем случае предпочтительно объявлять переменные рядом с тем местом, где вы их используете (а не сверху).
  • Вы можете поставить свой тест на «только один символ» в своем собственном цикле.

'Надеюсь, это поможет!

...