(for those who are too lazy for the link):
Quote
need logic for the program
I need logic for the following program. please help me
Question :
Accept 2 strings and check how many times the second string is in the first string.
Example1:
Enter main string : This is a dog which is angry. This is a dog which eat much.
Enter string to check: This is a dog
output
2 times the 2nd string is present in the main string.
I need logic for the following program. please help me
Question :
Accept 2 strings and check how many times the second string is in the first string.
Example1:
Enter main string : This is a dog which is angry. This is a dog which eat much.
Enter string to check: This is a dog
output
2 times the 2nd string is present in the main string.
and, being a java noob, I was encouraged to try to write this program to test my skills.
I have come this far and I think I'm pretty close, but I could be wrong.
import java.util.*;
public class Sentence {
public static void main(String[] args){
// This program is supposed to let the user input two strings and check to see how many times
// the second string is in the first.
String main, check;
int i = 0, index = 0;
main = "This is a dog which is angry. This is a dog which eat much.";
check = "This is a dog";
for(int length = 0; length < main.length(); length++){
index = main.indexOf(check, index + 1);
if(index >= 0){
i += 1;
}
}
System.out.println("The check string appears in main " + i + " times.");
}
}
I thought I had coded it right, but obviously I didn't, because the output returns "The check string appears in main 39 times.
"
I'm 99% sure it has something to do with my for loop, can anyone help nudge me in the right direction? thanks :)
p.s. once I'm done with this program and it runs well, I'm going to change the value of the two string variables to scanner variables, that way the user can input whatever they like. I just wanted to test certain strings first.
Edited by Cruel Hand, 09 December 2011 - 05:49 PM.
p.s.


Sign In
Create Account


Back to top









