首页 > 解决方案 > 要求用户输入特定数量的字符串,然后将每个字符串添加到数组中?

问题描述

java新手。我需要询问用户他们想要输入的字符串数量(仅由大小写字母、空格和数字组成)。这些字符串需要存储在一个数组中。然后我创建了一个布尔方法来判断这些字符串是否是回文(忽略空格和大小写)。如果它是回文,那么我添加到结果列表中以便稍后打印。我对如何要求用户输入确切数量的字符串以及如何检查每个单独的字符串感到困惑。我必须使用 StringBuilder。这就是我到目前为止所拥有的(有点乱,抱歉)。我觉得我在使用 StringBuilder/array 错误,我该如何解决这个问题?

public class Palindromes {

    public static void main(String[] args) {
        int numOfStrings;

        Scanner scan = new Scanner(System.in);  // Creating Scanner object
        System.out.print("Enter the number of strings: ");
        numOfStrings = scan.nextInt();

        System.out.print("Enter the strings: ");
        StringBuilder paliString = new StringBuilder(numOfStrings);
        for(int n=0; n < paliString; n++){
            paliString[n] = scan.nextLine();
            scan.nextLine();

            String[] stringPali = new String[numOfStrings];

            StringBuilder str = paliString;
            if(isPali(userString)){
                paliString = append.userString;
            }
            System.out.println("The palindromes are: " + userString ";");
        }

    static boolean isPali(String userString) {
        int l = 0;
        int h = userString.length() - 1;

        // Lowercase string
        userString = userString.toLowerCase();

        // Compares character until they are equal
        while (l <= h) {

            char getAtl = userString.charAt(l);
            char getAth = userString.charAt(h);

            // If there is another symbol in left
            // of sentence
            if (!(getAtl >= 'a' && getAtl <= 'z'))
                l++;

            // If there is another symbol in right
            // of sentence
            else if (!(getAth >= 'a' && getAth <= 'z'))
                h--;

            // If characters are equal
            else if (getAtl == getAth) {
                l++;
                h--;
            }

            // If characters are not equal then
            // sentence is not palindrome
            else
                return false;
        }

        // Returns true if sentence is palindrome
        return true;
    }
}

样品结果:

Enter the number of strings: 8

Enter the strings:

Race Car

Mountain Dew

BATMAN

Taco Cat

Stressed Desserts

Is Mayonnaise an instrument

swap paws

A Toyotas a Toyota

The palindromes are: Race Car; Taco Cat; Stressed Desserts; swap paws; A Toyotas a Toyota

标签: javaarraysstringstringbuilderpalindrome

解决方案


因为我认为回答这个问题的最佳方法是帮助你逐步学习,所以我试图坚持你关于如何解决这个问题的最初想法,并以最小的变化编辑你的主要方法。

这个可以解决问题。

    public static void main(String[] args) {
        int numOfStrings;

        Scanner scan = new Scanner(System.in);  // Creating Scanner object
        System.out.print("Enter the number of strings: ");
        numOfStrings = scan.nextInt();
        scan.nextLine(); // you need this to catch the enter after the integer you entered

        System.out.print("Enter the strings: ");
        StringBuilder paliString = new StringBuilder();
        for (int n = 0; n < numOfStrings; n++) {
            String userString = scan.nextLine();
            if (isPali(userString)) {
                if (paliString.length() > 0) {
                    paliString.append("; ");
                }
                paliString.append(userString);
            }
        }
        System.out.println("The palindromes are: " + paliString);
    }

主要变化:

  • scan.nextLine();在读取字符串数后立即添加。这会处理用户按回车时获得的换行符。
  • 您不需要使用 numOfStrings 初始化 StringBuilder。这只是以字符为单位预先分配 StringBuilder 的大小。不是字符串的数量。无论哪种方式,都没有必要。StringBuilder 根据需要增长。
  • 我建议你检查一下我在 for 循环中做了什么。这是最大的混乱,并且发生了重大变化。
  • 最后但同样重要的是:在所有回文都已添加到 StringBuilder 之后,写入结果需要在 for 循环之外。

编辑

根据您的评论,在下一次迭代中,我将 StringBuilder 的用法更改为 ArrayList 的用法。(这是完全不同的)我在这里使用它是因为 Java 中的列表按需增长。而且由于回文数可能不等于输入字符串的数量,所以这是要走的路。要真正将它分配给一个数组,总是可以调用String[] paliStringsArray = paliStrings.toArray(new String[]{});,但由于 ArrayLists 已经使用了一个底层数组并且不需要生成你想要的输出,我没有把它放到新版本中。

请将此步骤与上一版本的差异进行比较。我还添加了这String.join("; ", paliStrings)部分,它创建了你想要的输出。

    public static void main(String[] args) {
        int numOfStrings;

        Scanner scan = new Scanner(System.in);  // Creating Scanner object
        System.out.print("Enter the number of strings: ");
        numOfStrings = scan.nextInt();
        scan.nextLine(); // you need this to catch the enter after the integer you entered

        System.out.print("Enter the strings: ");
        List<String> paliStrings = new ArrayList<>();
        for (int n = 0; n < numOfStrings; n++) {
            String userString = scan.nextLine();
            if (isPali(userString)) {
                paliStrings.add(userString);
            }
        }
        System.out.println("The palindromes are: " + String.join("; ", paliStrings));
    }

现在到最后一步。Arvind Kumar Avinash实际上解决了我在最初的问题中也错过的部分。(我以后会更仔细地阅读)。他正在验证用户输入。所以在最后一次迭代中,我以修改的方式添加了他的验证代码。我将它放入一种方法中,因为我认为这会使事情变得更清晰并摆脱boolean valid变量的必要性。

    public static void main(String[] args) {
        int numOfStrings;

        Scanner scan = new Scanner(System.in);  // Creating Scanner object
        System.out.print("Enter the number of strings: ");
        numOfStrings = scan.nextInt();
        scan.nextLine(); // you need this to catch the enter after the integer you entered

        System.out.print("Enter the strings: ");
        List<String> paliStrings = new ArrayList<>();
        for (int n = 0; n < numOfStrings; n++) {
            String userString = readNextLine(scan);
            if (isPali(userString)) {
                paliStrings.add(userString);
            }
        }
        System.out.println("The palindromes are: " + String.join("; ", paliStrings));
    }

    static String readNextLine(Scanner scanner) {
        while (true) {
            String userString = scanner.nextLine();
            if (userString.matches("[A-Za-z0-9 ]+")) {
                return userString;
            } else {
                System.out.println("Error: invalid input.");
            }
        }
    }

推荐阅读