我一直在解决一些练习问题并对此代码提出疑问。我能够使用不同的方法来解决这个问题,但我不明白为什么这个例子不起作用。代码要求输入,直到用户输入两次相同的输入,然后它应该显示在结束程序之前重复输入。
我得到了:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: any>
word 变量的最后一行出错。有什么想法吗?
import java.util.ArrayList;
import java.util.Scanner;
public class MoreThanOnce {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// create here the ArrayList
ArrayList<String> words = new ArrayList<String>();
while (true){
System.out.print("Type a word: ");
String word = reader.nextLine();
if(!words.contains(word)){
words.add(word);
}else{
break;
}
}
System.out.println("You gave the word " + word + " twice");
}
}
答案 0 :(得分:0)
您的代码无法编译。要在末尾显示的变量“word”不在正确的范围内:您在while循环中声明它但尝试在此循环之外使用它。 只需改变这样的事情:
import java.util.ArrayList;
import java.util.Scanner;
public class MoreThanOnce {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// create here the ArrayList
String word; //variable declared before loop
ArrayList<String> words = new ArrayList<String>();
while (true){
System.out.print("Type a word: ");
word = reader.nextLine();
if(!words.contains(word)){
words.add(word);
}else{
break;
}
}
System.out.println("You gave the word " + word + " twice");
}
希望它有所帮助。
的Mathias
答案 1 :(得分:0)
声明&#34;字符串字&#34;在循环之前变量。
import java.util.ArrayList;
import java.util.Scanner;
public class MoreThanOnce {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
// create here the ArrayList
String word;
ArrayList<String> words = new ArrayList<String>();
while (true) {
System.out.print("Type a word: ");
word = reader.nextLine();
if (!words.contains(word)) {
words.add(word);
} else {
break;
}
}
System.out.println("You gave the word " + word + " twice");
}
}
答案 2 :(得分:0)
您使用的是NetBeans吗?
如果是,则存在一个开放的错误