gpt4 book ai didi

java - 如何打印元音、数字等列表?

转载 作者:行者123 更新时间:2023-11-30 06:08:41 24 4
gpt4 key购买 nike

这个程序接受一个语句,然后打印元音、数字等的数量。我想知道如何打印作为输入给出的数字和元音列表。有人可以告诉我如何使用数组来完成此操作吗?

package strings;
import java.util.Scanner;

public class Strings
{
public static void main(String [] abc)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a statement:");
String statement = sc.nextLine().toLowerCase();
System.out.println("------------------------------------------------");
System.out.println("Total characters: " + statement.length());
int vowels = 0,num = 0,spaces = 0,spl = 0,others = 0;

char alpha;

for (int i = 0;i < statement.length();i++)
{
alpha = statement.charAt(i);
if (alpha == 'a' || alpha == 'e' || alpha == 'i' || alpha == 'o' || alpha == 'u')
{
vowels++;
}
else if (alpha == ' ')
{
spaces++;
}
else if (alpha == '0' || alpha == '1' || alpha == '2' || alpha == '3' || alpha == '4' || alpha == '5' || alpha == '6' || alpha == '7' || alpha == '8' || alpha == '9')
{
num++;
}
else if (alpha =='!' || alpha =='@' || alpha =='#' || alpha =='$' || alpha =='%' || alpha =='^' || alpha =='&' || alpha =='*' || alpha =='(' || alpha ==')')
{
spl++;
}
else
{
others++;
}
}
System.out.println("Total vowels: " + vowels);
System.out.println("Total spaces: " + spaces);
System.out.println("Total numerics: " + num);
System.out.println("Total special characters: " + spl);
System.out.println("Other characters: " + others);
System.out.println("");



for (int i = 0;i < statement.length();i++)
{
System.out.println("The vowels are as follows:");
System.out.println(alpha);
}
}
}

最佳答案

您可以使用java.util.ArrayList ,例如,为元音创建一个ArrayList:

List<Character> vowelList = new ArrayList<>();
...
for (int i = 0; i < statement.length(); i++) {
if (alpha == 'a' || alpha == 'e' || alpha == 'i' || alpha == 'o' || alpha == 'u') {
vowels++;
vowelList.add(alpha);
} else {

...
}
System.out.println("The vowels are as follows:");
System.out.println(vowelList);

关于java - 如何打印元音、数字等列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50723590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com