有人可以告诉我在Android Studio中这段代码有什么问题吗?

huangapple go评论71阅读模式
英文:

Can anyone tell me what is the problem with this piece of code in Android Studio?

问题

我想检查字符串的长度是否大于3,并且是否有两个以上的空格。
我使用了一个for循环来计算有多少个空格(代码如下)。
然后使用了'if'语句。
当我添加'&&'时,当字符数少于3个时,应用程序崩溃。
如果我移除'&&'部分,虽然我需要它,但它可以正常工作! :/
这是我使用的逻辑有问题吗?

for循环:

for (int i = 0; i < 4; i++) {
    if (message.charAt(i) == ' ') {
        count++;
    }
}

然后是'if'部分:

if (message.length() < 3 && count > 2) {
    outputText.setText("呃!别费心琢磨这个了!");
    Toast.makeText(getApplicationContext(), "警告!!", Toast.LENGTH_SHORT).show();
} else {
    methodEncrypt(message);
}
英文:

I want to check if the length of the string is >3 and if there are more than two spaces.
I implemented a for loop to count how many spaces are there(code below).
Then used the 'if'.
When I add &&, the app crashes when there are less than 3 characters.
It works when I remove the && part but, I need it! :/
Is it a problem with the logic I have used? :/

for loop:

for(int i=0; i&lt;4; i++){
        if(message.charAt(i) == &#39; &#39;){
              count++;
        }
}

then the if part:

if(message.length()&lt;3 &amp;&amp; count&gt;2){
     outputText.setText(&quot;Duh! DO NOT TRY TO FIGURE THIS OUT!&quot;);
     Toast.makeText(getApplicationContext(),&quot;WARNING!!&quot;,Toast.LENGTH_SHORT).show();
}
else
     methodEncrypt(message);

答案1

得分: 2

NomadMaker是正确的。循环可能失败的一个原因是假设'message'的长度大于4。如果message ='123',那么尝试获取'charAt'索引4将会失败,因为请求的索引大于字符串的大小。

更新为:

for (int i = 0; i < message.length(); i++) 
{
    if (message.charAt(i) == ' ') 
    {
        count++;
    }
}

应该解决这个问题。还可以考虑一些轻微的性能改进。例如:
1)如果字符串的长度小于4,则不必遍历整个字符串。
2)一旦找到第二个空格,就不必遍历字符串的其余部分。

英文:

NomadMaker is correct. One reason the loop may be failing is the assumption that the length of 'message' is greater than 4. If message = '123', then attempting to get the 'charAt' index 4 will fail due to the requested index being greater than the size of the String.

Updating to:

for(int i=0; i &lt; message.length(); i++)
{
        if(message.charAt(i) == &#39; &#39;)
        {
              count++;
        }
}

Should resolve this issue. Some minor performance improvements may also be considered. Ex:

  1. If the length of the String is less than 4, don't bother iterating through the String.
  2. Once the second space is found, don't bother iterating through the rest of the String.

huangapple
  • 本文由 发表于 2020年9月18日 00:07:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63942017.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定