【问题标题】:How to compare content of an string array to a string如何将字符串数组的内容与字符串进行比较
【发布时间】:2016-04-11 06:50:47
【问题描述】:

如果TextView 中的当前字符串是“Heads”,我在使用if 语句执行某些操作时遇到问题。

这是我当前的代码:

 if (myCoin = "Heads") {

                 ImageView img = (ImageView) findViewById(R.id.imageView);
                 img.setImageResource(R.mipmap.heads);

             }

“myCoin”是包含单词“Heads”和“Tails”的字符串的名称。

final String[] myCoin= {"Heads", "Tails"};

生成随机数时,TextView 会根据数字显示其中一个单词。但是,由于(myCoin = "Heads") 下的波浪形红线显示为:

,我无法运行代码
Incompatible Types.

Required: Java.Lang.String[]

Found: Java.Lang.String

如您所见,我的字符串 DOES 有方括号,所以我想知道是否可以在 if 语句中使用 myCoin

已解决

【问题讨论】:

  • myCoin 是一个final 变量,测试myCoin[0] 是否等于Heads 总是正确的——你想做什么?
  • myCoin 是一个数组...您正在尝试查看您已经定义为具有正面和反面的数组的那个数组是否等于正面?
  • 你不能比较字符串和字符串数组。字符串包含在字符串数组中。

标签: java android if-statement random textview


【解决方案1】:

问题一)

= 是一个任务,你想要.equals

问题 b)

myCoin 是一个数组

如果你这样做了

myCoin[0].equals ("Heads") 

它永远是真的

【讨论】:

    【解决方案2】:

    试试 最适合我 if(Arrays.asList(myCoin).contains("Heads"))

    【讨论】:

      【解决方案3】:

      myCoin 是一个数组,所以它不能等于字符串。

      你应该使用

      if myCoin[random].equals("Heads") {
          // do something
      }
      

      【讨论】:

        【解决方案4】:

        如果你想比较两个对象,你必须使用“==”。

        == 相当于“等于”,= 相当于“设置等于”

        //This checks if A is equal to one
        if (A == 1){  
             //This sets A equal to one
             A = 1;
        }
        

        另外,您在放置时尝试检查整个数组

          if (myCoin == "Heads") {
          }
        

        您应该检查数组中的字符串,方法是向其中传递一个数字,然后检查字符串是否相等。值得注意的是,在比较字符串时,您要使用 .equals() 方法。下面的代码将检查数组“myCoin”中的第一项是否等同于“Heads”。

         if (myCoin[0].equals("Heads")){
         }
        

        ==和.equals()方法here的区别有很深入的解释。

        【讨论】:

          【解决方案5】:
          final String[] myCoin= {"Heads", "Tails"};
          
          if (myCoin = "Heads") {
              ImageView img = (ImageView) findViewById(R.id.imageView);
              img.setImageResource(R.mipmap.heads);
           }
          
          //----------------------------------------------------------
          

          你的变量是数组。因此你的代码看起来像这样......ff:

          final String[] myCoin= {"Heads", "Tails"};
          
          int randomNumber = Math.random(10)%2;
          
          if (myCoin[randomNumber].equals("Heads")){ //when you are in string condition symbol must .equals instead '=' .
             ImageView img = (ImageView) findViewById(R.id.imageView);
             img.setImageResource(R.mipmap.heads);
           }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-10-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-01-21
            • 1970-01-01
            相关资源
            最近更新 更多