【问题标题】:How to convert a string to char array then return the array to another class?如何将字符串转换为 char 数组然后将数组返回给另一个类?
【发布时间】:2019-03-15 16:26:58
【问题描述】:

我需要程序接受用户字符串,然后在单独的行上输出字符串的每个字符。

这是我的 Main 类中执行菜单的方法。案例 6 是我要开始工作的案例。

  private static void executeMenuChoice(int menuChoice, StringManipulator myManipulator)
{
    switch (menuChoice)
    {
        case 1:
            String userUpperCase = myManipulator.listUppercase();
            JOptionPane.showMessageDialog(null, "Your string value converted to uppercase is: " + userUpperCase);
            break;
        case 2:
            String listVowels = myManipulator.listVowels();
            JOptionPane.showMessageDialog(null, "Here are the vowels in your string: " + listVowels);
            break;
        case 3:
            String replaceVowels = myManipulator.replaceVowels();
            JOptionPane.showMessageDialog(null, "Here is your string with values replaced by underscores: " + replaceVowels);
            break;
        case 4:
            int countVowels = myManipulator.countVowels();
            JOptionPane.showMessageDialog(null, "Here is the number of vowels in your string: " + countVowels);
            break;
        case 5:
            String reverseString = myManipulator.reverseString();
            JOptionPane.showMessageDialog(null, "Here is your string in reverse: " + reverseString);
            break;
        case 6:
            char[] character = myManipulator.newlineString();
            JOptionPane.showMessageDialog(null, "Here is your string with each character on a separate line: " + character);
            break;
        case 7:
            JOptionPane.showMessageDialog(null, "You are now exiting the program.");
            break;
    }

这是我的第二个类中将用户字符串转换为 char 数组以将字符串的每个字符输出到不同行的方法。

        public char[] newlineString() {

    String newLine = getUserString();

    char[] chars = newLine.toCharArray();

    return chars;
}

【问题讨论】:

  • System.out.println(String.join(System.lineSeparator(), "abc".split("")));
  • 我花了好几遍才知道你在问什么。
  • 用户输入一个字符串值并选择菜单上的选项6“在单独的行上打印字符串值的每个字符”后。我需要公共 char[] newlineString() 方法来获取 userString 并获取字符并将它们输出到单独的行中。然后返回给主类输出给用户。
  • 既然我们似乎无法沟通:试试这个,JOptionPane.showMessageDialog(null, String.join(System.lineSeparator(), "Zayne".split("")));

标签: java arrays string char return


【解决方案1】:

我认为问题在于您试图将数组连接到文本字符串。

试试这样:

case 6:
        char[] character = myManipulator.newlineString();
        JOptionPane.showMessageDialog(null, 
               "Here is your string with each character on a separate line: " +
                String.join("\n", character));
        break;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 2014-01-04
    • 2015-11-30
    • 2011-10-04
    • 2019-08-04
    • 2015-12-19
    • 2012-05-16
    相关资源
    最近更新 更多