Java: Check if next "field" in array exists - java

Ive made this:
if( tal[i+1] ){
if( tal[i] == tal[i+1]){
match=true;
}
}
But it doesnt seem to work.
I want to check whether the field next to the current (i) exists, in the array tal[].
How can i fix this?

If by "exists" you mean "is not out of bounds", then you have to check the length:
if (i+1 < tal.length) {
// i+1 is a valid index in tal here
}

You can check the length of an array with the length field, like:
if (tal.length > i + 1) {
// there is an elemnt at i + 1
}
As you did not mention anything about your comparison line (the line containing ==) I think it is not part of the question.
Although I guess you should put it into a for loop like:
for (int i=0; < tal.length - 1; i++) {
// you can safely do something here involving tal[i] and tal[i + 1]
}

well, all his code does is check if the next element of the boolean array is the same as the current element after first checking if the next element is true.
My guess is he thinks it does something else, but without him telling us what that something is it's rather hard to make recommendations for changes.

Related

Can`t compare ArrayList values in Java

Im doing a Java course and in one exercise I have to create three ArrayLists, ask the user to fill the first two with Integers, and then compare both ArrayLists.
The values that donĀ“t repeat are added to the third ArrayList. I already declared the ArrayLists, used Scanner to allow the user to fill the ArrayLists, and that part works.
The problem comes when I try to compare both ArrayLists. I get all sort of alerts in this line ("the if statement is redundant", "Integer values compared using == or !=","Flip operands of the binary operator", "Invert if").
I suspect that what I wrote after the if statement is not very clean, and that I could get some comments about that (Im not an expert in Java), but I do not understand the alerts that the IDE displays. The code compiles and runs just fine until it hits the nested loops. Please help! Thanks.
//Checking for values that dont repeat
for(int i=0;i<listVector1.size();i++){
for(int j=0;j<listVector2.size();i++){
if(listVector1.get(i)==listVector2.get(j)){//Im getting an alert here
repeats=true; //this boolean was previously declared
} else {
repeats=false;
}
if(repeats==false){
int newValue=listVector1.get(i);
listVector3.add(newValue);
}
}
}
First of all, you have a mistake in the second for loop. I expect you want increment j.
Second is comparing you must explicit cast your values from the array or use function equals.
Third your if statement must be out of your second loop. Because I expect you want to add number in third array only one time as it you find.
for(int i = 0; i < listVector1.size(); i++) {
for(int j = 0; j < listVector2.size(); j++) {
if (listVector1.get(i).equals(listVector2.get(j))) {
repeats = true;
break;
} else {
repeats = false;
}
}
if(!repeats){
int newValue=listVector1.get(i);
listVector3.add(newValue);
}
}
This is the real problem here.
Integer values compared using == or !=
The == operator compares the two object's reference. But what you actually want to do is compare the values stored in the reference.
So, you need to use the equals operator.
Or you could explicitly cast one of the values to int and use == on the values like
if(listVector1.get(i) == ((int)listVector2.get(j))){
repeats=true;
} else {
repeats=false;
}
For more reading, you'd google difference between == and equals operator.

How can test the content beyond a String?

I need to take an input (a tweet), and tell the user how many mentions and hashtags there are, if the input is a valid length (max = 148 characters), and if the message was re-tweeted (by looking for "RT:").
I already worked out the cap-length, and re-tweets, but I can't seem to figure out how counting the hash and mentions would work. This is what I've come up with:
for (int i = 0; i < tweet.length(); i++) {
if ((tweet.charAt(i) == '#') && (tweet.charAt(i+1) != ' ')) {
hash++;
}
}
The problem I face is that if there is a hashtag or mention at the end of the string the variable goes out of bounds and I get an Index range Exception. So I need help finding out how I can get the same effect without the exception while not counting the char at the end.
The mention "function" will work the exact same way as the hash "function".
Try i < tweet.length() - 1 in your for loop.

My 'for loop' inside another 'for loop' is not working

for (int i=0; i<Intlength; i++){
int intPosition;
intPosition=strAlphabet.indexOf(strMessage.charAt(i));
System.out.println(intPosition);
System.out.println("BREAK");
for (int k=0; k<Intlength2; k++){
int intPosition2;
intPosition2=strAlphabet.indexOf(strKeyword.charAt(k));
System.out.println(intPosition2);
System.out.println("BREAK-------------");
}
}
i will ask the user to type in two words. one is a message and one is a keyword.
the first loop above will check that if i
will add 1, and print out the first letters position number. for example if the message was "red". i would first want it to output the position number of "r" which is 17. then it mmust move to the second loop, and do the exact same for the keyword. for example if the keyword was "cat" i would want it to print the first letter position of the first letter in this case "c" has the position value of 2. in this way i want the output to be as such:
first letter position of message
first letter position of keyword
second letter position of message
second letter position of keyword
etc.
therefore sticking to the message "red" and the keyword "cat" i would want the output as such:
17
2
4
0
3
19
i have added in break texts to distinguish what was happening to my coding and this was the result.
Please give me a message:
red
Thank you! Now please give me a keyword:
cat
17
BREAK
2
BREAK-------------
0
BREAK-------------
19
BREAK-------------
4
BREAK
2
BREAK-------------
0
BREAK-------------
19
BREAK-------------
3
BREAK
2
BREAK-------------
0
BREAK-------------
19
BREAK-------------
as you can see it putputs the first letter position of the message, then all three positions of the keyword, and goes onto the second position letter of the message then again outputting all three position values of the keyword.
how do i fix this to get the output i want, i am sure that i am not writing the forloop correctly.
What you've got are nested for loops to make it do what you suggested they just need to be one after the other, not nested inside each other. When you put the second for loop inside the first what you're telling it to do is print each letter in the keyword for every letter in the message.
What you want is a loop like this (It's unclear what you want it to do if one string is longer than the other, I'm assuming you want it to stop with the shorter string but you can change that.)
if(strMessage.length > keyword.length){
intLength = keyword.length;
} else {
intLength = strMessage.length;
}
for (int i=0; i<intLength; i++){
//Print the position of the i'th letter of the message
int intPosition;
intPosition=strAlphabet.indexOf(strMessage.charAt(i));
System.out.println(intPosition);
//Print the position of the i'th letter of the keyword
int intPosition2;
intPosition2=strAlphabet.indexOf(strKeyword.charAt(i));
System.out.println(intPosition2);
}
When you nest loops, the inner one is executed from start to end for each iteration of the outer loop.
You probably need something like that (note that there's only one loop):
for (int i=0; i < Math.max(strMessage.length, keyword.length); i++){
if (i < strMessage.length) {
System.out.println(strAlphabet.indexOf(strMessage.charAt(i)));
} else {
// To be defined
}
if (i < strKeyword.length) {
System.out.println(strAlphabet.indexOf(strKeyword.charAt(i)));
} else {
// To be defined
}
}
(NB: not tested, not compiled)
If you break your requirement, you will get to know that you have straight forward functionality of taking a character at a given index from your both the string.
So you only need single for loop. Inside that you can take character from first string and then from second string.
Note: You need to take care of length of both the strings. Depending on it you can fetch the character from it.
Another Approach without IF else block
for (int i=0; i<Math.max(strMessage.length, keyword.length);i++){
int intPosition;
try{
intPosition=strAlphabet.indexOf(strMessage.charAt(i));
System.out.println(intPosition);
}catch(Exception e){
}
try{
intPosition=strAlphabet.indexOf(strKeyword.charAt(i));
System.out.println(intPosition);
}catch(Exception e){
}
}
String strAlphabet="ABCDEFGHIJKLMNOPQRSTUWXYZ";
String strMessage="red".toUpperCase();
String strKeyword="cat".toUpperCase();
int Intlength=strMessage.length();
int Intlength2=strKeyword.length();
for (int i=0; (i<Intlength) || (i<Intlength2); i++){
int intPosition=strAlphabet.indexOf(strMessage.charAt(i));
System.out.println(intPosition);
int intPosition2=strAlphabet.indexOf(strKeyword.charAt(i));
System.out.println(intPosition2);
}
1) Make the comparison case-insensitive. Don't be sure that user will take care of case while typing words.
2) Ensure the expected behavior in case message length is shorter than keyword or vice versa.

Java: I compare two Strings but it didn't recognize it

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.

Finding index of an array while only knowing half the value

sender.sendMessage("Your referal code is: " + codestring[ArrayUtils.indexOf(namestring, value )]);
the value is equal to "name" plus a random number, how can i make this work without knowing the second part of this string array?
iterate through array and check for startsWith()
for(int index = 0 ; index < array.length ; index ++){
if(array[index].startsWith(key)){return index;}
}
return -1; // not found
I didn't understand what you asked, but if you're trying to find a String, knowing only the first characters, you might use a regular expression to check, like:
for(String string: arrayOfStrings){
if(string.matches("beginningOfString^[1-9]")){
// your code
}
}

Categories