calculator bug java | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
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 Resposta
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