java 字符串 char数组_java-将字符串更改为Char数组

将值存储为字符串后,如何遍历字符串并将每个值分配给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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值