-4

I was wondering if I could compare the String Array value to a String, for eg; I have a String array which has 5 values on it. String [] sampleArray = {"a","b","a","b","a"} and I want to know which index value has a or b. I thought of an idea but it didn't work.

String[] sampleArray = {"a","b","a","b","a"};
String value;
for (int i=0; i <= sampleArray.length; i++){
  if ( sampleArray[i].equals("a") ) {
    value = "apple";
  } else {
    value = "ball";
  }
  System.out.println(value);
}

Basically if the index 0 is a then it should print "Apple" and if it's b it should print "ball" and so on. Is there any idea to compare values or string array to a string?

7
  • 1
    Possible duplicate of Java Compare Two List's object values? Commented Sep 18, 2018 at 14:28
  • "I have a String array which has 5 values on it. String [] sampleArray = {"a","b","a","b","a"} and I want to know if my first index value is whether a or b." if (sampleArray[0].equals("a"))` does that. What's the loop for? Commented Sep 18, 2018 at 14:29
  • It didn't work -> maybe you mean the "java.lang.ArrayIndexOutOfBoundsException: 5"? Commented Sep 18, 2018 at 14:30
  • @T.J.Crowder sorry, that was my mistake in questioning part. I wanted to know which index has which value and know whether or not that "if statement" is valid. I edited the question. Commented Sep 18, 2018 at 14:33
  • 3
    @सृजनसृजन Your code is already doing the job. All you need to fix is the conditional statement in the for cycle definition: i < sampleArray.length; Commented Sep 18, 2018 at 14:39

1 Answer 1

2

If I get your question, you are trying to see if sampleArray[0] is equal to "a".

Your code does compare the first index of your array but does not keep the result of your comparaison.

The reason is that your variable value change each loop. In the end, I suppose you are getting this in the console :

apple

But this value of your value variable is the result of the comparaison of the last index, sampleArray[4] and "a". In your code, the value of value is erase at each loop by the next comparaison, at the end you only get the value of the last one.

If you want to get a result like

apple
ball
apple
ball
apple

You need to print the result at each loop just like this :

for (int i=0; i < sampleArray.length; i++){
     if ( sampleArray[i].equals("a") ) {
        System.out.println("apple");
     } else {
        System.out.println("ball");
     }
}

Be careful here, sampleArray.length is equal to five, but index in most programming languages are going from 0 to length-1. So i <= sampleArray.length will probably throw a ArrayIndexOutOfBoundsException

I hope it answers your question.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.