【问题标题】:Asking user to enter specific number of strings then adding each string to array?要求用户输入特定数量的字符串,然后将每个字符串添加到数组中?
【发布时间】:2020-03-05 00:12:59
【问题描述】:

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

【问题讨论】:

  • 您还没有告诉我们,您面临的实际错误是什么,但我看到不少。 a) 在执行scan.nextInt(); 之后执行scan.nextLine(); b) 在循环中使用numOfStrings 变量for int x = 0; x &lt; numOfStrings; x++) .... c) 将StringBuilder paliString 更改为使用String[] d) 只需在循环中调用isPali 方法,不需要存储任何东西(这实际上消除了对c)的需要

标签: java arrays string stringbuilder palindrome


【解决方案1】:

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

这个可以解决问题。

    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.");
            }
        }
    }

【讨论】:

  • 太棒了!是否有将字符串添加到数组的部分?
  • 不,你是对的。我过分关注最小的更改以使输出正常工作,而错过了那部分。我会更新我的答案。
【解决方案2】:

我需要询问用户字符串的数量(仅由大写组成) 和小写字母、空格和数字)他们想要输入。这些 字符串需要存储在数组中。

我已经完成了您问题的上述部分。我希望,这将为您指明前进的方向。

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        boolean valid = true;
        int numOfStrings = 0;
        do {
            valid = true;
            System.out.print("Enter the number of strings: ");
            try {
                numOfStrings = Integer.parseInt(scan.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("Error: invalid input.");
                valid = false;
            }
        } while (!valid);
        String[] stringPali = new String[numOfStrings];
        String input;
        for (int i = 0; i < numOfStrings; i++) {
            do {
                valid = true;
                System.out.print("Enter a string consisting of only letters and digits: ");
                input = scan.nextLine();
                if (!input.matches("[A-Za-z0-9 ]+")) {
                    System.out.println("Error: invalid input.");
                    valid = false;
                }
            } while (!valid);
            stringPali[i] = input;
        }
    }
}

示例运行:

Enter the number of strings: a
Error: invalid input.
Enter the number of strings: 3
Enter a string consisting of only letters and digits: Arvind
Enter a string consisting of only letters and digits: Kumar Avinash
Enter a string consisting of only letters and digits: !@£$%^&*()_+
Error: invalid input.
Enter a string consisting of only letters and digits: Hello @
Error: invalid input.
Enter a string consisting of only letters and digits: Hello 123

如有任何疑问/问题,请随时发表评论。

祝你一切顺利!

[更新]

根据您的要求,我发布了以下更新,它只要求输入一次字符串,然后允许用户一个接一个地输入所有字符串:

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner scan = new Scanner(System.in);
        boolean valid = true;
        int numOfStrings = 0;
        do {
            valid = true;
            System.out.print("Enter the number of strings: ");
            try {
                numOfStrings = Integer.parseInt(scan.nextLine());
            } catch (NumberFormatException e) {
                System.out.println("Error: invalid input.");
                valid = false;
            }
        } while (!valid);

        String[] stringPali = new String[numOfStrings];
        String input;
        System.out.println("Enter " + numOfStrings + " strings consisting of only letters and digits: ");
        for (int i = 0; i < numOfStrings; i++) {
            do {
                valid = true;
                input = scan.nextLine();
                if (!input.matches("[A-Za-z0-9 ]+")) {
                    System.out.println("Error: invalid input.");
                    valid = false;
                }
            } while (!valid);
            stringPali[i] = input;
        }
    }
}

示例运行:

Enter the number of strings: 3
Enter 3 strings consisting of only letters and digits: 
Arvind
Kumar
He$ll0
Error: invalid input.
Avinash

如有任何疑问,请随时发表评论。

【讨论】:

  • 嗨,Arvind,有没有什么方法可以让用户输入任意数量的字符串(由用户提供),而无需在每次输入一个字符串时询问“输入一个由...组成的字符串”。只需询问一次“输入字符串:”并让用户一个一个地输入字符串(知道当用户按下 Enter 时移动到下一个字符串)?
  • @kak23 - 我希望解决方案对你有用。不要忘记接受答案,以便将来的访问者也可以放心地使用该解决方案。检查meta.stackexchange.com/questions/5234/… 了解如何操作。如有任何疑问/问题,请随时发表评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多