-2

The objective: Create a program that responds to the "sysout" of the first RNG produced results.

The last two lines are the problematic lines.

The code thus far:

    import java.util.Random;

public class Tutorials {

public static void main(String[] args) {
String[] test = new String [3];
test[0]= "go";
test[1] = "stop";
test [2] = "slow";
System.out.println(test [new Random ().nextInt(test.length)]);
if (test="stop") { System.out.println("wait 3 seconds");}   
}

}
Miguel.P
  • 9
  • 2
  • What is the problem? – dwilliss Nov 06 '17 at 20:39
  • "Exception in thread "main" java.lang.Error: Unresolved compilation problems: Type mismatch: cannot convert from String[] to boolean Type mismatch: cannot convert from String to String[] at Tutorials.main(Tutorials.java:11) " – Miguel.P Nov 06 '17 at 20:40
  • 1
    ```if (test="stop")``` is not testing for anything. – Eddie Martinez Nov 06 '17 at 20:40
  • `if (test="stop")` assigns a String to a String array and you expect it to return a boolean. – luk2302 Nov 06 '17 at 20:41
  • How would I work around that? If I wish to use the results for the next step? – Miguel.P Nov 06 '17 at 20:43
  • test is an array, so test = "stop" won't work for 2 reasons. 1) = is an assignment. You want == to compare. 2) test is an array, so you need an array index like test[1] == "stop" – dwilliss Nov 06 '17 at 20:43

1 Answers1

1

You are trying to assign a String to String array in this line if (test="stop"). To perform the check it needs to be == not =. But when doing String comparision try to use .equals() instead of the == operator, more info about == vs .equals()

Solution

public class Tutorials {

   public static void main(String[] args) {
       String[] test = {"go", "stop", "slow"};
       String result = test [new Random().nextInt(test.length)];
       System.out.println(result);

       if (result.equals("stop")) { 
         System.out.println("wait 3 seconds");
       }   
    }
  }
Eddie Martinez
  • 13,582
  • 13
  • 81
  • 106
  • @Miguel.P No probem! If you feel this answer solved your question please accept. Also you can initialize array in one line like the example provided. – Eddie Martinez Nov 06 '17 at 20:53