要求用户输入特定数量的字符串,然后将每个字符串添加到数组中?

问题描述 投票:0回答:2

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;
    }
}

示例结果:

输入字符串数:8

输入字符串:

赛车

山露

BATMAN

塔可猫

甜品

是蛋黄酱的工具

交换爪子

一个丰田人一个丰田人

回文集是:赛车;塔可猫甜点心;交换爪子;丰田汽车,丰田汽车

java arrays string stringbuilder palindrome
2个回答
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();。这将处理您在用户点击Enter时获得的换行符。
  • 您不需要使用numOfStrings初始化StringBuilder。这只是以字符为单位预分配StringBuilder的大小。不是字符串数。无论哪种方式,都是没有必要的。 StringBuilder根据需要增长。
  • 我建议您检查一下我在for循环中所做的事情。这是最大的混乱,并且发生了很大变化。
  • 最后但并非最不重要:在将所有回文都添加到StringBuilder之后,将结果写入for循环之外。

编辑

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

请将该步骤与以前的版本进行比较。我还添加了此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.");
            }
        }
    }

-1
投票

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

我已经完成了您问题的以上部分。希望这会给您前进的方向。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.