我正在練習編寫Java代碼,我試圖解決這個問題,但我不知道如何解決它。我會告訴你我的代碼。線程「主」異常java.util.NoSuchElementException
在我Fortunecookie.java是:
public class FortuneCookie {
private String subjectList;
private String objectList;
private String verbList;
private int sWord;
private int oWord;
private int vWord;
private Random random = new Random() enter code here;
public FortuneCookie() {
subjectList = "I#You#He#She#It#They";
objectList = "me#you#him#her#it#";
verbList = "hate#love#deny#find#hear#forgive#hunt#win#teach";
}
public String getFortuneMsg() {
StringTokenizer subSt = new StringTokenizer(subjectList,"#");
StringTokenizer objSt = new StringTokenizer(objectList,"#");
StringTokenizer verbSt = new StringTokenizer(verbList,"#");
sWord = subSt.countTokens();
oWord = objSt.countTokens();
vWord = verbSt.countTokens();
int c1 = random.nextInt(sWord);
String line1 = " ";
String line2 = " ";
String line3 = " ";
while(subSt.hasMoreTokens()) {
line1 = subSt.nextToken("#");
for (int i=0;i<sWord;i++)
if (i == c1) {
break;
}
else{
line1 = subSt.nextToken("#");
}
}
int c2 = random.nextInt(oWord);
while(objSt.hasMoreTokens()) {
line2 = objSt.nextToken("#");
for (int i=0;i<sWord;i++)
if (i == c2) {
break;
}
else{
line2 = objSt.nextToken("#");
}
}
int c3 = random.nextInt(vWord);
while(verbSt.hasMoreTokens()) {
line3 = verbSt.nextToken("#");
for (int i=0;i<sWord;i++)
if (i == c3) {
break;
}
else{
line3 = verbSt.nextToken("#");
}
}
return line1+line2+line3;
}
public void setSubjectList(String aSubjectList) {
subjectList = aSubjectList;
}
public void setObjectList(String aObjectList) {
objectList = aObjectList;
}
public void setVerbList(String aVerbList) {
verbList = aVerbList;
}
public void print() {
StringTokenizer subSt = new StringTokenizer(subjectList,"#");
StringTokenizer objSt = new StringTokenizer(objectList,"#");
StringTokenizer verbSt = new StringTokenizer(verbList,"#");
sWord = subSt.countTokens();
oWord = objSt.countTokens();
vWord = verbSt.countTokens();
System.out.println("Subject List : "+subjectList);
System.out.println("Object List : "+objectList);
System.out.println("Verb List : "+verbList);
}
在我FortuneCookieTest.java是
public class FortuneCookieTest {
public static void main(String[] args) {
FortuneCookie ck = new FortuneCookie();
System.out.println(ck.getFortuneMsg());
}
}
當我編譯並運行它:
//Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(Unknown Source)
at java.util.StringTokenizer.nextToken(Unknown Source)
at CS_111_Homework_2.FortuneCookie.getFortuneMsg(FortuneCookie.java:39)
at CS_111_Homework_2.FortuneCookieTest.main(FortuneCookieTest.java:6)
我怎樣才能解決這個問題?
謝謝你們的一切answer.I現在可以解決它。再次感謝你。 :) –