我是java的新手,需要帮助。我的while循环不起作用。它不会执行除count之外的任何操作。
对于这个问题,我需要制作具有mutator和辅助方法的分数类。然后我必须使分子和分母成为最低形式,所以我使用while循环通过使用模块找到最大公约数。任何其他评论家也表示赞赏。
public class Fraction {
private int numerator;
private int denominator;
public Fraction(){
}
public Fraction(int num, int den){
this.numerator = num;
this.denominator = den;
}
public void setNumerator(int numerator){
this.numerator = numerator;
}
public void setDenominator(int denominator){
this.denominator = denominator;
}
public double divided(){
double divide = (double)this.numerator/this.denominator;
return divide;
}
public String printFraction(){
int numerator = greatestCommmonNumetaror();
return "";
}
private int greatestCommmonNumetaror(){
int count = 1;
int first;
int mod;
while(count != this.numerator){// need help with this
mod = this.numerator%count;
if(mod != 0){
first = count;
if(first < count){
first = count;
}
}
count++;
}
return 1;
}
}
答案 0 :(得分:1)
如果你调用它,while循环很好。 刚刚添加了几个System.out.println,你可以看到它正在执行:
private int greatestCommmonNumetaror(){
int count = 1;
int first;
int mod;
System.out.println("Outside while: count is "+count+" and this.numerator is "+this.numerator);
while(count != this.numerator){// need help with this
System.out.println("In while: Count is "+count);
mod = this.numerator%count;
System.out.println("In while: mod is "+mod);
if(mod != 0){
first = count;
System.out.println("In while and if: first is "+first+" and count is "+count);
if(first < count){
first = count;
System.out.println("In while and if and if: first is "+first+" and count is "+count);
}
}
count++;
}
return 1;
}
public String printFraction(){
int numerator = greatestCommmonNumetaror();
return "";
}
还添加了下面提到的代码来调用printFraction:
public static void main(String[] args){
Fraction fraction = new Fraction(3,5);
fraction.printFraction();
}
你可以看到输出:
Outside while: count is 1 and this.numerator is 3
In while: Count is 1
In while: mod is 0
In while: Count is 2
In while: mod is 1
In while and if: first is 2 and count is 2
所以它确实适用于while循环。
*编辑:虽然使用System.out.println,但您应该能够看到算法的问题,但如果您还有其他问题,请与示例一起解释您的算法。
答案 1 :(得分:-2)
只需使用分子摆脱循环中的this.numerator