我是Java的初学者,我正在开展一个需要我们制作句子句子的项目。我遇到的问题是,即使在找到带有形容词的第一个char匹配的名词后,while循环也不会停止。这就是我到目前为止所做的:
import java.io.*;
import java.util.*;
public class WordList {
int count = 1;
String Adj = randomAdj();
String Noun = randomNoun();
public String randomAdj() {
ArrayList<String> Adjs = new ArrayList<String>();
Scanner adj = null;
try {
adj = new Scanner(new File("adj.txt"));
} catch (Exception e) {
System.out.println("Couldn't not open file");
}
while (adj.hasNext()) {
Adjs.add(adj.next());
}
adj.close();
Random rand = new Random();
String randomAdj = Adjs.get(rand.nextInt(Adjs.size()));
System.out.printf("%s ", randomAdj);
return randomAdj;
}
public String randomNoun() {
ArrayList<String> Nouns = new ArrayList<String>();
Scanner noun = null;
try {
noun = new Scanner(new File("noun.txt"));
} catch (Exception e) {
System.out.println("Couldn't not open file");
}
while (noun.hasNext()) {
Nouns.add(noun.next());
}
noun.close();
Random rand = new Random();
String randomNoun = Nouns.get(rand.nextInt(Nouns.size()));
//System.out.printf("%s ", randomNoun);
return randomNoun;
}
public void randomWordStartingWith() {
while(Adj.charAt(0) != Noun.charAt(0))
{
count++;
//System.out.println(Adj + " " + randomNoun() + " " + count);
randomNoun();
}
System.out.println(Adj + " " + Noun + " " + count);
}
}
答案 0 :(得分:0)
问题是你的循环是永远不会更新Noun
(或Adj
):
while(Adj.charAt(0) != Noun.charAt(0))
{
count++;
Noun = randomNoun();
}
我删除了注释行:
//System.out.println(Adj + " " + randomNoun() + " " + count);
如果您要取消注释此行,则应使用Noun
的值,而不是再次调用randomNoun()
- 并且可能将其放在Noun =
行之后。