A
A
Amir Kenesbay2021-10-27 13:15:05
Java
Amir Kenesbay, 2021-10-27 13:15:05

In the array of words, find a word consisting only of numbers. If there are several such words, find the second one?

This is a learning problem. Java Collection Framework (with the exception of java.util.Arrays) and regular expressions cannot be used. I made my own implementation, but the code does not work for me, what could be the problem? Maybe I didn't convert the strings correctly?

public class Application {
    public static void main(String[] args) {
        String[] words = new String[]{"qqqqqqqqqqwe", "qwer", "123", "4321"};
        StringProcessor stringProcessor = new StringProcessor();
        stringProcessor.displayNumberContainingOnlyDifferentDigits(words);
    }
}

public class StringProcessor {
    public void displayNumberContainingOnlyDifferentDigits(String[] array) {
        for (String element : array) {
            boolean isDistinct = true;
            char[] chars = String.valueOf(element).toCharArray();
            for (int i = 0; i < chars.length - 1; i++) {
                for (int j = i + 1; j < chars.length; j++) {
                    if (chars[i] == chars[j] && chars[i] >= '0' && chars[i]<='9') {
                        isDistinct = false;
                        break;
                    }
                }
                if (!isDistinct) {
                    break;
                } else if (i == chars.length - 2) {
                    System.out.println("Число, состоящее только из различных цифр: " + element);
                    return;
                }
            }
        }
        System.out.println("Таких чисел нет!");
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-10-27
@Amir1807

Good afternoon.

In the array of words, find words consisting only of numbers.

Here is one possible solution to the problem:
import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {
        String[] words = new String[]{"qqqqqqqqqqwe", "qwer", "123", "4321"};
        char a = 'a';
        StringProcessor stringProcessor = new StringProcessor();
        List<String> wordsContainingOnlyDigits = stringProcessor.findWordsContainingDigits(words);
        wordsContainingOnlyDigits.forEach(System.out::println);
    }

}

class StringProcessor {

    /**
     * Метод находит слова, которые состоят только из цифр
     * @param words массив слов
     * @return список слов, состоящих из цифр
     */
    public List<String> findWordsContainingDigits(String[] words) {
        List<String> wordsContainingOnlyDigits = new ArrayList<>();
        // Итерируем по массиву слов
        for (String word : words) {
            // получаем массив символов из слова
            char[] wordChars = word.toCharArray();
            // Boolean[] isDigits = new Boolean[wordChars.length];
            boolean[] isDigits = new boolean[wordChars.length];
            // итерируем по массиву символов
            for (int i = 0; i < wordChars.length; i++) {
                char currentChar = wordChars[i];
                // проверяем является ли символ цифрой
                if (Character.isDigit(currentChar)) {
                    isDigits[i] = true;
                } else {
                    // если нет, то проверяем следующее слово
                    break;
                }
            }
            // если все значения isDigits true, то значит слово состоит из цифр
            if (areAllTrue(isDigits)) {
                // добавляем слово в список
                wordsContainingOnlyDigits.add(word);
            }
        }
        return wordsContainingOnlyDigits;
    }

    /**
     * Метод проверяет boolean массив на истинность
     * @param array boolean массив
     * @return boolean
     */
    private static boolean areAllTrue(boolean[] array)
    {
        for(boolean b : array) if(!b) return false;
        return true;
    }
}

If there are several such words, find the second one?

It's not entirely clear what the "second one" is.
As for your code, then:
why convert a string to a string and then get an array of characters
char[] chars = String.valueOf(element).toCharArray();

you can:
char[] chars = element.toCharArray();
here the iteration is incorrect:
for (int i = 0; i < chars.length - 1; i++) {
either like this: i < chars.length; or like this: i <= chars.length - 1;
there is a method to check whether a character is a digitCharacter.isDigit()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question