0

Used scanner for user input struggling to get in to if loop when providing value for suncondition

@SuppressWarnings("resource")
Scanner temp = new Scanner(System.in);
int temperature;
System.out.print("Enter the temperature : ");
temperature=temp.nextInt();
@SuppressWarnings("resource")
Scanner suncon= new Scanner(System.in);
String suncondition;
System.out.print("Enter the Sun condition : ");
suncondition=suncon.nextLine();

if ((temperature==50) || (suncondition=="Sunny")){
    System.out.println(" This is tooo hot");
}

2 Answers2

0

Use .equals() to compare Strings. Only use == to compare primitives - comparing classes is usually comparing references.

@SuppressWarnings("resource")
Scanner temp = new Scanner(System.in);
int temperature;
System.out.print("Enter the temperature : ");
temperature=temp.nextInt();
@SuppressWarnings("resource")
String suncondition;
System.out.print("Enter the Sun condition : ");
suncondition=temp.nextLine();

if ((temperature==50) || (suncondition.equals("Sunny"))){
    System.out.println(" This is tooo hot");
}

Also, there is no need to create two Scanner objects when one could do.

Spectric
  • 5,761
  • 2
  • 6
  • 27
0

== will compare if they refer to the same object in memory which is not the case here so it will be false.

Here you can use the equals method, this compares based on the data / content of the string.

@SuppressWarnings("resource")
Scanner temp = new Scanner(System.in);
int temperature;
System.out.print("Enter the temperature : ");
temperature=temp.nextInt();
@SuppressWarnings("resource")
Scanner suncon= new Scanner(System.in);
String suncondition;
System.out.print("Enter the Sun condition : ");
suncondition=suncon.nextLine();

if ((temperature==50) || (suncondition.equals("Sunny"))){
    System.out.println(" This is tooo hot");
}

If you would like to learn more about this here is a nice article

Aalexander
  • 4,834
  • 3
  • 7
  • 30