我是新来的,我试着写一些代码,用来计数字符串字母,空格等等。因此,我设置数组长度为50。但是,当我稍后运行代码并输入超过50个字符时,它仍然可以运行,总计数可能超过50,为什么?谢谢。
import java.util.Scanner;
public class javaexcrises {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String astrg = new String();
char[] ch = new char[50];
int charcount=0;
int spaccount=0;
int numcount=0;
int othcount=0;
System.out.println("Please enter some word ");
if(scan.hasNextLine()){
astrg = scan.nextLine();
ch = astrg.toCharArray();
int i;
for(i=0;i<astrg.length();i++){
if(Character.isLetter(ch[i])){
charcount++;
}
else if(Character.isDigit(ch[i])){
numcount++;
}
else if(Character.isSpaceChar(ch[i])){
spaccount++;
}
else{
othcount++;
}
}
System.out.println("Character = "+charcount);
System.out.println("Space = "+spaccount);
System.out.println("Number = "+numcount);
System.out.println("Others ="+othcount);
System.out.println("Total = "+ch.length);
}
scan.close();
}
}发布于 2017-11-25 17:59:28
ch = astrg.toCharArray();toCharArray()返回对新数组的引用,该引用替换您分配的旧数组。这个新数组足够大,足以包含整个输入字符串。
发布于 2017-11-25 18:25:03
当我们执行astrg.toCharArray()时,它返回一个新分配的字符数组,其长度为该字符串的长度,其内容被初始化为包含该字符串表示的字符序列。
如果删除新的char50,也不会影响。
https://stackoverflow.com/questions/47488974
复制相似问题