简体   繁体   English

Android Studio:三位数的数字不加到++

[英]Android studio: Number with three digits do not add to count++

For practice purposes I'am building a braintrainer app. 出于练习目的,我正在构建一个Braintrainer应用程序。 It looks like this: 看起来像这样:

在此处输入图片说明

You can click on the number that you think is the correct one. 您可以单击您认为正确的号码。 Foreach click on a number the top right counter will increase with one. Foreach单击一个数字,右上角的计数器将增加一。 If you clicked the correct number the counter next to it will also increase with one. 如果单击正确的数字,则其旁边的计数器也会增加一。

My problem is this: 我的问题是这样的:

If the correct answer is made out of 2 digits. 如果正确答案是2位数字。 Both counters will increase. 两个计数器都将增加。 However, if the correct answer is made out of 3 digits. 但是,如果正确答案是3位数字。 Only the top right counter will increase. 只有右上方的计数器会增加。 Tracking some values give me these logs: 跟踪一些值会给我这些日志:

在此处输入图片说明

Here is the code that checks if the correct answer is pressed: 这是检查是否按下正确答案的代码:

public void guessFunction(View view){
    TextView guessView = (TextView) view;
    String buttonText = guessView.getText().toString();
    Log.i("correctAnswer: ", String.valueOf(correctAnswer));
    Log.i("buttonText: ", buttonText);

    if (buttonText == String.valueOf(correctAnswer)){
        correctCount++;
        TextView correctText = (TextView) findViewById(R.id.correctText);
        correctText.setText(String.valueOf(correctCount));
    }
    Log.i("count: ", String.valueOf(correctCount));


    shuffleFunction();
}

Please let me know if more codesamples are needed. 请让我知道是否需要更多的代码样本。

if (buttonText.equals(String.valueOf(correctAnswer)){ ... }

By putting object == otherObject you ask about the identity of two objects, whether or not they are one and the same instance (referenced by two variables). 通过放置object == otherObject您询问两个对象的身份 ,它们是否是一个实例(由两个变量引用)。 By putting object.equals(otherObject) you ask about the equality of two distinct objects, that is whether two objects are equal in a certain respect (implemented in an equals() method) or not. 通过放置object.equals(otherObject)您将询问两个不同对象的相等性,即两个对象在特定方面是否相等(在equals()方法中实现)。

In Java, you will almost always want to compare String s with the equals() method of the String class. 在Java中,几乎总是希望将String与String类的equals()方法进行比较。 In your case it is obvious that you are comparing two separate objects (you just created the second String with the static valueOf method of the String class); 在您的情况下,很明显,您正在比较两个单独的对象(您刚刚使用String类的静态valueOf方法创建了第二个String )。 therefore you need to use equals() . 因此,您需要使用equals()

This is wrong. 错了

if (buttonText == String.valueOf(correctAnswer))

Do not use == to compare strings in Java. 不要使用==来比较Java中的字符串。 Use equals instead. 请改用equals

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM