문제

can you check why this code jumps to else with the conditions like e1="1", e2="2", e3=""

if (e1=="" || e2=="" || e3==""){
                Context context = getApplicationContext();
                CharSequence text = "Fill in all required fields!";
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(context, text, duration);
                toast.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
                toast.show();
            }
            else {
                m=Integer.parseInt(e1);
                std=Integer.parseInt(e2);
                nhv=Integer.parseInt(e3);
            rsl=((std*std)*((t1+t2)*(t1+t2)))/((m-nhv)*(m-nhv));
            if (Math.round(rsl) < rsl) {
                rsl = Math.round(rsl) +1; 
            } 
            else {
                rsl=Math.round(rsl);
            }
            et4.setText(""+rsl);
        }
도움이 되었습니까?

해결책

For String comparison you need to use .equals(), like e1.equals(""), or argubly better "".equals(e1).
The second form is argubly better as it can never throw a NullPointerException.

Keep in mind that only primitives int, etc. should be compared with ==, everything else should be compared with Object#equals(Object).

다른 팁

Simply use:

if (e1.isEmpty() || e2.isEmpty() || e3.isEmpty())

Since you are checking if your String is null or empty, use the method designed for it:

if (myString != null && !myString.isEmpty()) 
{ 

// doSomething

}

Anything else is prone to bugs or just isn't clear.

Note: This is available in Android 2.3.

Google also provides this via TextUtils:

if (TextUtils.isEmpty(value))
{
    // do something
}

Internally TextUtils.isEmpty() checks if the length of the String is 0 (and does a null check).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top