我正在處理這個程序並不斷得到這個結果。Fraction.java保持獲取對象地址不是我想要的值
要轉換小數措施, 進入小數措施要轉換:3/4
輸入小數量減少/增加由它:1/2
轉換後的測量:分數@ 6750cf54
零件是粗體是問題。
這是我的主要程序。
import java.util.*; // Scanner
import java.io.*; // PrintStream
public class Pierre1 extends Object
{
public static void main(String args[])
{
PrintStream theScreen = new PrintStream(System.out);
Scanner theKeyboard = new Scanner(System.in);
theScreen.println("\nTo convert fractional measures,");
theScreen.print(" enter the fractional measure you want to convert: ");
Fraction oldMeasure = new Fraction();
oldMeasure.read(theKeyboard);
theScreen.print("\nEnter the fractional amount to reduce/increase it by: ");
Fraction scaleFactor = new Fraction(1,6);
scaleFactor.read(theKeyboard);
Fraction newMeasure = oldMeasure.times(scaleFactor);
theScreen.print("\nThe converted measurement is: ");
theScreen.print(newMeasure);
theScreen.println();
theScreen.println();
}
}
這是我的其他程序。
import java.util.*; // Scanner
import java.io.*; // PrintStream
public class Fraction extends Object
{
private int myNumerator = 0;
private int myDenominator = 0;
public void print(PrintStream out)
{
System.out.print(myNumerator + "/" + myDenominator);
}
public Fraction()
{
myNumerator = 0;
myDenominator = 1;
}
public Fraction(int numerator, int denominator)
{
myNumerator = numerator;
myDenominator = denominator;
}
private int numerator()
{
return myNumerator;
}
private int denominator()
{
return myDenominator;
}
public void read (Scanner in)
{
String fraction = in.next();
StringTokenizer parser = new StringTokenizer(fraction, "/", false);
if (parser.countTokens() != 2)
throw new RuntimeException("Bad Fraction Format");
myNumerator = Integer.parseInt(parser.nextToken());
myDenominator = Integer.parseInt(parser.nextToken());
}
Fraction times(Fraction rightOperand)
{
Fraction result
= new Fraction(myNumerator*rightOperand.numerator(),
myDenominator*rightOperand.denominator());
result.simplify(result);
return result;
}
public Fraction simplify(Fraction getGcd)
{
Fraction result = new Fraction();
int num = numerator();
int den = denominator();
int gcd = greatestCommonDivisor(num, den);
if (gcd == 0)
return result;
else
{
myNumerator = myNumerator/gcd;
myDenominator = myDenominator/gcd;
}
return result;
}
private static int greatestCommonDivisor(int alpha, int beta)
{
alpha = Math.abs(alpha); // take absolute values of operands
beta = Math.abs(beta);
if (beta == 0) // base case
return alpha;
else // induction step
{
int remainder = alpha % beta;
return greatestCommonDivisor(beta, remainder);
}
}
}
我需要做些什麼來解決這個問題? 我一直在掃描程序來查找問題,但是我有限的Java體驗正在讓我獲得最好的體驗。任何幫助是極大的讚賞。提前致謝!
爲什麼你認爲它應該打印什麼嗎? Java對你的自定義類有什麼瞭解? –
關鍵是'toString()'。給你的類一個體面的toString覆蓋方法,它返回一個代表你的類的狀態的String。 –
它是對象的hashCode而不是它的地址,順便說一句。 – Woot4Moo