[英]if loop is not working? can anyone help me
public class meaingCompare {
public static void main(String[] args) {
int cnt = 0;
String st1, u, st2;
st2 = "funny";
int n = 5;
System.out.println("Enter the string");
Scanner in=new Scanner(System.in);
st1 = in.nextLine();
String[] v = st1.split("\\s+");
for(int i = 0; i < st1.length(); i++) {
if(v[i].equalsIgnoreCase(st2))
cnt++;
}
if(cnt>=4)
System.out.println(" match found");
}
}
I am just a beginner in java.I want to get the output as match found if the no: of words in the input string match the word funny is greater than 4 but the if loop is not working.我只是 java 的初学者。如果输入字符串中的单词的 no: 匹配单词 fun 大于 4,但 if 循环不起作用,我想将输出作为匹配找到。
Your stop condition in the for loop is wrong: since you're looping on the array of strings v
you should stop when you've reached the last element.您在 for 循环中的停止条件是错误的:因为您在字符串数组
v
上循环,所以您应该在到达最后一个元素时停止。 Modify:调整:
for(int i=0;i<st1.length();i++)
to:到:
for(int i=0;i<v.length;i++)
when traversing due to this st1.length() we get ArrayIndexOutofBoundException so compare with array length instead of strings length.由于这个st1.length()遍历时,我们得到 ArrayIndexOutofBoundException 因此与数组长度而不是字符串长度进行比较。 This works:
这有效:
public static void main(String[] args)
{
int cnt=0;
String st1,u,st2;
st2="funny";
int n=5;
System.out.println("Enter the string");
Scanner in=new Scanner(System.in);
st1=in.nextLine();
String[]v=st1.split("\\s+");
for(int i=0;i<v.length;i++)
{
if(v[i].equalsIgnoreCase(st2))
cnt++;
}
if(cnt>=4)
System.out.println(" match found");
}
}
First of all, there is no such thing as an if
loop.首先,没有
if
循环这样的东西。 You have a for
loop.你有一个
for
循环。
Your problem is that in your for loop, you check if i
is less then the length of the String st1.你的问题是在你的 for 循环中,你检查
i
是否小于字符串 st1 的长度。 However you need to check if I
is less then the length of the array v
.但是,您需要检查
I
是否小于数组v
的长度。 So, change this statement:因此,更改此语句:
for(int i = 0; i < st1.length(); i++)
to this:对此:
for(int i = 0; i < v.length; i++)
Hope this helped.希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.