So I'm working on my application and I'm simply trying to declare a new array of strings. For some reason it wants an extra bracket to close the class at the end (even though the brackets are fine), and also after "private String[] addSentences = new String[3];" if asks for "{" instead of ";". In other words it wants to close something...I don't get it. Maybe you guys can help.
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() and playSentence() have not been created yet. The errors are below.
Description Resource Path Location Type Syntax error on token ";", { expected after this token Game.java /ChineseTones/src/org/chinesetones/teacher line 39 Java Problem
Description Resource Path Location 开发者_StackOverflow Type Syntax error, insert "}" to complete ClassBody Game.java /ChineseTones/src/org/chinesetones/teacher line 43 Java Problem
Thanks!
You cannot initialize class field that way..
Change
private String[] addSentences = new String[3];
addSentences[0] = "Hi";
addSentences[1] = "No";
addSentences[2] = "Yes";
to
private String[] addSentences = {"Hi", "No", "Yes"};
The other option is to just do
private String[] addSentences = new String[3];
and initialize the array in the class constructor.
public Game()
{
addSentences[0] = "Hi";
addSentences[1] = "No";
addSentences[2] = "Yes";
...
}
You can only have declarations outside of methods. So your addSentence assignements
addSentences[0] = "Hi";
addSentences[1] = "No";
addSentences[2] = "Yes";
must either be in a method, constructor, or be part of the declaration.
For a small, statically-defined list like your's, you can do this:
private String[] addSentences = {"Hi","No","Yes"};
If you had a larger initialization list you put that logic into your constructor.
public Game(){
addSentences[0] = "Hi";
addSentences[1] = "No";
addSentences[2] = "Yes";
....
}
精彩评论