java - parseInt 行错误

标签 java android textview

所以,我正在玩我的这款安卓数学游戏。我很难弄清楚为什么会出现这些错误并尝试了一些在互联网上找到的代码,但它不起作用。

我在下面的代码没有错误。但是当我尝试运行它时,我的 logcat 中出现错误。

 check.setOnClickListener(new OnClickListener(){

        int x = Integer.valueOf(fn.getText().toString());
        int y = Integer.valueOf(sn.getText().toString());

        public void onClick(View v){
         String ope = op.getText().toString();


         if(ope=="+"){
             if(x + y == total2){
                 Toast.makeText(getApplicationContext(), "Answer is correct. You may proceed to level 2.", Toast.LENGTH_LONG).show();
             }
         }

         if(ope=="-"){
             if(x-y==total2){
                 Toast.makeText(getApplicationContext(), "Answer is correct. You may proceed to level 2.", Toast.LENGTH_LONG).show();
             }
         }  


         if(ope=="*"){
             if(x*y==total2){
                 Toast.makeText(getApplicationContext(), "Answer is correct. You may proceed to level 2.", Toast.LENGTH_LONG).show();
             }
         }

         if(ope=="/"){
             if(x/y==total2){
                 Toast.makeText(getApplicationContext(), "Answer is correct. You may proceed to level 2.", Toast.LENGTH_LONG).show();
             }
             else if(y/x==total2){
                 Toast.makeText(getApplicationContext(), "Answer is correct. You may proceed to level 2.", Toast.LENGTH_LONG).show();
             }

         }


         }});

这是我的 LOGCAT:

enter image description here

我正在解析它,对吧?那么,为什么我会遇到这些错误?

注意: fn 和 sn 是 textView,op 也是。 fn 和 sn 是用户放置操作数答案的地方,而 op 是运算符。游戏给出了这个随机数,用户应该点击 2 个操作数和一个运算符来制作一个方程式并能够得出给定的随机数。她/他的方程式的结果应该与给定的随机数相同。

谢谢你:)

最佳答案

您的代码中有两个问题。首先,正如 Henry 在您的回答中提到的,您需要添加以下几行:

  int x = Integer.valueOf(fn.getText().toString());
  int y = Integer.valueOf(sn.getText().toString());

onClick 方法内部

第二个问题是您正在使用 == 在所有 if 检查中进行字符串比较,例如:

     if(ope=="+")

您应该使用 String equals() 方法来进行字符串比较。更改它和其他 if 条件以使用 equals 方法,如此处所述:

     if(ope.equals("+"))

==比较两个引用是否指向同一个内存位置,而equals()比较字符串内容。

关于java - parseInt 行错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18290526/

相关文章:

java - hibernate - 线程中的异常 "main"java.lang.IndexOutOfBoundsException : Index: 0, 大小:0

java - 如何在特殊图中获取从叶子到根的所有路径

android - 仅当用户更改时更改 Android 上的 Wifi 状态

android - 操纵杆 API 安卓

android - 为什么 ProGuard 不混淆这些类?

Android:如何从 TextView 链接本地 HTML 文件

android - 如何使textview在android中的按钮点击事件中可见

java - OWLAPI : HermiT reasoner thows "UnsupportedDatatypeException" for data type from imported Ontology

使用 MAPI 访问 MAILBOX 的 Java 应用程序

android - 在 Arraylist 的 ListView 的列表项上显示值