For with if statement java - java

I need to chek where the char c index is on string , and if the char c is'nt there - return -1.
public class Find {
private String _st;
int i;
public Find(String st) {
_st = st;
}
public int whatIstheIndex(char c) {
for (i=0;i<_st.length();i++)
if (_st.charAt(i) == c) {
return i;
} else {
return -1;
}
return i;
}
}
I'm getting always -1. Why? Is the last return i; unnecessary?

Remove the else clause, it's returning -1 if the first character in the string isn't correct.
You would then also need to change the return statement at the end of the method.

Why don't you just use the built-in indexOf method? That would be a lot easier and quicker than looping through the string and testing each and every character.
But if you have to use this method for some strange reason, get rid of your else clause, because it makes the function return -1 every time the character tested is not matched.

Here is an alternative solution which also works.
public int whatIstheIndex(char c) {
int result = -1;
for (int i = 0; i < _st.length(); i++) {
if (_st.charAt(i) == c) {
result = i;
}
}
return result;
}
It's just a different way of thinking about the problem. I suppose it's slightly "worse" because it adds an extra line of code, but I hope you see how/why this works.

Your code should be like this:
public int whatIstheIndex(char c) {
for (int i = 0; i < _st.length(); i++)
if (_st.charAt(i) == c) {
return i;
}
return -1;
}
Hope this helps!

Why not use String.indexOf(int) method.
public int whatIstheIndex (char c) {
return _st.indexOf(c);
}
Else, return a -1 only after the loop finishes:
public int whatIstheIndex (char c) {
for (i=0;i<_st.length();i++)
if (_st.charAt(i) == c ) {
return i;
}
}
return -1;
}

What's happening is that it's looking at the first character, and if that doesn't match, it immediately returns -1 (and hence, doesn't continue looping through the chars until it finds the right one).
You need to return -1 only if you have finished the for loop and have not found the character. So it needs to be:
public int whatIstheIndex(char c) {
for (i = 0; i < _st.length(); i++) {
if (_st.charAt(i) == c) {
return i;
}
}
return -1;
}

You are always returning after looking at the first character. Your test doesn't look at other characters. A debugger would show you this. The last return i is only called if the length is 0.

Your current implementation will only ever return one of two values, 0, or -1. 0 is returned when the first index is that which the character resides, or -1 if its not found there. Remove the else clause and return -1 after you've finished the for loop to indicate that you've exhaustively searched all indexes, and found no answer.

Related

Question >> print "True" or "False" if the string contains two or more characters

I have to make a method named 'contains' that accepts a string and a character as parameters and returns true if that character occurs two or more times in the string.
example: Input contains("Apple", 'p') should return "True"
private boolean contains(String a,char b) {
if(a.contains(b)) {
print("true");
}
else {
print("");
}
//boolean c = a.contains('l');
return false;
}
I know this code is wrong ... I want to know what I have to do and what I have to fix .
I would appreciate your advice
Thank you.
There are a few ways to do this but the simplest would just be to loop through the String looking for the char, if count reaches two then return true.
For this consider using
for (char c : input) {
if (c == myChar) count++;
if (count >= 2) return true;
}
return false;
Another way would be to use String.replace and replace the wanted char with ""
then compare the size of the before and after String
Your method may return a boolean based on the size difference between the original string, and the string without the given character :
return (a.length() - (a.replace(b, '')).length()) >= 2 ;
In theoretical terms:
First: you need to iterate over the input string characters using a for loop and then in each iteration compare the current character in the string with the other character argument which is given as method argument. If they match, then you can increase a counter (a variable). Then compare if the counter value is 2 and return true immediately it is so. At the method end you can return false just like you have done already.
Second : you are printing true , not returning true. Should use return true; when the value of variable becomes 2
countMatches(a,b) returns the count of b in String a. and it is from org.apache.commons.lang3
private boolean contains(String a,char b) {
return StringUtils.countMatches(a, b)>=2 ;
}
or in simple java you can use
private boolean contains(String a,char b) {
return (a.length() - a.replaceAll(String.valueOf(b),"").length())>=2 ;
}
This is one of simple ways to do this. Here the string is put into char array. This way it is easier to examine the elements of the char array and find out same characters.
private boolean contains(String a, char b) {
char[] c_array = a.toCharArray();
int count = 0;
for (int i = 0; i < c_array.length; i++) {
if (b == c_array[i]) {
count++;
continue;
} else {
continue;
}
}
if (count >= 2) {
return true;
} else {
return false;
}
}
public class Demo {
public static boolean contains(String str,char c){
//todo:check str for NullPointExecption
int flag=0;
for(int i=0;i<str.length();i++){
if(c==str.charAt(i)){
flag++; //if str contains char c,flag=flag+1
}
if(flag>=2){
return true; //if flag>=2,return true
}
}
return false;
}
public static void main(String[] args) {
System.out.println(contains("appple", 'p'));//result is true
}
}

