0

I am new to Java and trying to learn by practicing. I am not sure where I am going wrong in my if statement, it seems that after I type r (I believe scanner is storing this in value) the first part of the if statement does not initialize and instead the else statement initializes.

import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class T2 {
public static void main(String args[]){
    Scanner input = new Scanner(System.in);
    T2_2 T2_2Object = new T2_2();

    System.out.println("What is your favorite color? (Enter 0 if unsure) ");
    String value = input.nextLine();

    if (value == "r"){
        int value2;

        value2 = ThreadLocalRandom.current().nextInt(1,10);

        String value3 = Integer.toString(value2);
        System.out.println(value3);

2 Answers2

0

Use:

if (value.equals("r"))

The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.

fluffy
  • 223
  • 1
  • 14
0

In java, you must compare strings using .equals()

if (value.equals("r"))
Easton Bornemeier
  • 1,918
  • 8
  • 22