calculator bug java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

calculator bug java

hello guys i am with a bug in my calculator , i was programing in netbeans and .......you will see, this is the code : import java.util.Scanner; public class Calculadora { public static void main(String[] args) { Scanner input = new Scanner (System.in); double op1, op2, resultado ; String operaçao = new String (); String soma = new String (); String subtraçao = new String (); String multiplicaçao = new String (); String divisao = new String (); System.out.println("insira o primeiro numero"); op1 = input.nextDouble(); System.out.println("insira o segundo numero "); op2 = input.nextDouble(); System.out.println("que operaçao deseja fazer"); Scanner r = new Scanner (System.in); operaçao = r.next(); if (operaçao == "soma" ){ resultado = op1 + op2 ; System.out.println(resultado); }else if (operaçao == "subtraçao " ){ resultado = op1 - op2 ; System.out.println(resultado); }else if ( operaçao =="multiplicaçao"){ resultado = op1 * op2 ; System.out.println(resultado); }else if (operaçao == "divisao"){ resultado = op1 / op2 ; System.out.println(resultado); }else { System.out.println("insia uma operaçao valida como : soma , subtraçao , multiplicaçao , divisao"); } } } soo this is the code and what happens is that when i put the operation the output is always "invalid operation pls enter sum......" ; and the system.out.println(); they are is portuguese so go to gooogle tradutor but i think that is prety obvius

30th Jun 2017, 8:31 AM
sargentov
sargentov - avatar
1 Answer
0
Common mistake. Do not compare String using the "==" operator. You have to use equals() as the String is a Class and the text is the instance of the String Class. package com.company; import java.util.Scanner; public class Calculadora { public static void main(String[] args) { Scanner input = new Scanner(System.in); double op1, op2, resultado; String operaçao = new String(); String soma = new String(); String subtraçao = new String(); String multiplicaçao = new String(); String divisao = new String(); System.out.println("insira o primeiro numero"); op1 = input.nextDouble(); System.out.println("insira o segundo numero "); op2 = input.nextDouble(); System.out.println("que operaçao deseja fazer"); Scanner r = new Scanner(System.in); operaçao = r.next(); if (operaçao.equals("soma")) { resultado = op1 + op2; System.out.println(resultado); } else if (operaçao.equals("subtraçao ")) { resultado = op1 - op2; System.out.println(resultado); } else if (operaçao == "multiplicaçao") { resultado = op1 * op2; System.out.println(resultado); } else if (operaçao.equals("divisao")) { resultado = op1 / op2; System.out.println(resultado); } else { System.out.println("insia uma operaçao valida como : soma , subtraçao , multiplicaçao , divisao"); } } }
1st Jul 2017, 6:56 AM
Claudiu Stefan Haidu
Claudiu Stefan Haidu - avatar