每个人都想知道为什么在 getWord 方法中,Try-catch block 中的变量单词返回 null,尽管它在我执行 system.println 时起作用。我认为我知道原因,但我也想知道,是否有一个 mwthod 来获取 try-catch block 内的变量。
public class JobToExecute
{
protected SpriteBatch batch ;
private String lemmaWord, word;
protected LemmaValidationJob finalResult;
protected BooleanTermAnswer firstWord, secondWord;
protected boolean answer;
private BitmapFont font;
public JobToExecute()
{
font = new BitmapFont(Gdx.files.internal(Constants.FONT_PATH));
font.setScale(0.6f);
server();
}
public void server()
{ final TaskConfiguration config = new TaskConfiguration(TaskType.RELATION);
config.setLanguage(Language.EN);
try
{
AnnotationManager.getInstance().getData(config , new MainThreadCallback<LemmaValidationJob>()
{
@Override
public void onSuccessInMainThread(LemmaValidationJob result)
{
finalResult = result;
lemmaWord = result.getLemma();
firstWord = result.getNextAnswerContainer();
secondWord = result.getNextAnswerContainer();
word = firstWord.getTerm()+" "+secondWord.getTerm();
firstWord.addAnswer(getAnswer(answer));
System.out.println(lemmaWord.toUpperCase());
System.out.println(word);
}
@Override
public void onFailureInMainThread(Throwable cause)
{
// TODO Auto-generated method stub
}
});
}
catch (AuthenticationRequiredException e)
{
e.printStackTrace();
System.err.println("You have to be logged in!");
}
}
public String getWord()
{
return word;
}
最佳答案
这取决于您在什么时候调用 getWord()。不要忘记您尚未在声明语句中初始化 word
,这意味着在您首先初始化它之前它将为 null。
private String word="";
我看到你正在 server() 调用中初始化它
word = firstWord.getTerm()+" "+secondWord.getTerm();
如果在执行上述行之前调用 getWord(),您将得到 null。
关于java - 如何获取 block 中的变量 Try -Catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32618801/