Проверка наличия одной и той же гласной дважды подряд

#java #string #char #switch-statement #java.util.scanner

#java #строка #символ #switch-оператор #java.util.scanner

Вопрос:

Я пытаюсь написать программу (на самом деле раздел программы), которая проверяет, повторяются ли какие-либо гласные дважды подряд. Например input = boo, output = o

Это код, который у меня есть для этого:

 //j - displays any vowels which occur consecutively
System.out.print("nj. ");

// have to give these variables a value
// otherwise the default statements won't work
char current_letter_1 = ' ', current_letter_2 = ' ';

//making strings for these characters so they are easier to output
String current_letter_1_string = String.valueOf(current_letter_1);
String current_letter_2_string = String.valueOf(current_letter_2);

//checking it against the sentence in lowercase so it's case insensitive
char low_letter = e.charAt(ind);

while (ind < a) {
    current_letter_1_string = String.valueOf(current_letter_1);
    current_letter_2_string = String.valueOf(current_letter_2);

    low_letter = e.charAt(ind);

    switch (low_letter) {
        case 'a', 'e', 'i', 'o', 'u', 'y':
            current_letter_1 = low_letter;
            break;
        default:
            break;
    }
    ind  = 1;
    switch (low_letter) {
        case 'a', 'e', 'i', 'o', 'u', 'y':
            current_letter_2 = low_letter;
            break;
        default:
            break;
    }
    if (current_letter_1 == current_letter_2) {
        System.out.print(current_letter_2_string.trim()   " ");
    } else {
    }
    //in case the same vowel is repeated more than twice in a row
}
while (low_letter == current_letter_2 amp;amp; ind < a) {
    low_letter = e.charAt(ind);
    ind  = 1;
}
if (low_letter != current_letter_2) {
    ind  = 1;
} else {
}
  

Кстати, поскольку это подразделы более крупной программы, я дам вам несколько значений переменных:

 Scanner sc(System.in);
String sentence = sc.nextLine();
int a = sentence.length();
String e = sentence.toLowerCase();
int ind = 0;
  

Кроме того, это для школы, поэтому, если это выглядит действительно странно, и вы бы сделали это совершенно по-другому, потерпите меня. Этот код вроде как работает, но вывод всегда странный, даже trim() если переменная по-прежнему выводится с пробелом перед ней. Кроме того, если sentence содержит более одной повторяющейся гласной, вывод снова искажается.
Любая помощь приветствуется.

Комментарии:

1. «переменная по-прежнему выводится с пробелом перед ней» , вы явно печатаете ее, добавляя " " в print . Или вы говорите о чем-то другом?

2. Нет, я имею в виду что-то другое. Это просто для разделения выходных данных. Я имею в виду, что перед первой выводимой переменной есть куча пробелов. Если вы хотите, я мог бы предоставить вам всю программу, и вы могли бы ее запустить, но не чувствуйте себя обязанным.

3. Это помогло бы увидеть некоторый образец ввода, некоторый образец вывода и тот результат, который вы действительно хотите.

4. Да, пожалуйста, предоставьте всю программу. Нам также нужны входные данные, а также ожидаемый и фактический результат.

5. Я понял. Кто-то опубликовал ответ. Спасибо за ответ.

Ответ №1:

Сохраняйте простоту.

 import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a text: ");
        String sentence = sc.nextLine();

        // Text in the lower case
        String sentenceLowerCase = sentence.toLowerCase();

        // Check all but the last char if it is same as its following character and if
        // it's a vowel
        for (int i = 0; i < sentence.length() - 1; i  ) {
            char ch = sentenceLowerCase.charAt(i);
            if (ch == sentenceLowerCase.charAt(i   1)
                    amp;amp; (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')) {
                System.out.println(ch);
            }
        }
    }
}
  

Пример запуска:

 Enter a text: Booster and rooster are different things
o
o
  

