gpt4 book ai didi

java - 字符串转字符问题

转载 作者:行者123 更新时间:2023-12-01 09:27:39 24 4
gpt4 key购买 nike

我正在尝试编写一个简单的程序来计算用户输入的字符串中元音、辅音和空格的数量。我的 do while 循环和 if 语句有问题。它将所有内容都视为空格而不是元音或辅音。如果大家有什么建议,请告诉我! :)

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JOptionPane;

public class VowelCounter {

private static final Set<String>
vowels = new HashSet<>
(Arrays.asList("a","e","i","o","u","y"));

private static final Set<String>
cons = new HashSet<>
(Arrays.asList("b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","z"));

public static void main(String[] args) {

// ---------------------------------------------- VARIABLE DECLARATIONS
int vnum = 0;
int snum = 0;
int cnum = 0;
int i = 0;


// -------------------------------------------------------------- INPUT
String input = JOptionPane.showInputDialog
("Enter name (like your university)");
// --------------------------------------------------------- PROCESSING
char result = input.charAt(i);

do{
if (vowels.contains(result))
vnum++;

if (cons.contains(result))
cnum++;

if (!input.matches(("[a-zA-Z]+")))
snum++;


i++;
}while (i < input.length());

System.out.println("There are " + vnum + " vowels, " + cnum + " consonants, and " + snum + "spaces");

最佳答案

  1. 你不会找到 charSet<String> .

  2. 在循环中,您正在递增 i但没有选择相应的字符。

  3. 您不必要(且错误地)使用正则表达式,其中一个简单的 else就足够了。

试试这个:

private static final Set<Character> 
vowels = new HashSet<>
(Arrays.asList('a','e','i','o','u','y'));

private static final Set<Character>
cons = new HashSet<>
(Arrays.asList('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','z'));

...

for (int i = 0; i < input.length(); i++) {
Character result = input.charAt(i);
if (vowels.contains(result))
vnum++;
else if (cons.contains(result))
cnum++;
else
snum++;
}

关于java - 字符串转字符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39713676/

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