Why does the following method shows error of return type

public static int letterPosition(String word,char a)//returns the position of searched character
{
int lenght=word.length();
for (int i=0; i < lenght; i++)
{
if(word.charAt(i)==a)
{
return i;
}
}
}
You need to handle the possibility that the loop isn't entered (or if it is entered, that the character isn't found). Add something like
return -1;
at the end of the method (to handle when the character isn't present).
Something must be returned, and your return statement is inside the 'if' statement, implying you have to enter the conditional statement to return something. You need to have a return option if the 'if' statement isn't executed.
You can fix this by adding an 'else if' statement after the 'if' statement.
please do something like,
public static int letterPosition(String word,char a)//returns the position of searched character
{
int returnValue = -1;
if(word != null){ //this will save us from NullPointerException...
int lenght=word.length();
for (int i=0; i < lenght; i++)
{
if(word.charAt(i)==a)
{
returnValue = i;
break;
}
} //end of for loop
}//end of if - word != null
return returnValue;
}

Rewriting the whole String Class methods

My professor have given me a challenging homework, where the idea is to rewrite all the methods in the String classes without using String, StringBuilder, and Wrapper classes. This is for Intro to Java class. I already have some methods done but having a hard time with some other ones. This is for the main class only with no creation of any string inside.
What I have: a "data" as a char[] data for my "MyOwnString" object.
CompareTo method:
public int compareTo(MyOwnString rhs){
if (this.data == rhs.data){
return 0;
} else if (this.data > rhs.data){
return 1;
}
else {
return -1;
}
}
This one shows an error. My guess is that the rhs needs to be declare before being able to compare to any string being assigned to a MyOwnString object.
Since there is a compareTo method and a compareToIgnoreCase, then I would have to add a line to ignore the comparsion?
Update:
This is the code I went with for the compareTo method by creating own method using length of the array.
public int compareTo(MyOwnString cts){
int word1 = data.length;
int word2 = cts.length();
int result = 0;
for (int i=0; i<word1; i++){
for (int j=0;j<word2; j++){
if(word1 == word2){
result = 0;
}
else if (word1 > word2){
result = 1;
}
else {
result = -1;
}
}
}
return result;
}
Since you are not allowed to use String.compareTo()
and since java doesn't support > for your custom objects or char[] for that matter (e.g doesn't support operator overloading) you have to do it programmatically.
In other words you have the two char arrays and you have to loop through all the characters. You compare the first two characters from each of the char arrays (there you can use > or <) if they are == you compare the second two characters and so on.. till you find two characters that break the tie - you can then break your for loop and return the result as -1, 1. If they are tied on every character you return 0.
If you want to implement equals you could just call compareTo and optimize it a bit by checking the lengths of the strings. If they are different then of course the strings are not equal
Update: I am not sure if you ran your code above - try to compile your code and run it before you move forward. I believe it won't even compile.
Here is, I believe, a correct unchecked version. I could have mixed the -1 and 1s as always..
public int compareTo(MyOwnString cts){
int word1Length = ((MyOwnString)this).data.length;
int word2Length = cts.data.length;
for (int i=0; i < Math.min(word1Length,word2Length); i++){
if(this.data[i] == cts.data[i]){
continue;
}
else if (this.data[i] > cts.cts[i]){
return -1;
}
else if (this.data[i] < cts.cts[i]) {
return 1;
}
}
if (word1Length == word2Length){
return 0;
}
else if(word1Length < word2Length){
return 1;
}
else {
return -1;
}
}
public boolean equals(MyOwnString cts){
int word1Length = ((MyOwnString)this).data.length;
int word2Length = cts.data.length;
if (word1Length != word2Length){
return false;
}
else { // if they are equal
int comparison = this.compareTo(cts);
if (comparison==0){
return true;
}
else {
return false;
}
}
}
You can't compare char[] objects with the > operator, since it's not defined on them. You'll have to iterate over the char[] arrays and compare the characters yourself.
BTW, it's very easy to cheat in this assignment, since the code of the String class is available online.

PrefixAgain solution in codingbat

