Java 程序 - "Erroneous tree type"问题



我一直在研究一些实践问题,对这段代码有一个问题。我可以用另一种方法算出来,但我不明白为什么这个例子不起作用。代码要求输入,直到用户两次输入相同的输入,然后在结束程序之前显示重复的输入。

我得到了:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type: any>

最后一行变量出错。什么好主意吗?

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");
    }
}

您的代码无法编译。你想在最后显示的变量"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

您使用NetBeans吗?

如果是,则存在一个开放的bug

在while循环前声明"String 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 
    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");
  }
}

相关内容

最新更新