按钮文本到字符串
Buttons text to string
我有一个包含两个元素的按钮数组。
我想从按钮的文本创建一个字符串。
我正在努力解决的问题是 if 语句。基本上,它从不烤面包。为什么?
String word2 = "ok";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button buttons[] = new Button[2];
buttons[0] = (Button) findViewById(R.id.btn);
buttons[1] = (Button) findViewById(R.id.btn2);
buttons[0].setText("o");
buttons[1].setText("k");
buttons[0].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String word = "";
for (int i = 0; i < 2; i++) {
word += buttons[i].getText().toString();
}
if (word == word2) {
Toast.makeText(getApplicationContext(), "Good",
Toast.LENGTH_LONG).show();
}
}
});
}
改变这个:
if (word == word2) {
有了这个:
if(word.equals(word2)) {
您无法将 String
与 ==
进行比较
- 写出更好的问题(基本上是问题)
- Compare string with
.equals()
not ==
.
只需使用 if(word.equals(word2) {
为什么?第一个是内容比较,但第二个我只是
参考比较:
String a = new String("x");
String b = new String("x");
if(a==b){
System.out.println("It wont work");
}else if(a.equals(b)){
System.out.println("It will");
}
永远不要使用 new String(),它只是为了证明
- 我一定要写。
换行
for (int i = 0; i < 2; i++) {
进入
for (int i = 0; i < buttons.length; i++) {
因此您的应用程序将更容易更改
我有一个包含两个元素的按钮数组。
我想从按钮的文本创建一个字符串。
我正在努力解决的问题是 if 语句。基本上,它从不烤面包。为什么?
String word2 = "ok";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button buttons[] = new Button[2];
buttons[0] = (Button) findViewById(R.id.btn);
buttons[1] = (Button) findViewById(R.id.btn2);
buttons[0].setText("o");
buttons[1].setText("k");
buttons[0].setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String word = "";
for (int i = 0; i < 2; i++) {
word += buttons[i].getText().toString();
}
if (word == word2) {
Toast.makeText(getApplicationContext(), "Good",
Toast.LENGTH_LONG).show();
}
}
});
}
改变这个:
if (word == word2) {
有了这个:
if(word.equals(word2)) {
您无法将 String
与 ==
- 写出更好的问题(基本上是问题)
- Compare string with
.equals()
not==
.
只需使用if(word.equals(word2) {
为什么?第一个是内容比较,但第二个我只是 参考比较:
String a = new String("x");
String b = new String("x");
if(a==b){
System.out.println("It wont work");
}else if(a.equals(b)){
System.out.println("It will");
}
永远不要使用 new String(),它只是为了证明
- 我一定要写。
换行
for (int i = 0; i < 2; i++) {
进入
for (int i = 0; i < buttons.length; i++) {
因此您的应用程序将更容易更改