Ternary Calculation

Ternary Calculation

Time Limit : 4000/2000ms (Java/Other)   Memory Limit : 131072/65536K (Java/Other)
Total Submission(s) : 16   Accepted Submission(s) : 5
Problem Description
Complete the ternary calculation.
Input
There are multiple test cases. The first line of input contains an integer T indicating the number of test cases. For each test case:
There is a string in the form of "number1 operatora number2 operatorb number3". Each operator will be one of {'+', '-' , '*', '/', '%'}, and each number will be an integer in [1, 1000].
Output
For each test case, output the answer.
Sample Input
5
1 + 2 * 3
1 - 8 / 3
1 + 2 - 3
7 * 8 / 5
5 - 8 % 3
Sample Output
7
-1
0
11
3
Note
The calculation "A % B" means taking the remainder of A divided by B, and "A / B" means taking the quotient.
 
package ACM1;


import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Scanner;



public class nyojw2
{
  public static void main(String[]args)
  {
       Scanner scanner = new Scanner(System.in);
       int n = scanner.nextInt();
       for(int i=0;i<n;i++)
       {
           int sum=0;
           int sum1 =0;
           int a = scanner.nextInt();
           String b=scanner.next();
            
//           str=scanner.next();
           int c =scanner.nextInt();
           String d = scanner.next();
           int e = scanner.nextInt();
           if((b.equals("/"))||(b.equals("*"))||(b.equals("%")))
           {
//               sum1 = cal(a,b,c);
               sum = cal(cal(a,b,c),d,e);
           }
           else if((d.equals("/"))||(d.equals("*"))||(d.equals("%")))
           {  
//               sum1 = cal(c,d,e);
               sum = cal(a,b,cal(c,d,e));
           }
           else
               {
//                sum1 = cal(a,b,c); 
                sum=cal(cal(a,b,c),d,e);
               }
//           System.out.println(sum1);
           System.out.println(sum);
           
           
           
       }
      
  }
  public static int cal(int x,String y,int z)
  {  // String y11 = new String();
       if(y.equals("/"))
           return (x/z);
       else if(y.equals("%"))
           return (x%z);
       else if(y.equals("*"))
           return (x*z);
       else if(y.equals("+"))
           return (x+z);
       else 
           return (x-z);
        
       
      
  }
}

注意:在java里面要知道==和equals的区别:

需注意几点:

  1、string是一个特殊的引用类型。对于两个字符串的比较,不管是 == 和 Equals 这两者比较的都是字符串是否相同;

  2、当你创建两个string对象时,内存中的地址是不相同的,你可以赋相同的值。

    所以字符串的内容相同。引用地址不一定相同,(相同内容的对象地址不一定相同),但反过来却是肯定的;

  3、基本数据类型比较(string 除外) == 和 Equals 两者都是比较值;

原文地址:https://www.cnblogs.com/mmlovejj/p/4447355.html