gpt4 book ai didi

java - 我的代码是不是太重复了?

转载 作者:太空宇宙 更新时间:2023-11-03 11:27:46 25 4
gpt4 key购买 nike

我当时正在开发我的文字冒险游戏,想知道是否有更简单的方法来编写重复的代码块,例如我下面的代码块。

在此 block 中,向用户呈现 N、E、S、W 表示北、东、南和西。所以我分别编写每个监听器,并在每个监听器中包含一个 try/catch block 。但是整个代码块现在看起来确实是重复的。

这是代码块:

btnNorth.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tvIntro.setText("You go north");
String testString = "nothing";
try {
testString = Encounter.EncounterGeneratorText();
} catch (Exception e) {
e.printStackTrace();
}
testString = Encounter.EncounterGeneratorText();
tvIntro.setText(testString);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tvIntro.setText(testString);
}
});

btnEast.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tvIntro.setText("You go east");
String testString = "nothing";
try {
testString = Encounter.EncounterGeneratorText();
} catch (Exception e) {
e.printStackTrace();
}
testString = Encounter.EncounterGeneratorText();
tvIntro.setText(testString);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tvIntro.setText(testString);
}
});

btnSouth.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tvIntro.setText("You go south");
String testString = "nothing";
try {
testString = Encounter.EncounterGeneratorText();
} catch (Exception e) {
e.printStackTrace();
}
testString = Encounter.EncounterGeneratorText();
tvIntro.setText(testString);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tvIntro.setText(testString);
}
});

btnWest.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
tvIntro.setText("you go west");
String testString = "nothing";
try {
testString = Encounter.EncounterGeneratorText();
} catch (Exception e) {
e.printStackTrace();
}
testString = Encounter.EncounterGeneratorText();
tvIntro.setText(testString);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tvIntro.setText(testString);
};
});

最佳答案

您可以创建一个所有按钮都将使用的 OnClickListener,在该 OnClickListener 中,您将检测哪个按钮被单击并在 switch 语句中执行特定于方向的任务。

像这样:

private OnClickListener DirectionClickListner = new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.north:
//Set your strings for North
break;
case R.id.west:
//Set your strings for West
break;
case R.id.east:
//Set your strings for East
break;
case R.id.south:
//Set your strings for South
break;
}
}
};

关于java - 我的代码是不是太重复了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6961995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com