我需要将句子中每个单词的首字母大写,并且第一个单词的首字母已经是大写的了,句子只能以句号或问号结尾。然后我还要计算出每个单词中元音字母和辅音字母的数量。
以下是我的代码:
该类名很奇怪,因为这是我计算机考试中的一个问题。程序有点可以工作,但是在主函数
以下是我的代码:
import java.io.*;
import java.util.*;
class ISC_Prac_2015
{
String s;
ISC_Prac_2015()
{
s="";
}
void input()throws IOException
{
System.out.println("Enter a sentence :");
BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
s=buf.readLine();
if(!((s.charAt(s.length()-1)=='.'||s.charAt(s.length()-1)=='?')))
{
System.out.println("Invalid input.");
System.exit(0);
}
}
char changeToUpper(char c)
{
return Character.toUpperCase(c);
}
boolean isVowel(char c)
{
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='A'||c=='E'||c=='I'||c=='O'||c=='U')
return true;
else
return false;
}
void main()throws IOException
{
input();
String s2=s.substring(0,s.length()-1);
StringBuffer s3=new StringBuffer(s2);
for(int x=0;x<s3.length()-1;x++)
if(s3.charAt(x)==' ')
s3.setCharAt(x+1,changeToUpper(s3.charAt(x+1)));
String s4=s3.toString();
System.out.println("\n"+s4);
StringTokenizer st=new StringTokenizer(s4);
String a[]=new String[st.countTokens()];
for(int x=0;x<st.countTokens();x++)
a[x]=st.nextToken();
/*replace the 4 lines above with String a[]=s4.split(" ");
and the program works, but why?*/
System.out.println("Word\t\t"+"Vowels\t\t"+"Consonants");
int vowel=0,consonant=0;
for(int x=0;x<a.length;x++)
{
for(int y=0;y<a[x].length();y++)
if(isVowel(a[x].charAt(y)))
vowel++;
else
consonant++;
if(a[x].length()<8)
System.out.println(a[x]+"\t\t"+vowel+"\t\t"+consonant);
else if(a[x].length()>=8&&a[x].length()<16)
System.out.println(a[x]+"\t"+vowel+"\t\t"+consonant);
else
System.out.println(a[x]+vowel+"\t\t"+consonant);
}
}
}
该类名很奇怪,因为这是我计算机考试中的一个问题。程序有点可以工作,但是在主函数
main()
的内部for
循环中,我出现了空指针异常。但是,当我在程序中使用split(" ")
函数时,程序会正确地运行,如我在代码中所注释的那样。但是为什么?难道StringTokenizer
和split(" ")
不是做同样的事情吗?
s1
,s2
)。具体是哪一行引发了“NullPointerException”? - ryanyuyu