试图在实例变量中调用类

时间:2014-04-08 20:26:03

标签: java

  1. 添加称为currentPhrase一个实例变量来保存当前轮的短语
  2. 我的错误消息是“短语无法解析为变量” 我觉得它与新的String()有关?也许。
    或者它可能是短语短语=新短语();

    package edu.htc.java1.phrasegame;
    import edu.htc.java1.phrasegame.model.*;
    
    public class PhraseGameController {
    
        public void currentPhrase() {
            String p = new String();
            p = Phrase;
        }
    
    }
    

    package edu.htc.java1.phrasegame.model;
    
    import java.util.ArrayList;
    
    public class Phrase { 
        public void setPhrase(String phrase) {
            this.phrase = phrase; 
        }
    
        private String phrase;
    
        public Phrase(String phrase) {      
            phrase = phrase.toUpperCase();
            for(char c : phrase.toCharArray()) {
                letters.add(new Letter(c));
            }   
        }
    
        public String getPhrase() {
            return phrase;  
        }
    
        ArrayList<Letter> letters = new ArrayList<Letter>();
    
        public ArrayList<Letter> getLetters() {
            return letters;
        }
    
    
        public boolean guessLetter(char c) {
            // convert received character to letter
            Letter letter = new Letter(c);
    
            // loop through your list of letters
            for(Letter l : letters)   {
                // if list of letters contains same letter as the one you received then return true
                if(l.getLetter() == letter.getLetter()) {
                    letter.unhide();
                    // return true;
                }
            }
    
            // we did not find the letter, so we return false
            return false;   
        }
    }
    

2 个答案:

答案 0 :(得分:0)

我认为首先你必须导入这个包:

edu.htc.java1.phrasegame.model;

进入PhraseGameController类。通过在包声明下面添加这个,但在类声明之上:

import edu.htc.java1.phrasegame.model.*;

然后你将在该类中创建一个名为currentPhrase的新变量,如下所示:

private Phrase currentPhrase;

你从那里做的事情超出了你的问题的范围。

答案 1 :(得分:0)

实例变量是类的属性。

public class MyClass {
    private static String classVariable;

    private String instanceVariable;

    public String instanceMethod () {
        String localVariable = "hey";
    }

    public static String classMethod {

    }
}

要实例化变量,您必须使用new关键字:

SomeClass someInstance = new SomeClass();

或者如果你使用泛型:

List<SomeType> myList = new ArrayList<SomeType>();

所以在你的情况下它应该是:

public class PhraseGameController {
    private Phrase p = new Phrase();
}