2015-11-07 128 views
0

我正在嘗試在Java中添加,乘除分數。我得到的輸出是:FRACTIONS @ 3d4eac69。有任何想法嗎?在Java中添加,減去,乘除法和除法分數

public class FRACTIONS { 
private int numer, denom; 
    public FRACTIONS(){ 
    numer=1; 
    denom=1; 
} 
public FRACTIONS (int n, int d){ 
    numer=n; 
    denom=d; 
} 
public int getNumerator(){ 
    return numer; 
} 
public int getDenominator(){ 
    return denom; 
} 
public FRACTIONS add(FRACTIONS other){ 
    int n = numer * other.denom + other.numer * denom; 
    int d = denom * other.denom; 
    return new FRACTIONS (n, d); 
} 

public FRACTIONS sub(FRACTIONS other){ 
int n = numer * other.denom + other.numer * denom; 
int d = denom * other.denom; 
return new FRACTIONS (n, d); 
} 

public FRACTIONS mult(FRACTIONS other){ 
int n = numer * other.numer; 
int d = denom * other.denom; 
return new FRACTIONS (n, d); 
} 

public FRACTIONS div(FRACTIONS other){ 
int n = numer * other.denom; 
int d = denom * other.numer; 
return new FRACTIONS (n, d); 
} 

public String toString(){ 
String str; 
str= n + "/" + d; 
return str; 
} 

} 

測試人員計劃:

import java.util.Scanner; 
public class FRACTIONS_TESTER { 

public FRACTIONS_TESTER() { 
} 

public static void main(String[] args) { 
    Scanner reader = new Scanner (System.in); 
    Scanner scan = new Scanner (System.in); 
    FRACTIONS numer, denom; 
    numer= new FRACTIONS(); 
    denom = new FRACTIONS(); 
    System.out.print ("Enter the numerator for fraction 1: "); 
    int n1 = reader.nextInt(); 
    System.out.print ("Enter the denominator for fraction 1: "); 
    int d1 = reader.nextInt(); 
    System.out.print ("Enter the numerator for fraction 2: "); 
    int n2 = reader.nextInt(); 
    System.out.print ("Enter the denominator for fraction 2: "); 
    int d2 = reader.nextInt(); 
int n = 5; 
int d = 6; 
    FRACTIONS f1=new FRACTIONS (n1, d1); 
    FRACTIONS f2=new FRACTIONS (n2, d2); 
    FRACTIONS f3=new FRACTIONS (n,d); 


    int opt; 
    System.out.println ("Select the corresponding number for the desired 
operation: "); 
    System.out.println (" 1. Addition \n 2. Subtraction \n 3. 
Multiply \n 4. Divison"); 
    opt=scan.nextInt(); 
    if (opt==1){ 
     f3=f1.add (f2); 

    } 
    if (opt==2){ 
     f3=f1.sub (f2); 

    } 
    if (opt==3) { 
     f3=f1.mult (f2); 

    } 
    if (opt==4){ 
     f3=f1.div (f2); 

    } 
    } 
System.out.println (f3); 
} 

在此先感謝。我只想輸出爲字符串,以「/」形式返回

+0

你是否在添加toString方法後重新編譯你的FRACTIONS類? – Kenney

+0

您需要下面答案中的toString方法,但我在評論說您應該遵循Java命名約定和CamelCase類名稱,而不是ALL_CAPS –

+0

此代碼不能編譯。請不要讓人們檢查與您實際使用的代碼不同的代碼。 –

回答

0

ndtoString的範圍內未定義。也許你的意思是

@Override 
public String toString() { 
    return numer + "/" + denom; 
} 
+0

謝謝。我添加了這個,並且仍然將FRACTIONS @ 3d4eac69作爲我的輸出,而不是分子/分母形式的分數的解決方案。 –