英文:
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<4; i++){
if(message.charAt(i) == ' '){
count++;
}
}
then the if part:
if(message.length()<3 && count>2){
outputText.setText("Duh! DO NOT TRY TO FIGURE THIS OUT!");
Toast.makeText(getApplicationContext(),"WARNING!!",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 < message.length(); i++)
{
if(message.charAt(i) == ' ')
{
count++;
}
}
Should resolve this issue. Some minor performance improvements may also be considered. Ex:
- If the length of the String is less than 4, don't bother iterating through the String.
- Once the second space is found, don't bother iterating through the rest of the String.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论