Еще один пример запуска:

 Enter a text: Faaster is a wrong spelling. Boost your vocabulary.
a
o
  

Ответ №2:

Вот полный код:

 import java.util.Scanner;
//also using java.lang.StringBuilder and java.lang.Character

public class Ch6Extra1 {

    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        
        String sentence;
        
        
        do {
            System.out.print("Enter a sentence: ");
            sentence = sc.nextLine();
            
        } while (sentence.equals(null) || sentence.equals(""));
            
        
        //variables used throughout code
        int ind = 0;
        char letter = sentence.charAt(ind);
        
        //a - character counter
        int a;
        a = sentence.length();
        
        System.out.print("na. "   a);
        
        //b - word counter
        int b;
        b = 0;
        
        while (ind < a) {
            
            letter = sentence.charAt(ind);
            
            switch (letter) {
                
                case ' ':
                    b  = 1;
                    break;
                    
                default:
                    break;
            }
            ind  = 1;
        }
        b  = 1;
        ind = 0;
        
        System.out.print("nb. "   b);
        
        //c - sentence reversed
        StringBuilder c = new StringBuilder(sentence);
        StringBuilder rev_sentence = c.reverse();
        
        System.out.print("nc. "   rev_sentence);
        
        //d - sentence to uppercase
        String d;
        d = sentence.toUpperCase();
        
        System.out.print("nd. "   d);
        
        //e - sentence to lowercase
        String e;
        e = sentence.toLowerCase();
        
        System.out.print("ne. "   e);
        
        //f, g and m - vowel, consonant, and punctuation count
        int f, g, m;
        f = 0;
        g = 0;
        m = 0;
        ind = 0;
        
        while (ind < a) {
            
            letter = sentence.charAt(ind);
            
            switch (letter) {
                case 'a', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y':
                    f  = 1;
                    break;
                    
                //in case it's a number, the code will pass to the next char
                case 1, 2, 3, 4, 5, 6, 7, 8, 9:
                    break;
                 
                //in case it's a special character, the code will pass to the next char
                case 'b', 'B', 'c', 'C', 'd', 'D', 'f', 'F', 'g', 'G', 'h', 'H', 
                     'j', 'J', 'k', 'K', 'l', 'L', 'm', 'M', 'n', 'N', 'p', 'P', 
                     'q', 'Q', 'r', 'R', 's', 'S', 't', 'T', 'v', 'V', 'w', 'W', 
                     'x', 'X', 'z', 'Z':
                    g  = 1;
                    break;
                    
                //checks for punctuation
                case '.', ',', ';', ':', '?', '!':
                    m  = 1;
                    break;
                    
                default:
                    break;
                    
            }
            ind  = 1;
        }
        
        System.out.print("nf. "   f);
        System.out.print("ng. "   g);
        ind = 0;
        
        
        //h - ASCII of first word
        
        System.out.print("nh. ");
        while (ind < a) {
            
            letter = sentence.charAt(ind);
            
            switch (letter) {
                
                case ' ':
                    ind = a -1;
                    break;
                    
                default:
                    System.out.print((int)letter   " ");
                    break;
            }
            ind  = 1;
        }
        ind = 0;
        
        //i - checks for word and in the sentence
        boolean i = e.contains("and");
        
        if (i == true) {
            System.out.print("ni. Yes");
        } else if (i == false) {
            System.out.print("ni. No");
        }
        
        
        //j - displays any vowels which occur consecutively
        
        System.out.print("nj. ");
        
        //have to give these variables a value otherwise the default statements won't work
        char current_letter_1 = ' ', current_letter_2 = ' ';
        
        //making strings for these characters so they are easier to output
        String current_letter_1_string  = String.valueOf(current_letter_1);
        String current_letter_2_string  = String.valueOf(current_letter_2);
        
        //checking it against the sentence in lowercase so it's case insensitive
        char low_letter = e.charAt(ind);
        
