括号和阵列声明的问题

时间:2011-06-28 18:51:45

标签: java android function error-handling declaration

所以我正在处理我的应用程序而我只是想尝试声明一个新的字符串数组。由于某种原因,它需要一个额外的括号来结束最后的类(即使括号很好),也需要“private String [] addSentences = new String [3];”如果要求“{”而不是“;”。换句话说,它想要关闭一些东西......我不明白。也许你们可以帮忙。

package org.chinesetones.teacher;

import java.util.ArrayList;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;
import org.chinesetones.teacher.Sentence;

public class Game extends Activity implements OnClickListener {
private String[] addStrings = new String[3];
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game);

// Setup button listeners...
View nextButton = findViewById(R.id.next_button);
nextButton.setOnClickListener(this);
View repeatButton = findViewById(R.id.repeat_button);
repeatButton.setOnClickListener(this);
}
public void onClick(View v){
    switch(v.getId()) {
    case R.id.next_button:
        giveSentence();
        break;
    case R.id.repeat_button:
        playSentence();
        break;
    }
}
private ArrayList<Sentence> sentences;
private String[] addSentences = new String[3];
addSentences[0] = "Hi";
addSentences[1] = "No";
addSentences[2] = "Yes";
}

还没有创建giveSentence()和playSentence()。错误如下。

描述资源路径位置类型 令牌“;”上的语法错误,{此符号之后的预期Game.java / ChineseTones / src / org / chinesetones / teacher line 39 Java问题

描述资源路径位置类型 语法错误,插入“}”以完成ClassBody Game.java / ChineseTones / src / org / chinesetones / teacher line 43 Java问题

谢谢!

2 个答案:

答案 0 :(得分:1)

你无法以那种方式初始化类字段..

更改

private String[] addSentences = new String[3];
addSentences[0] = "Hi";
addSentences[1] = "No";
addSentences[2] = "Yes";

private String[] addSentences = {"Hi", "No", "Yes"};

另一个选择就是

private String[] addSentences = new String[3];

并在类构造函数中初始化数组。

public Game()
{
   addSentences[0] = "Hi";
   addSentences[1] = "No";
   addSentences[2] = "Yes";
   ...
}

答案 1 :(得分:0)

您只能在方法之外进行声明。所以你的addSentence分配

addSentences[0] = "Hi"; 
addSentences[1] = "No"; 
addSentences[2] = "Yes"; 

必须位于方法,构造函数中,或者是声明的一部分。

对于像你这样的小型静态定义列表,你可以这样做:

 private String[] addSentences = {"Hi","No","Yes"}; 

如果您有一个更大的初始化列表,则将该逻辑放入构造函数中。

public Game(){
   addSentences[0] = "Hi"; 
   addSentences[1] = "No"; 
   addSentences[2] = "Yes"; 
   ....
}