package hjroh0315.numbergame;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int SelN=-1;
Random Rand = new Random();
TextView Hint = (TextView)findViewById(R.id.textView);
EditText GuessInput = (EditText)findViewById(R.id.editText);
Button NewNumber = (Button)findViewById(R.id.button);
Button Guess = (Button)findViewById(R.id.button2);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NewNumber.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SelN = Rand.nextInt(100);
}
});
Guess.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String Guessed = GuessInput.getText().toString();
int Num = Integer.parseInt(Guessed);
if(SelN == -1)Hint.setText("Error: Number not generated.");
else if (Num < SelN)
{
Hint.setText("Up");
}
else if(Num > SelN)
{
Hint.setText("Down");
}
else
{
Hint.setText("Good");
SelN=-1;
}
}
});
}
}
当我运行此代码时,该应用程序立即崩溃。 它说第15行有一个错误。 但我不明白为什么。 有人可以向我解释一下吗? 附:这是一个猜测游戏,这是我的一个项目。
答案 0 :(得分:0)
你不应该在onCreate方法之外初始化textview:
TextView Hint = (TextView)findViewById(R.id.textView);
布局尚未膨胀,因此无法找到它
您应该在
之后复制onCreate方法中的所有findViewByIdsetContentView();
试试这样:
public class MainActivity extends AppCompatActivity {
int SelN=-1;
Random Rand = new Random();
TextView Hint;
EditText GuessInput;
Button NewNumber;
Button Guess;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Hint = (TextView)findViewById(R.id.textView);
GuessInput = (EditText)findViewById(R.id.editText);
NewNumber = (Button)findViewById(R.id.button);
Guess = (Button)findViewById(R.id.button2);
NewNumber.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SelN = Rand.nextInt(100);
}
});
Guess.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String Guessed = GuessInput.getText().toString();
int Num = Integer.parseInt(Guessed);
if(SelN == -1)Hint.setText("Error: Number not generated.");
else if (Num < SelN)
{
Hint.setText("Up");
}
else if(Num > SelN)
{
Hint.setText("Down");
}
else
{
Hint.setText("Good");
SelN=-1;
}
}
});
}
}