将值存储为字符串后,如何遍历字符串并将每个值分配给char数组?还必须计算数组中每个元音的出现次数.
这是我当前的代码:
public class Part1_5 {
/**
* Method that gets user name and stores it as a string. Each value then
* assign to a char array. no of vowels are counted and no of each printed
*/
public static void main(String[] args) {
// Setting up scanner
Scanner scanner = new Scanner(System.in);
// declaring string for name
String userName = null;
// declaring ints to hold total no of each vowel
int totalOfA = 0;
int totalOfE = 0;
int totalofI = 0;
int totalofO = 0;
int totalofU = 0;
// Get user input for name
System.out.println("Please enter your Name...");
userName = scanner.nextLine();
for (int loop = 0; loop < userName.length(); loop++) {
// declaring char array
char[] letter = userName.toCharArray();
if (userName.charAt(0) == 'a') {
totalOfA++;
}
}
System.out.println(totalOfA);
}
}
解决方法:
在for循环中使用计数变量来指定userName字符串中的位置以对元音进行计数.
另外,您甚至不需要为执行的方法使用char数组.但是,如果确实需要一个,则应在启动for循环之前对其进行定义.为什么创建那么多次?
您询问了如何遍历String并将每个值分配给char数组,但是您不需要这样做:您可以简单地完成您的工作,char [] letter = userName.toCharArray();.
public class Part1_5 {
public static void main(String[] args) {
// Setting up scanner
Scanner scanner = new Scanner(System.in);
// declaring string for name
String userName = null;
// declaring ints to hold total no of each vowel
int totalOfA = 0,totalOfE = 0,totalofI = 0,totalofO = 0,totalofU = 0;
// Get user input for name
System.out.println("Please enter your Name...");
userName = scanner.nextLine();
// declaring char array (declare it once, before the loop)
char[] letter = userName.toCharArray();
for (int loop = 0; loop < userName.length(); loop++) {
// check and count for any vowel at every iteration of the loop
if (userName.charAt(loop) == 'a')
totalOfA++;
else if (userName.charAt(loop) == 'e')
totalOfE++;
else if (userName.charAt(loop) == 'i')
totalOfI++;
else if (userName.charAt(loop) == 'o')
totalOfO++;
else if (userName.charAt(loop) == 'u')
totalOfU++;
}
System.out.println(totalOfA);
}
}
标签:for-loop,char,string,java
来源: https://codeday.me/bug/20191030/1966157.html