I have this problem:
I wrote this function because I need to get the index of the occurrence of a particular string st in a String array
static public int indicestring(String[] array, String st) {
int ret = -1;
for (int i = 0; i < array.length; i++){
if (st.equals(array[i])) {
ret=i;
break;
}
}
return ret;
}
I then called:
System.out.println("indicestring(NODO,"ET2"));
and I got the correct number.
But then when I do:
String[] arcos2 = linea.split("-");//reading from a file and separating by "-"
String aux = arcos2[1];
System.out.println(arcos2[1]);
System.out.println(aux);
if (aux.equals(arcos2[1])) {
System.out.println("Is equal 1");
}
if (aux.equals("ET2")) {
System.out.println("Is equal 2");
}
if ("ET2".equals(aux)) {
System.out.println("is equal 3");
}
The first two prints were ET2, but then it only printed of the 3 ifs is "Is equal 1".... The thing is I have nearly 200 nodes like "ET2" and only 3 are failing and giving me -1 in the first function...
My question is....Am I using wrong the arrays to save and compare the data, because if aux=arcos2[1]="ET2", why is 'aux.equals("ET2") 'or 'arcos2[1].equals("ET2)' not working
? Is ther another function you can recommend to try?(I tried changing equals with compareTo() == 0 and that didn't work either and trimming was also recommended).
Before, I had a similar error where I compare two arrays like this:
if(a[0] == b[0] && a[1] == b[1])
There was a case that clearly was correct but it was ignored...
But it got corrected when a i changed it to:
if (Arrays.equals(a, b))
Is there maybe some change like that
You should put a debug break point in the code and add expression watches to identify the root cause of the problem.
Related
This question already has answers here:
How Do I Print the values in a recursive Program in Java?
(5 answers)
Closed 2 years ago.
java write recursive function that accept int : k and print to screen k of "*"
Attempt:
public static String numStarec(int k) {
String ans = "";
if (k == 0) {
ans += "*";
return ans;
}
return numStarec(k-1);
}
this code not work and print for me only "*" ones I know the problem
I tried to fix that but , unfortunately without successes
Example :
k = 3
console : ***
You can append an asterisk after each recursive call, with the base case returning an empty string when k is 0.
public static String numStarec(int k) {
if(k == 0) return "";
return numStarec(k-1) + "*";
}
Demo
Before writing the solution to the problem, I think it would be valuable for you to understand the definition of recursion and what is it that you want to happen. First things first, "recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem" (Source).
If the previous definition still confuses you a bit then lets take a look at the solution to your problem:
public static String numStarec(int k) {
if (k == 0) {
return "";
}
return numStarec(k-1) + "*";
}
As the definition says, "method of solving a problem..." (In this specific case the problem you have is that you want to print the character * an amount K of times on screen) "...where the solution depends on solutions to smaller instances of the same problem" (Where these smaller instances of the same problem consist on finding out how many characters '*' are left to be printed, which is what the value of K is for)
What is happening when you provide the function numStarec with a certain number K is that it will take K and check whether it is 0 or not. If K == 0 evaluates to true then the return statement will be "" but while K != 0 evaluates to true, what will happen is that the function will return the character "*" and keep on invoking itself with the value of K-1 and once again return accordingly.
Hope it helps you understand a little bit about recursion.
just doing an assignment and to sum it up:
I need to get a users ID which is an int and make sure the first number is 4.
I have tried to do this by converting the id (int from the object in the main method) into the char array.
I print out the index[0] to console and it says 4, great right?
But i have made an if statement that then says if index[0]of the array is 4 then do something... it doesn't seem to acknowledge index 0 is 4 and proceeds to do whats in the else block.
public boolean checkID()
{
int convert = getId(); //get id is 44444
char[] idArray = String.valueOf(convert).toCharArray();
System.out.println(idArray[0]); // this returns a value of 4 in the console
boolean check = false;
if(idArray[0] == 4)
{
check = true;
System.out.println("Id starts with 4!");
}
else
{
check = false;
throw new IllegalArgumentException("Id does not start with 4");
}
return check;
}
}
Of course in the console i receive the illegal argument exception but also 4 printed out?
Sorry if this is a silly problem i have been looking at it for so long and its abit blurry now haha!
Possibly there is a better way?
Thanks in advance!
You are trying to compare an int with a char.
You have converted your int to an array of char, so the right way to see whether the first element in your array is equal 4 or not, you need to make it a char and put it inside single quotes like this:
if(idArray[0] == '4')
{
check = true;
System.out.println("Id starts with 4!");
}
Thanks!
So recently I got invited to this google foo.bar challenge and I believe the code runs the way it should be. To be precise what I need to find is the number of occurrences of "abc" in a String. When I verify my code with them, I pass 3/10 test cases. I'm starting to feel bad because I don't know what I am doing wrong. I have written the code which I will share with you guys. Also the string needs to be less than 200 characters. When I run this from their website, I pass 3 tests and fail 7. Basically 7 things need to be right.
The actual question:
Write a function called answer(s) that, given a non-empty string less
than 200 characters in length describing the sequence of M&Ms. returns the maximum number of equal parts that can be cut from the cake without leaving any leftovers.
Example : Input : (string) s = "abccbaabccba"
output : (int) 2
Input: (string) s = "abcabcabcabc"
output : (int) 4
public static int answer(String s) {
int counter = 0;
int index;
String findWord ="ABC";
if(s!=null && s.length()<200){
s = s.toUpperCase();
while (s.contains(findWord))
{
index = s.indexOf(findWord);
s = s.substring(index + findWord.length(), s.length());
counter++;
}
}
return counter;
}
I see a couple of things in your code snippet:
1.
if(s.length()<200){
Why are you checking for the length to be lesser than 200? Is that a requirement? If not, you can skip checking the length.
2.
String findWord ="abc";
...
s.contains(findWord)
Can the test program be checking for upper case alphabets? Example: "ABC"? If so, you might need to consider changing your logic for the s.contains() line.
Update:
You should also consider putting a null check for the input string. This will ensure that the test cases will not fail for null inputs.
The logic of your code is well but on the other hand i found that you didn't check for if input string is empty or null.
I belief that google foo.bar wants to see the logic and the way of coding in a proper manner.
so don't be feel bad
I would go for a simpler approach
int beforeLen = s.length ();
String after = s.replace (findWord, "");
int afterLen = after.length ();
return (beforeLen - afterLen) / findWord.length ();
String pattern = "abc";
String line="<input text here>";
int i=0;
Pattern TokenPattern=Pattern.compile(pattern);
if(line!=null){
Matcher m=TokenPattern.matcher(line);
while(m.find()){
i++;
}}
System.out.println("No of occurences : "+ " "+i);
put declaration of index out before while block, isn't never good re-declare the same variable n time.
int index;
while (s.contains(findWord))
{
index = s.indexOf(findWord);
....
}
I hope this help
Update:
try to compact your code
public static int answer(String s) {
int counter = 0;
int index;
String findWord = "ABC";
if (s != null && s.length() < 200) {
s = s.toUpperCase();
while ((index = s.indexOf(findWord)) > -1) {
s = s.substring(index + findWord.length(), s.length());
counter++;
}
}
return counter;
}
Update:
The logic seems good to me, I'm still try to improve the performance, if you can try this
while ((index = s.indexOf(findWord, index)) > -1) {
//s = s.substring(index + findWord.length(), s.length());
index+=findWord.length();
counter++;
}
SO i made a CharSequence[] array with all the two consecutive uppercase letters. Why is this code not returning the correct values?
public static boolean containConsecCaps(String passw)
{
CharSequence[] consec = {"AA","AB","AC","AD","AE","AF", ... "ZZ"};
boolean contain = false;
String pass = passw;
for (int i = 0; i <= 675; i++)
{
contain = pass.contains(consec[i]);
if (contain == true)
break;
}
return contain;
}
and in the main string, this syntax:
while (consec != false)
{
//Consec.setPassword(password.getPassword());
consec = Consec.containConsecCaps(password.getPassword());
if (consec == false)
break;
else
password.setPassword(reader.readLine("Error. Please enter a password with no consecutive letters: "));
}
now everything else in the three classes work. This is the only problem and it seems to get stuck in the else. Why is it not testing all of the array char's then returning true or not?
It gets stuck in a loop if i enter: AApassword.1 , which fits all the other criteria, except the two consecutive capitals. So then i enter: aApassword.1 , which should fit ALL of the criteria, but it still prints out the else statement, instead of breaking the while loop.
Can anyone help me?
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