I'm currently doing codingbat problems for fun, and I just done this problem.
"Given a string, consider the prefix string made of the first N chars of the string. Does that prefix string appear somewhere else in the string? Assume
that the string is not empty and that N is in the range 1..str.length(). prefixAgain("abXYabc", 1) → true prefixAgain("abXYabc", 2) → true prefixAgain("abXYabc",
3) → false"
http://codingbat.com/prob/p136417
And my solution is:
public boolean prefixAgain(String str, int n) {
return (str.replaceFirst(Character.toString(str.charAt(n-1)),"").contains(Character.toString(str.charAt(n-1))));
}
Now, I didn't really understand the problem while writing this code and I thought only to find the occurance of the character of the specified index and
ignore the characters before it using the .contains() method. So I'm really not finding the prefix as the problem instructed. I just found my mistake after submitting it. However, this solution passed the exercise.
When I test it with my own input, such as
prefixAgain("abcccccbx", 2);
it returned true instead of false. So am I missing some reason why codingbat accepted my solution even though it's totally wrong?
public boolean prefixAgain(String str, int n)
String prefix = str.substring(0, n);
int length = str.length();
for (int i = n; i <= length - n; i++) {
if (prefix.equals(str.substring(i, i + n))) {
return true;
}
}
return false;
}
Restate your strategy (algorithm): Do the first N characters in a string appear anywhere else in the string? Simplest solution would be to look for that string in the 2nd through last characters of the original string. Like below (even if someone gives you an assumption, always check!)
public boolean prefixAgain(String str, int n) {
boolean result = false;
if (n < str.length() &&
(str.substring(1)).indexOf(str.substring(0,n)) > -1
) {
result = true;
}
return result;
}
Maybe i missed something but this seems correct and elegant:
public boolean prefixAgain(String str, int n) {
if(str.substring(n).contains(str.substring(0, n))) return true;
return false;
}
If n > str.length() it returns false.
public boolean prefixAgain(String str, int n) {
int l= str.length();
String test = str.substring(0,n);
boolean flag = false;
str = str.substring(1);
l= str.length();
for(int i=0;i<l;i++){
if((i+n <= l)){
if((str.substring(i,n+i).equals(test)))
return true;
}
}
return flag;
}
This is mine (considering that indexOf() is not introduced yet):
public boolean prefixAgain(String str, int n) {
for (int i=1; i <= str.length()-n; i++)
if (str.substring(i, i+n).equals(str.substring(0, n)))
return true;
return false;
}
But I found this solution the most elegant so far:
public boolean prefixAgain(String str, int n) {
return (str.indexOf(str.substring(0, n), 1) != -1);
}
public boolean prefixAgain(String str, int n) {
return str.substring(n).contains(str.substring(0,n));
}
just looking the prefix(str.substring(0,n)) in the substring of str without the prefix this means starting from n which is (str.substring(n)).
public boolean prefixAgain(String str, int n) {
return (str.substring(n).contains(str.substring(0,n)));
}
This has been posted basically, but I revised it a little to make it super easy to read instead of going for the one liner.
public boolean prefixAgain(String str, int n) {
String prefix = str.substring(0, n);
String afterPrefix = str.substring(n);
return afterPrefix.contains(prefix);
}
First, we grab the prefix which will start at index zero and go up to not including n. afterPrefix is simply the rest of the string which will start at n. Finally, return whether everything after the prefix contains the prefix.
public boolean prefixAgain(String str, int n) {
String pre = str.substring(0, n);
for (int i=n; i<str.length()-n+1; i++)
{
if (str.substring(i, i+n).equals(pre))
return true;
}
return false;
}
A solution, not the fastest but clear.
public boolean prefixAgain(String str, int n) {
String prefix = str.substring(0,n); // prefix String
int index = str.indexOf(prefix); //first loc of prefix
if(str.lastIndexOf(prefix) > index){ //see if it appears again
return true;
}
else return false; //if we get here, doesn't appear again, false
}

Android find array index value of a partial match

I'm looking for a way to find the index position of a partial match in Java (Android).
Let's say my Array is:
String ips[] = {"10.185.98.111", "192.168.0.13", "Some random IPV6 address"};
I'd like to be able to something like ips[].indexOf("192") and this return "1" rather than "-1".
Is this possible?
Do your own function such as:
public int getElementThatContains(String[] ips, String key) {
for (int i = 0; i < ips.length; i++) {
if (ips[i].indexOf(key) >= 0) {
return i;
}
}
return -1;
}
Observe that the ordering of your list will determine which ip you'll get.
If you have two elements with 192 whichever is closer to the beginning will get selected.
Also you may change:
if (ips[i].indexOf(key) >= 0) {
return i;
}
To different kind of matches such as:
ips[i].contains(key)
ips[i].startsWith(key)
ips[i].endsWith(key)
public void specialIndexOF(List<String> ips){
int index=0;
for(String s:ips){
if(s.contains(search)){
return index;
}
index++;
}
return -1;
}

Categories