Java skips my scanner and won’t let me answer!

Asked

Viewed 23 times

0

I am learning Java alone. One of the activities was the following:

"Make a program that works like a calculator between two numbers any choice to calculate the sum, subtraction, division or multiplication between them."

My code is this one:

import java.util.Scanner;
public class teste01{
    public static void main (String[] args){
        Scanner scan= new Scanner (System.in);

        int num1=0, num2=0;
        String operacao="";

        System.out.println("Digite o primeiro número:");
        num1=scan.nextInt();
        System.out.println("Digite o segundo número:");
        num2=scan.nextInt();
        System.out.print("Qual operação deseja realizar?");
        operacao=scan.next();
        
        if (operacao=="soma" ||operacao=="+") {
            System.out.println(num1+num2);
        }else if (operacao=="subtracao" || operacao=="-"){
            System.out.println(num1-num2);
        }else if(operacao=="divisao" || operacao=="/"){
            System.out.println(num1/num2);
        }else if (operacao=="multiplicacao" || operacao=="*"){
            System.out.println(num1*num2);
        }else{
            System.out.println("Esta opção não é válida, tente novamente.");
        }
        


    }
}

However, whenever you arrive at the part of asking which operation you want to perform, I reply sum for example and even then it returns me "This option is not valid, try again.". Can you help me understand what’s wrong? It’s my first question here in the community, I use VS Code, I’ve done similar activities using Scanner and all worked. I’ve spent a couple of hours trying to figure out where my mistake is. Thank you!

  • Use the method equals to make comparisons with string in Java.

1 answer

0


In java if you compare the value of a String variable and a literal value (even if it is a string between quotation marks) with "==" it returns false, so it jumps straight to the last Else, when all others give false. To compare literal value with variable string vc uses "equals(String)". In case your code would be:

        if (operacao.equals("soma") || operacao.equals("+")) {
            System.out.println(num1+num2);
        }else if (operacao.equals("subtracao") || operacao.equals("-")){
            System.out.println(num1-num2);
        }else if(operacao.equals("divisao") || operacao.equals("/")){
            System.out.println(num1/num2);
        }else if (operacao.equals("multiplicacao") || operacao.equals("*")){
            System.out.println(num1*num2);

forehead there

  • Perfect friend, correctly solved the problem, thank you for your attention!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.