I have an array array1[] that has 3 values. example: dog cat chicken String[] array1 = {"dog", "cat", "chicken"};
What I need to do use a if statement in this situation? Example: if (array1 == "dog" ) { println("is a dog"); } OR if (array1.equals("dog")) { println("is a dog"); } Can any of these, too be possible, How, I try both cases show above but they don't work. Thanks.
SJCP 1.4<br /> <br />"Go in there and do the best you can. That's all you can do."<br />Tiger Woods<br /> <br />"Practice is the best of all instructors."<br />Publilius Syrus (b. 42 AD)
You're comparing the array object to a String; they're definitely not equal. You want to compare one element, or all the elements, to the String. To compare one particular element, you'd use if (array1[1].equals("dog")) To compare them all, you could use a for loop, or the following trick: if (Arrays.asList(array1).contains("dog")) using the "asList()" static method in the java.util.Arrays class.
import java.util.*; public class TestingArrays { public TestingArrays() { } public static void main(String[] args) { TestingArrays tt = new TestingArrays(); String[] parentid = {"1", "1", "1", "dog", "cat"}; String str = new String("1"); // Fixed-size list List list = Arrays.asList(parentid); // Growable list list = new LinkedList(Arrays.asList(parentid)); Vector v = new Vector(); for ( int i=0; i<parentid.length; i++ ) { v.add(parentid[i]); } System.out.println("v : " + v); Enumeration e = v.elements(); while (e.hasMoreElements()) { System.out.println(e.nextElement()); } System.out.println("list.size(): " + list.size()); System.out.println("list.contains(str) " + list.contains(str)); System.out.println(""); System.out.println("array size: " + parentid.length); for ( int i=1; i<= parentid.length; i++) { if (Arrays.asList(parentid).contains("2")) { System.out.println("la la la: " ); } } } }
SJCP 1.4<br /> <br />"Go in there and do the best you can. That's all you can do."<br />Tiger Woods<br /> <br />"Practice is the best of all instructors."<br />Publilius Syrus (b. 42 AD)
IN THE ABOVE SAMPLE PROGRAM I like to prove that I have three "1" and then a "cat" and a "dog" ..... I wanna be able to run a sql query where if the userID="1" I like to perform a different behavior than if ther userID="something else". "1" is a default value in the database table for users. Thanks.
SJCP 1.4<br /> <br />"Go in there and do the best you can. That's all you can do."<br />Tiger Woods<br /> <br />"Practice is the best of all instructors."<br />Publilius Syrus (b. 42 AD)