1

I have been trying to compare a string to another, or a string to a statement, but I can't find where the mistake is. I tried with the == but it didnt work, then i changed to .equals()

static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
  System.out.print("En este programa calcularemos el area de una figura.\n" + 
              "Ingresa a continuacion que figura calcularemos.");
    String triangulo = "triangulo";
    String figura = scan.nextLine();
    if (figura.equals(triangulo)){
        System.out.print("Ingrese base y altura del triangulo.\n");
        double base = scan.nextDouble();
        double altura = scan.nextDouble();
        System.out.print("La altura es " + (base*altura)/2);
    }
}

The idea here is to ask the user the name of the shape whose area will be calculated, and if it equals one of the different shapes I'm going to name, then it will use formula depending on the shape.

mkobit
  • 34,772
  • 9
  • 135
  • 134
ValenRW
  • 13
  • 3

3 Answers3

2

When I tried this program and entered triangulo as input it seems to work for me as it printed Ingrese base y altura del triangulo..Then enter the value for sides and it works. I think code is correct.

akhil_mittal
  • 18,855
  • 7
  • 83
  • 82
0

You have to differentiate between compering the references and values. Using "==" means you are comparing references not values. The link here will describes what are the java methods to compares variables in general and in which cases you have to use them.

http://www.leepoint.net/data/expressions/22compareobjects.html

I hope this will answer your question.

Riad
  • 668
  • 1
  • 10
  • 33
0

Replace this line: String figura = scan.nextLine();with String figura = scan.next();and your program will work: see image below

triangle

Also see here the difference between Scanner.next() and Scanner.nextLine()

Community
  • 1
  • 1
alainlompo
  • 4,130
  • 3
  • 27
  • 39