I am looking for some code to read the last TWO letters AND the first TWO letters on a single word and see if they match. The words will always be in upper case. this is the code i have so far and i am quite bummed why this will NOT work! sorry for being a n00b :)
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
String s;
char[] a;
int input=scan.nextInt();
scan.nextLine();
for(int i=0; i<input; i++){
a = scan.nextLine().toCharArray();
if((a[0] == a[a.length -1]) && (a[1] == a[a.length])){
System.out.println("MATCH");
}else{
System.out.println("DO NOT MATCH");
}
}
}
}
first thing i do is a FOR statement for how many times it runs if you were wondering..
Try replacing this:
if((a[0] == a[a.length -1]) && (a[1] == a[a.length])){
with this:
if((a[0] == a[a.length - 2]) && (a[1] == a[a.length - 1])){
Arrays are 0-based in Java, so the last element is actually .length - 1. (An array of length 3 will have valid indices of [0, 1, 2] - not [1, 2, 3].)
Edit:
However, since Brian has since upped the ante: I would propose one better, which doesn't require converting the String to a character array - or require creating any new Strings through the use of substring.
String str = scan.nextLine();
if((str.charAt(0) == str.charAt(str.length() - 2)) && (str.charAt(1) == str.charAt(str.length() - 1))){
Also, what happens if your String is less than 2 characters? (You may want to check for this...)
You're almost there - the bit you're missing is that array's are indexed from zero so the last element in the array is a[a.length-1] and the penultimate one is a[a.length-2]
Converting to a char array is actually kinda silly.
String line = scan.nextLine();
if (line.substring(0,2).equals(line.substring(line.length() - 2)))
{
// it matched ...
}
Edit: You'll note that I'm using both forms of substring() above. The first one takes a start and end index, while the second takes only the start index and extends to the end of the source String. Take special note that the two argument version's second argument is the index after the substring you want.
There are boolean methods for string called startsWith- and endsWith, respectively, for the class string.
http://docs.oracle.com/javase/8/docs/api/
Related
Look for patterns like "zip" and "zap" in the string -- length-3, starting with 'z' and ending with 'p'. Return a string where for all such words, the middle letter is gone, so "zipXzap" yields "zpXzp"
Here is a solution i got from someone:
public class Rough {
public static void main(String [] args){
StringBuffer mat = new StringBuffer("matziplzdpaztp");
for(int i = 0; i < mat.length() - 2; ++i){
if (mat.charAt(i) == 'z' & mat.charAt(i + 2) == 'p'){
mat.deleteCharAt(i + 1);
}
}
System.out.println(mat);
}
}
But why is it that the for loop condition (i < mat.length() -2) is not (i < mat.length())????
Because in the loop:
if (mat.charAt(i) == 'z' & mat.charAt(i + 2) == 'p'){
// -----------------------------------^^^^^
If i were bound by i < mat.length(), then i + 2 would be out of bounds.
Because you don't have to reach the end of your sentence since your words are at least three letters long.
"2" stands for "the length except the first word",you just need to check all the positions in the string variable , and treat the positions as the first word of the substring , so just ignore the "length of the substring without the first word".
in your case , the length of "z*p" is 3, you just check all the position in the string , and treat the position as z to check something ,so just ignore "*p" ,which has length 2.
mat.length() will give length 14 and if you check for mat.charAt(i + 2) at the end it will give java.lang.StringIndexOutOfBoundsException because the string counts from index 0 not from 1. If you still want to use mat.length() you have to replace the AND '&' operator with short circuit AND '&&' operator in if condition.
I want to check equality of first and last two characters of a string so i have written condition like
if (str.length() >= 4
&& ((str.startsWith(str.substring(0, 2))).equals(str.endsWith(str
.substring(str.length() - 3, str.length() - 1)))))
but I am getting error as
Cannot invoke equals(boolean) on the primitive type boolean
so what is the root cause?
Error is coming because : str.startsWith() returns boolean value and we are calling equals() with Boolean
Use this expression to compare :
str.substring(0, 2).equals(str.substring(str.length() - 3, str.length() - 1))
I want to check equality of first and last two characters of a string
That's not what you're doing though. You're using startsWith and endsWith - you're asking whether a string starts with its own first two characters, and whether it ends with some portion of the string near the end, and then trying to compare the results of those comparisons... except that you're trying to compare two boolean values with equals instead of ==, which isn't going to work either.
You just want substring and equals here - but your substring is incorrect too, in that you have an off-by-one error for finding the last two characters. I would personally split this up for simplicity:
if (str.length() > 4) {
String start = str.substring(0, 2);
// If you don't specify an end point, it'll be "the rest of the string"
// which is what you want.
String end = str.substring(str.length() - 2);
if (start.equals(end)) {
...
}
}
endsWith api will return you a boolean value and hence compiler is compiling that you are trying to compare String with boolean. Instead you could do something like:
if (str.endsWith(str.substring(0, 2))) {
//ye it does ends with same string as it starts with
}
The method startsWith(String) returns a boolean indicating if the string it is being applied on effectively starts with the string argument. For comparing the first two characters with the last two ones, your boolean condition can be:
if(str.length() >= 4 && str.startsWith(str.substring(str.length - 3, str.length()))
Be careful with the indices in the substring method since the last parameter indicates the place of the first character not to be included in the substring.
Same result but with the endsWith(String) method:
if(str.length() >= 4 && str.endsWith(str.substring(0, 3)))
Or with only sunbstring(int, int) method:
if(str.length() >= 4
&& str.substring(0, 3).equals(str.substring(str.length() - 3, str.length())))
Your problem stems from
((str.startsWith(str.substring(0, 2))).equals(str.endsWith(str
.substring(str.length() - 3, str.length() - 1))))
Which is basically coming down to boolean.equals(...), which can't be done, as boolean is not an Object
You could, instead, make use of String#startsWith and String#endsWith, for example...
if (str.length() >= 4 &&
str.endsWith(str.substring(0, 2)) &&
str.startsWith(str.substring(str.length() - 2))) {
Or maybe even
if (str.length() >= 4 &&
str.substring(0, 2).equals(str.substring(str.length() - 2))) {
I've been dealing with the following recursion question for a while now and haven't been able to figure it out. Basically, you have some sort of a sentence made out of certain words, where all the words are just jammed together, not spaced out. The idea is to find the number of all possible combinations of words that can be used to create the sentence.
For example,
Words: ook, ookook
Sentence: ookookook
Solution: {ook, ook, ook}, {ookook, ook}, {ook, ookook}.
Another example:
Words: ooga, oogam, oogum, mook, ook
Sentence: oogamookoogumook
Solution: {ooga, mook, oogum, ook}, {oogam, ook, oogum, ook}
I've tried a lot of things, finally giving up and trying to do it manually...
public static int WAYS(String word) {
int ways = 1;
for (int i = 0; i < word.length(); i++) {
try{
if(word.substring(i, i - 2).equals("ug")){
if(word.substring(i - 4, i - 2).equals("ug")){
ways++;
}
}
else if(word.substring(i, i - 3).contains("ook")){
System.out.println(word.substring(i-6, i-3));
if(word.substring(i - 6, i - 3).equals("ook")){
ways++;
}
if(word.charAt(i - 4) == 'm'){
if(word.substring(i - 8, i - 4).equals("ooga") || word.substring(i - 8, i - 4).equals("oogu")){
ways++;
}
}
}
else if(word.substring(i, i - 4).contains("mook")){
if(word.substring(i - 8, i - 4).contains("mook")){
ways++;
}
}
if(word.substring(i, i - 2).equals("oog")){
if(word.charAt(i + 2) == 'm'){
if(word.charAt(i + 1) == 'a' || word.charAt(i + 1) == 'u'){
ways++;
}
}
}
} catch(Exception e){
continue;
}
}
return ways;
}
But it hasn't worked. Could somebody please give me an idea or a sample on approaching this problem using recursion?
1) Name your methods properly, "WAYS" is a constant name, not a method name.
2) Provide runnable code, especially in cases where it's so short.
3) Never use Exceptions for control flow.
4) You are using magic values like "uug" and "ook" in your code? Does this look simple and obvious? Does this look maintainable? What is this supposed to look like if you get a lexicon with a million of different words?
Edit: giving the complete listing is somehow boring, so I left a few gaps. Try to fill those, hope that helps.
public class JammedWords {
public static int ways(String sentence, String[] words) {
if (sentence.isEmpty()) {
// The trivial case: the sentence is empty. Return a single number.
} else {
int c = 0;
for (String w: words) {
if (sentence.startsWith(w)) {
// call method recursively, update counter `c`.
}
}
return c;
}
}
public static void main(String[] args) {
System.out.println(ways("ookookook", new String[]{"ook", "ookook"}));
System.out.println(ways("oogamookoogumook", new String[]{"ooga","oogam","oogum","mook","ook"}));
}
}
Hints:
A) Understand the difference between empty set, set containing the empty set, set containing a set containing an empty set etc. Sets that contain empty sets are of course not empty, and their size is not 0.
B) There is a handy method String.substring(n) that drops everything before the 'n'-th character. And there is String.length() to get size of words.
Hope VB.NET code won't mind, just for the grasp.
Private Sub Go()
Dim words As New List(Of String)
words.Add("ooga")
words.Add("oogam")
words.Add("oogum")
words.Add("mook")
words.Add("ook")
Search("oogamookoogumook", words, "", New List(Of String))
End Sub
Private Sub Search(ByVal sentence As String, _
ByVal wordList As List(Of String), _
ByVal actualSentenceBuildingState As String, _
ByVal currentPath As List(Of String))
For Each word As String In wordList
Dim actualSentenceAttemp As String
Dim thisPath As New List(Of String)(currentPath)
thisPath.Add(word)
actualSentenceAttemp = actualSentenceBuildingState + word
If actualSentenceAttemp = sentence Then
Debug.Print("Found: " + String.Join("->", thisPath.ToArray()))
End If
If actualSentenceAttemp.Length < sentence.Length Then 'if we are not too far, we can continue
Search(sentence, wordList, actualSentenceAttemp, thisPath)
End If
Next
End Sub
Printouts:
Sentence: oogamookoogumook
Found: ooga->mook->oogum->ook
Found: oogam->ook->oogum->ook
Sentence: ookookook
Found: ook->ook->ook
Found: ook->ookook
Found: ookook->ook
Think about it as walking in graph (its nothing else than that in fact). You start with nothing (empty string). Now you start to iteratively add words from wordlist into your 'current attemp for sentence'. After adding word to current attemp, you can end only in three possible states: (1) you got the final sentence, (2) current attemp is shorter than target sentence and thus still suitable for adding next words (recursion call), or (3), your current attemp is longer (or the same length but not equal) than target sequence, thus it has no meaning to continue in search with it.
What you have to remember is path -- "how did i get here?" list (back tracking).
I have a basic String variable that contains the letter x a total of three times.
I have attempted to find x within the String using charAt, and then print the char and the next two characters next to it.
I have hit a snag within my code and would appreciate any help.
Here is my code.
public class StringX{
public static void main(String[] args){
String ss = "xarxatxm";
char first = ss.charAt(0);
char last == ss.charAt(3);
if(first == "x"){
String findx = ss.substring(0, 2);
}
if(last == "x"){
String findX = ss.substring(3, 5);
}
System.out.print(findx + findX);
}
}
Also, is there a way to implement the for loop to cycle through the String looking for x also?
I just need some advice to see where my code is going wrong.
You cannot find characters using charAt - it's for getting a character once you know where it is.
Is there a way to implement the for loop to cycle through the String looking for x also?
You need to use indexOf for finding positions of characters. Pass the initial position which is the position of the last x that you found so far to get the subsequent position.
For example, the code below
String s = "xarxatxm";
int pos = -1;
while (true) {
pos = s.indexOf('x', pos+1);
if (pos < 0) break;
System.out.println(pos);
}
prints 0 3 6 for the three positions of 'x' in the string.
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Programming java to determine a symmetrical word
am new here, but I am having hard time figuring out how to write a code to determine an input of word and see if the first is matching with the end of the word. You may input abba and get answer it's evenly symmetric and aba is oddly symmetric.
Please show me how:(
Just two main things.
first I want to know if it's oddly or evenly amount of letter(number of letter divided by 2,if it's ending with 0.5, it's oddly symmetric, if is an integer it's evenly symmetric.
second I want to get (i.e 1=n,2=n-1,3=n-2...) position of the letter in the word to be the main idea of the execution.If there is a last letter in the oddly symmetric word, ignore the last remaining letter.
I appreciate any headstart or idea:) Thanks!
Thanks KDiTraglia, I made the code and compiled and here is what I put. I am not getting any further.
Reported problem:
Exception in thread "main" java.lang.Error: Unresolved compilation problems: reverse cannot be resolved or is not a field reverse cannot be resolved or is not a field Syntax error, insert ") Statement" to complete IfStatement
This is what i got from, KDiTraglia's help
public class WordSymmetric {
public static void main(String[] args) {
String word = "abccdccba";
if ( (word.length() % 2) == 1 ) {
System.out.println("They are oddly symmetric");
//odd
}
else {
System.out.println("They are evenly symmetric");
//even
}
int halfLength = word.length() / 2;
String firstHalf = word.substring(0, halfLength);
String secondHalf = word.substring(halfLength, word.length());
System.out.println(secondHalf.reverse());
if (firstHalf.equals(secondHalf.reverse()) {
System.out.println("They match");
//they match
}
} }
String does not have a reverse method. You could use the apache commons lang library for this purpose:
http://commons.apache.org/lang/api-release/org/apache/commons/lang3/StringUtils.html#reverse%28java.lang.String%29
The reverse() approach is very clean and readable. Unfortunately there is no reverse() method for Strings. So you would either have to take an external library (StringUtils from the appache common lang3 library has a reverse method) or code it yourself.
public static String reverse(String inputString) {
StringBuilder reverseString = new StringBuilder();
for(int i = inputString.length(); i > 0; --i) {
char result = inputString.charAt(i-1);
reverseString.append(result);
}
return reverseString.toString();
}
(This only works for characters that can fit into a char. So if you need something more general, you would have to expand it.)
Then you can just have a method like this:
enum ePalindromResult { NO_PALINDROM, PALINDROM_ODD, PALINDROM_EVEN };
public static ePalindromResult checkForPalindrom(String inputStr) {
// this uses the org.apache.commons.lang3.StringUtils class:
if (inputStr.equals(StringUtils.reverse(inputStr)) {
if (inputStr.length % 2 == 0) return PALINDROM_EVEN;
else return PALINDROM_ODD;
} else return NO_PALINDROM;
}
System.out.println(secondHalf.reverse());
There is no reverse() method defined fro String
I would probably loop over word from index 0 to the half (word.length() / 2) and compare the character at the current index (word.charAt(i)) with the correspoding from the other half (word.charAt(word.length() - i).
This is just a rough draft, you probably need to think about the loop end index, depending on oddly or evenly symmetry.
You can adapt this :
final char[] word = "abccdccba".toCharArray(); // work also with "abccccba"
final int t = word.length;
boolean ok = true;
for (int i = t / 2; i > 0; i--) {
if (word[i - 1] != word[t - i]) {
ok = false;
break;
}
System.out.println(word[i - 1] + "\t" + word[word.length - i]);
}
System.out.println(ok);
Console :
c c
c c
b b
a a
true
Use class StringBuffer instead of String