2016-11-08 76 views
2

我必须作出一个程序,它从具有n列的二维阵列和2行的前输入的:以馏分=(1 2 3 4) (5 6 7 8)数组运算符

它也有(例如:Operators = [+ * - ])

代码必须根据1d数组中的运算符对数组中的分数进行加,减,乘,除 - 例如:1/5 + 2/6 * 3/7 -4/8

我得到我的代码来正确输入两个数组,但我很难找出如何让它做数学。我已经读过这个答案,它包含了最小公倍数和最大公倍数,所以我也做了一个单独的程序,但不知道如何将程序结合在一起。有没有人看到过这样的问题,并可以提供一些建议? 预先感谢您。

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


     //1D ARRAY OF OPERATORS 
     System.out.println("How many operators are you going to enter?"); 
     int length = s.nextInt(); 
     String operators[]=new String[length]; 

     System.out.println("Enter operators(+, -, *)"); 

     for (int counter=0; counter<length; counter++){ 
      operators[counter]=s.next(); 

      System.out.print(operators[counter]); 
      //1D ARRAY OF OPERATORS END 
     } 


     //INPUT OF ROWS AND COLUMNS 

     System.out.print("Enter number of rows in matrix:"); 

     int rows = s.nextInt(); 

     System.out.print("Enter number of columns in matrix:"); 

     int n = s.nextInt(); 

     int fractions[][] = new int[rows][n]; 

     System.out.println("Enter all the elements of matrix:"); 

     for (int i = 0; i < rows; i++) { 
      for (int j = 0; j < n; j++) { 
       fractions[i][j] = s.nextInt(); 
      } 
     } 
     for (int i = 0; i < rows; i++) { 
      for (int j = 0; j < n;j++){ 



       System.out.print (fractions[i][j]); 

      } 
      System.out.println(""); 

      //END OF INPUT OF ROWS AND COLUMNS 


     } 
    } 


} 
//LCM code and GCM code 

import java.util.Scanner; 
public class LCM_GCD_METHOD { 

    public static void printFace() { 
     int a; 
     int b; 
     int LCM; 
     int temp; 
     int GCD; 


     Scanner sc= new Scanner(System.in); 
     int x=sc.nextInt(); 
     int y=sc.nextInt(); 

     a=x; 
     b=y; 


     while(b!=0){ 
      temp = b; 
      b = a % b; 
      a = temp; 
     } 
     GCD = a; 
     LCM = (x*y)/GCD; 

     System.out.println("GCD = " + GCD); 
     System.out.println("LCM = " + LCM); 
    } 
    public static void main (String [] args) { 
     printFace(); 
     return; 
    } 
} 
+0

它总是2行吗? – JordanGS

+0

我正在研究它,但这对于atm来说工作太多了,如果您创建一个名为'Fraction'的新类,那么最简单。看到这里[信息](http://stackoverflow.com/questions/8453485/addition-subtraction-multiplication-division-with-fractions-in-java-homewo) – JordanGS

回答

1

您的数组数组是整数数组,但您的运算符数组是一个字符数组。我认为最直接的方式是

for(int i = 0 ; i < operators.length ; i++){ 
if(operators[i] == '+'){ 
//do addition 
}else if(operators[i] == '-'){ 
//do subtraction 
//and more conditions for the remaining operators 
} 
}