首页 / JAVA / java-将字符串更改为Char数组
java-将字符串更改为Char数组
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-将字符串更改为Char数组,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2080字,纯文字阅读大概需要3分钟。
内容图文
![java-将字符串更改为Char数组](/upload/InfoBanner/zyjiaocheng/678/85f5d99f43134cbd856426d770f6aa75.jpg)
将值存储为字符串后,如何遍历字符串并将每个值分配给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);
}
}
内容总结
以上是互联网集市为您收集整理的java-将字符串更改为Char数组全部内容,希望文章能够帮你解决java-将字符串更改为Char数组所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。