Reputation: 1
We were given instructions to write that accepts a string as input and computes and prints the longest substring displayed two times without overlap (see 5th example for overlap). If there are more from one of such sub-strings, the program displays the first one it finds as well the number of characters in the substring. If there is no substring that appears 2 times, then the program will not print anything. Examples that we were given on how the output should look like:
1st Example
Give a string: again and again
Longest substring: again
Longest substring size: 5
2nd Example
Give a string: seven saints and seven dinners
Longest substring: seven
Longest substring size: 6
Note: The answer completes the space and is 6 characters.
3rd Example
Give a string: Seven saints and seven sinners
Longest substring: even s
Longest substring size: 6
4th Example Give a string: Mary had a little lamb Longest substring: l Longest substring size: 2
5th Example Give a string: racecaracecar Longest substring: raceca Longest substring size: 6
My code up to now is the following, and doesn't work, in that the output screen is just empty, and when I tried to print the Array List, it just listed [null]. What is wrong with it and how can it be made to work?
import java.util.Arrays;
import java.util.ArrayList;
public class substring {
public static void main(String[] args) {
String string = args[0];
ArrayList<String> longestSubstring=new ArrayList<String>();
String substring;
for (int firstcharacter=0; firstcharacter<string.length()-1; firstcharacter++) {
for(int secondcharacter=firstcharacter+1; secondcharacter<string.length()-1; secondcharacter++) {
substring=string.substring(firstcharacter,secondcharacter);
for (int i=substring.length()+1; i<string.length()-1; i++) {
String firsttwo=String.valueOf(string.charAt(i)+string.charAt(i+1));
if (substring==firsttwo) {
longestSubstring.add(substring);
}
}
}
}
for(int i = 0; i < longestSubstring.size(); i++) {
System.out.print(longestSubstring.get(i));
}
}
}
Upvotes: 0
Views: 555
Reputation: 1147
for (int i=secondcharacter+1; i<string.length()-1; i++) {
String firsttwo=String.valueOf(string.charAt(i)+string.charAt(i+1));
System.out.println("2 chars: "+firsttwo+", matching: "+substring);
if (substring.equals(firsttwo)) {
System.out.println(substring);
longestSubstring.add(substring);
}
}
try using print statements to debug your code. When i tried the following it gave me this output:
2 chars: 200, matching: ra
2 chars: 200, matching: ra
2 chars: 196, matching: ra
2 chars: 211, matching: ra
2 chars: 146, matching: ra
2 chars: 129, matching: ra
2 chars: 207, matching: ra
2 chars: 210, matching: ra
2 chars: 132, matching: ra
2 chars: 146, matching: ra
2 chars: 211, matching: ra
2 chars: 196, matching: ra
2 chars: 200, matching: ra
2 chars: 200, matching: ra
this means that you are matching ascii characters (your firsttwo) against a substring
Upvotes: 1