Ethan Winter
Ethan Winter

Reputation: 1

JAVA cannot find symbol - variable ans

This is my code and I'm getting an error on the last line stating cannot find "symbol - variable ans"

I am new to java and I am trying to write a simple program that will allow the user input integers and perform operations on those integers

import java.util.Scanner;
/**
 * Write a description of class main here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class main {
  public static void main(String[] args){
      Scanner input = new Scanner(System.in);
      
      double inp1;
      double inp2;
      String opo;
      
      Scanner one = new Scanner(System.in);
      System.out.println("enter first input");
      inp1 = one.nextInt();
      
      Scanner two = new Scanner(System.in);
      System.out.println("enter second input");
      inp2 = two.nextInt();
      
      Scanner three = new Scanner(System.in);
      System.out.println("choose an oporation add/a sub/s mult/m div/d: ");
      
      opo = three.next();

      if (opo == "a"){
          double ans = inp1 + inp2;
      }
      else if (opo == "s"){
          double ans = inp1 - inp2;
      }
      else if (opo == "m"){
          double ans = inp1 * inp2;
      }  
      else if (opo == "d"){
          double ans = inp1 / inp2;
      }
        
      System.out.println("your answer is " + (String)ans);
    }  
}

Upvotes: 0

Views: 66

Answers (2)

Shubham Teke
Shubham Teke

Reputation: 21

Why your defining Scanner object for each variable just define it ones and use that object for every variable. I also go with what Nathan Mills suggests you do change in your code.

You don't face the problem now of that many scanner objects but just think if your solving one problem there are many variables then at that time you will face the problem. Because it will consume your memory

To define the Scanner object at ones.

Upvotes: 0

Nathan Mills
Nathan Mills

Reputation: 2279

Change the if/else chain to this and it should work:

      double ans;
      if (opo == "a"){
          ans = inp1 + inp2;
        }
      else if (opo == "s"){
          ans = inp1 - inp2;
        }
      else if (opo == "m"){
          ans = inp1 * inp2;
        }  
      else if (opo == "d"){
          ans = inp1 / inp2;
        }

Upvotes: 1

Related Questions