        while (ind < a) {
            
            current_letter_1_string  = String.valueOf(current_letter_1);
            current_letter_2_string  = String.valueOf(current_letter_2);
            
            low_letter = e.charAt(ind);
            
        
            switch (low_letter) {
                case 'a', 'e', 'i', 'o', 'u', 'y':
                    current_letter_1 = low_letter;
                    break;
                    
                default:
                    break;
                    
            }
            ind  = 1;
            
            switch (low_letter) {
                case 'a', 'e', 'i', 'o', 'u', 'y':
                    current_letter_2 = low_letter;
                    break;
                    
                default:
                    break;
                    
                    
            } if (current_letter_1 == current_letter_2) {
                System.out.print(current_letter_2_string.trim()   " ");
                
            } else {
            }
                
            //in case the same vowel is repeated more than twice in a row
            } while (low_letter == current_letter_2 amp;amp; ind < a){
                low_letter = e.charAt(ind);
                ind  = 1;
                
            } if (low_letter != current_letter_2) {
                ind  = 1;
            } else {
            }
        
        
        //k and l together - Upper and Lower case counters
        int k, l;
        k = 0;
        l = 0;
        
        boolean up_case = Character.isUpperCase(letter);
        boolean low_case = Character.isUpperCase(letter);
        
        while (ind < a) {
            
            up_case = Character.isUpperCase(letter);
            low_case = Character.isLowerCase(letter);
            letter = sentence.charAt(ind);
            
            if (up_case == true) {
                k  = 1;
                
            } else if (up_case == false) {
                if (low_case == true) {
                        l  = 1;
                        
                } else {
                }
                    
            } else {
            }
            ind  = 1;
        }
        
        System.out.print("nk. "   k);
        System.out.print("nl. "   l);
        
        System.out.print("nm. "   m);
        System.out.println("n");
        
    }
}
  

Я вижу, что кто-то опубликовал ответ. Я попробую это и отмечу, если это сработает.

Ответ №3:

Другой возможностью является использование регулярных выражений (то, с чем вы, возможно, захотите ознакомиться, продолжая изучать Java).

Тестовые данные

 String[] data =
        { "boo", "hello", "vacuUm", "keenly", "weedprOof" };
        
  

Шаблон. Он ищет любую гласную, за которой следует та же гласная.

  • регистр (?i:) игнорируется в совпадениях.
  • ([aeiou]) это группа захвата гласных
  • это предварительный (?=\1) просмотр нулевой ширины для ранее сопоставленной гласной из блока захвата (все это объясняется по ссылке выше).
 Pattern p = Pattern.compile("(?i:)([aeiou])(?=\1)");
  

Теперь просто перебирайте слова, ища одно или несколько совпадений с шаблоном для каждого слова. Это печатает одну букву для каждой найденной пары, включая шаблоны, подобные eee которым, которые будут двумя парами e's

 for (String d : data) {
    Matcher m = p.matcher(d);
    System.out.printf("%-10s -> ", d);
    boolean match = false;
    while (m.find()) {
        match = true;
        System.out.print(m.group(1)   " ");
    }
    System.out.println(match ? "" : "none found.");
}
  

Или подход без регулярных выражений

 String[] data =
        { "boo", "hello", "vacuUm", "keenly", "weedprOof" };

for (String d : data) {
    String orig = d;
    char[] chs = d.toLowerCase().toCharArray();
    System.out.printf("%-10s -> ", orig);
    boolean match = false;
    for (int i = 0; i < chs.length - 1; i  ) {
        if ("aeiou".indexOf(chs[i]) >= 0) {
            if (chs[i] == chs[i   1]) {
                match = true;
                System.out.print(chs[i]   " ");
            }
        }
    }
    System.out.println(match ? "" : "none found.");
    
}
  

Оба печатают

 boo        -> o 
hello      -> none found.
vacuUm     -> u 
keenly     -> e 
weedprOof  -> e o