我正在尝试获取目标(初始为ImageView(id,并将整数id放入开关盒中,以查看相邻的视图并比较其可绘制内容,以确定玩家是否获胜或游戏是否继续。我将buttonPressed变量初始化为Integer,并使用parseInt((获取target的int值。
public void compareButton(int buttonPressed){
//int count = 0;
ImageView adjacent;
ImageView adjacentB;
switch (buttonPressed){
case R.id.imageButtonA: //this is where adjacent buttons are identified and compared
adjacent = findViewById(R.id.imageButtonB);
adjacentB = findViewById(R.id.imageButtonC);
if (target.getDrawable() == adjacent.getDrawable() && target.getDrawable() == adjacentB.getDrawable()) {
Toast.makeText(MainActivity.this, "You Win!", Toast.LENGTH_SHORT).show(); //Win condition
// } else if (target.getDrawable() == R.id.imageButtonE.getDrawable() & target.getDrawable() == R.id.imageButtonI.getDrawable()) {
//Toast.makeText(MainActivity.this, "You Win!", Toast.LENGTH_SHORT).show(); //Win condition
// } else if (target.getDrawable() == R.id.imageButtonD.getDrawable() & target.getDrawable() == R.id.imageButtonG.getDrawable()) {
//Toast.makeText(MainActivity.this, "You Win!", Toast.LENGTH_SHORT).show(); //Win condition
}
break;
case R.id.imageButtonB:
break;
我并不是为了调试而填写每一个案例。
我遇到的问题是,当我运行模拟器时,我收到一个错误,显示
Caused by: java.lang.NumberFormatException: For input string: "androidx.appcompat.widget.AppCompatImageButton{517eade VFED..C.. ...P..ID 45,381-304,628 #7f070072 app:id/imageButtonA}"
at java.lang.Integer.parseInt(Integer.java:521)
at java.lang.Integer.parseInt(Integer.java:556)
at com.example.connect3.MainActivity.switchColor(MainActivity.java:75)
以下是OnClickListener的代码:
public void switchColor(View view) {
//Button pressed, depending on user, switch's to that users color; identify adjacent button ID's; toast player control switch
if (player == 1) {
source = findViewById(R.id.yellow);
target = findViewById(view.getId());
target.setImageDrawable(source.getDrawable());
buttonPressed = Integer.parseInt(target.toString());
compareButton(buttonPressed);
player++;
Toast.makeText(MainActivity.this, "Player 2's Turn!", Toast.LENGTH_SHORT).show();
} else {
source = findViewById(R.id.red);
target = findViewById(view.getId());
target.setImageDrawable(source.getDrawable());
buttonPressed = Integer.parseInt(String.valueOf(target));
compareButton(buttonPressed);
player--;
Toast.makeText(MainActivity.this, "Player 1's Turn!", Toast.LENGTH_SHORT).show();
}
我不完全确定这一点上发生了什么,因为我认为我做的每件事都是正确的,但显然遗漏了一些东西。如有任何帮助,我们将不胜感激。
更改:
buttonPressed = Integer.parseInt(String.valueOf(target));
收件人:
buttonPressed=target.getId((;
解释:您的错误显示NumberFormatException意味着您正试图从String中获取int值,这是不可能解析的,或者简单地说,您的字符串不包含正确的int值,并且您正在以字符串形式传递(androidx.appcompat.widget…(,而您必须传递按钮I’d