i am writing a program for my java class and have to create a calculator, i got the calculator to work for two numbers but can't get it to do more than two numbers and it needs to. any help will be greatly appreciated. If you take out the tnum the calculator will process the two numbers.

import java.util.Scanner;

public class MainClass
{
   public static void main( String args[] )
   {
      Scanner input = new Scanner( System.in );

    
      String operator = "+,-,*,/";
      double fnum = 0;
      double snum = 0;
      double answer = 0;
      double tnum = 0;
    
     
      System.out.print( "Enter first integer: " );
      fnum = input.nextDouble();
      
      System.out.println("enter operator");
      operator = input.next();
      System.out.print( "Enter second integer: " );
      snum = input.nextDouble();
       System.out.println("enter operator");
      operator = input.next();
      System.out.print( "Enter third integer: " );
      snum = input.nextDouble();
      if (operator.equals("+"))
      {
      answer = fnum + snum + tnum;
      System.out.println(fnum + snum + tnum);
      }
      else if (operator.equals("-"))
      {
      answer = fnum - snum - tnum;
      System.out.println(fnum - snum - tnum);
      }
      else if(operator.equals("*"))
      {
       answer = fnum * snum * tnum;
       System.out.println(fnum * snum * tnum);
      }
      else if(operator.equals("/"))
      {
       answer = fnum / snum / tnum;
       System.out.println(fnum / snum / tnum);
      }
       System.out.println(answer);   
     
    
     

    

     

   }
}

you need a loop in order to repeat the operation. Try using a switch/case statement. Also I noticed that when you are printing out your answers, you can just do

System.out.println(answer);

instead of typing out the actual functions each time if you've already defined them.

If you're just doing

number, operation, number, operation, number, etc
for example: 5 + 2 * 3 - 1

then you can just use a loop and some function calls. Integer.parseInt() will be useful here and so will the % operator (to decide if the position is odd -- because positions 1, 3, 5, etc are all numbers whereas the even positions are all operations.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.