Question and answer with if and else in Java

5

No matter what I answer, both "Yes" and "yes" only show ELSE . Where am I going wrong?

package saudacao;
import java.util.*;
public class Saudacao {
    public static void main(String[] args) {
        System.out.println("Ola, bom dia, voce esta bem hoje?");
        Scanner sdc_recebe = new Scanner(System.in);
        String sdc_armazena = sdc_recebe.nextLine();
        if (sdc_armazena == "Sim") {
            System.out.println("Que bom!!!");
        } else {
            System.out.println("Que pena!!!");
        }
    }
}
    
asked by anonymous 25.05.2014 / 02:11

2 answers

6

Use the function String.html#equals , the operator == is used to compare references.

See the difference:

String a = new String("foo");
String b = new String("foo");

System.out.println(a == b);      // False
System.out.println(a.equals(b)); // True 

Your code looks like this:

import java.util.*;

class Saudacao 
{
    public static void main(String[] args) 
    {
        System.out.println("Ola, bom dia, voce esta bem hoje?");

        Scanner sdc_recebe = new Scanner(System.in);
        String sdc_armazena = sdc_recebe.nextLine();

        if (sdc_armazena.equals("Sim")) 
        {
           System.out.println("Que bom!!!");
        } 
        else 
        {
           System.out.println("Que pena!!!");
        }
    }
}

See DEMO

To compare without differentiating between upper and lower case letters, use the String.html#equalsIgnoreCase ":

if (sdc_armazena.equalsIgnoreCase("Sim")) // Sim, sIM, SIM, sim...
{
   System.out.println("Que bom!!!");
} 
else 
{
   System.out.println("Que pena!!!");
} 

To compare integers, String.html#equals can also be used:

Integer I = 10;

if (I.equals(10))
{
   System.out.println("Igual!");
}
else
{
   System.out.println("Valores diferentes!");
}
    
25.05.2014 / 02:21
4

It could look like this:

System.out.println("Ola, bom dia, voce esta bem hoje?");
Scanner sdc_recebe = new Scanner(System.in);
String sdc_armazena = sdc_recebe.nextLine();
if ("sim".equals(sdc_armazena.toLowerCase()) ||
    "aham".equals(sdc_armazena.toLowerCase())) {
     System.out.println("Que bom!!!");
} else {
     System.out.println("Que pena!!!");
}

If you do not write anything, it does not give you an error, it only goes straight to else .

    
25.05.2014 / 02:27