Java 如果。。。Else语句似乎返回了错误的输出

Java 如果。。。Else语句似乎返回了错误的输出,java,if-statement,Java,If Statement,我只是探索在java中测试Log类的不同方法,如果显示某个文本视图,则使用Log.d(),否则使用Log.e()记录异常错误 然而,logcat似乎显示了相反的输出。为什么会这样 我的主要活动代码: package com.example.dummy_app; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; public class Mai

我只是探索在java中测试Log类的不同方法,如果显示某个文本视图,则使用Log.d(),否则使用Log.e()记录异常错误

然而,logcat似乎显示了相反的输出。为什么会这样

我的主要活动代码:

package com.example.dummy_app;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (findViewById(R.id.editText).toString().equals("Happy Birthday!")) {
            Log.d("logMessage", "correct message shown");
        } else {
            Log.e("logMessage", "exception error");
        }
    }
}
XML--


更改:

findViewById(R.id.editText).toString().equals("Happy Birthday!")
致:


你的问题在于以下陈述

findViewById(R.id.editText).toString().equals("Happy Birthday!")
不要那样申报。这不是一个好的做法。首先,声明您的TextView如下:

TextView textView = (TextView) findViewById(R.id.textView);
String inputTxt = textView.getText().toString();
现在你终于可以用它做任何你想做的事情了,比如下面的输入

TextView textView = (TextView) findViewById(R.id.textView);
String inputTxt = textView.getText().toString();
所以您的完整代码应该如下所示

package com.example.dummy_app;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = (TextView) findViewById(R.id.textView);

        if (textView.getText().toString().equals("Happy Birthday!")) {
            Log.d("logMessage", "correct message shown");
        } else {
            Log.e("logMessage", "exception error");
        }
    }
}

你试过调试你的代码吗?这看起来是个绝佳的机会。只需检查
findViewById(R.id.editText).toString()
实际返回的内容。感谢@Amongalen的指导!说得好。我尝试使用Log.e(“logMessage”,findViewById(R.id.editText).toString()进行调试;而不是在else语句中。logcat将logMessage显示为androidx.appcompat.widget.AppCompatTextView{506d7be V.ED…..ID 0,0-0,0#7f070035 app:ID/editText}。这就解释了为什么它不等于“生日快乐”…谢谢Hasitha!我注意到EditText=(EditText)findViewById(R.id.EditText);对象应该是TextView--即editText=(editText)findViewById(R.id.editText);否则应用程序将崩溃。@unacorn Ops!我的错。我会更新答案。我仅读取
main活动
中的
edittext
变量。