我是Java新手,需要帮助。我的while循环无法正常工作。除了计数之外,它不执行任何其他操作。
对于这个问题,我需要使分数类具有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;
}
}
如果调用它,则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可以看到算法问题,但是如果还有其他问题,请举例说明一下算法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句