java - 我该如何解决预期错误?
问题描述
我正在编写一个函数,该函数将另一个类中构造的对象用作变量。这是代码,我在这里得到错误“commonDenominator(Fraction,Fraction)”,Fraction和Fraction中预期的标识符的两个错误。
public class MyMath {
public static int commonDenominator(Fraction,Fraction){
int d1 = getDenominator();
int d2 = getDenominator();
if (d1%d2==0){
return d1;
} else if (d2%d1=0){
return d2;
} else {
return d1*d2 ;
}
}
}
另一方面,这是分数类的代码:
public class Fraction {
// The fields of this Fraction
private int numerator;
private int denominator;
/** Constructs a fraction.
* The newly constructed fraction is reduced.
* For example, given 6 and 9, constructs the fraction 2/3.
* If the denominator is negative, converts the signs of both the numerator and the denominator.
* For example, 2/-3 becomes -2/3, and -2/-3 becomes 2/3.
* @param numerator can be signed
* @param denominator can be signed
*/
public Fraction (int numerator, int denominator) {
// Handles the signs of the numerator and denominator
if (denominator < 0) {
numerator = numerator * -1;
denominator = denominator * -1;
}
// Initializes the object's fields
this.numerator = numerator;
this.denominator = denominator;
// Divides the numerator and denominator by their greatest common divisor
}
/** Constructs a random fraction.
* The denominator is a random positive random number which is less than limit, and
* the numerator is a random positive random number which is less than the denominator.
* @param limit must be greater or equal to 1
*/
public Fraction(int limit) {
// Put your code here
int denominator1 = (int)(Math.random()*(limit+1));
int numerator1 = (int)(Math.random()*(denominator + 1));
this.numerator = numerator1;
this.denominator = denominator1;
}
/** Returns the numerator of this fraction.
* @return the numerator of this fraction
*/
public int getNumerator() {
return numerator;
}
/** Returns the denominator of this fraction.
* @return the denominator of this fraction
*/
public int getDenominator() {
return denominator;
}
}
解决方案
您需要命名该方法的参数。可推测的,d1
并且d2
应该分别是它们的分母:
public static int commonDenominator(Fraction f1, Fraction f2) {
// Here ----------------------------------^------------^
int d1 = f1.getDenominator(); // Use f1
int d2 = f2.getDenominator(); // Use f2
if (d1%d2==0){
return d1;
} else if (d2%d1=0){
return d2;
} else {
return d1*d2 ;
}
}
推荐阅读
- excel - 在 Excel 中使用 VBA 在与工作表不同的工作表上查找和更新相关记录
- javascript - 如何根据其父组件在屏幕上的位置移动Vuetify组件```VDatePicker```
- sql - 如何修复 SQL 语句中的 H2 语法错误?
- spring-amqp - 无论指定的并发性如何,如果队列非空但未接收消息,RabbitMQ 侦听器只会为每个消费者启动一个线程
- javascript - 选项 modal: true in magnificpopup 不起作用
- arrays - 使用Angular 8中的服务将数据从一个组件传递到另一个组件的问题
- flutter - showDialog 在颤振中调用的方法有错误?
- r - 为什么删除一些列后头部的描述消失了?
- r - R中样本和rnorm函数的相互作用?
- xamarin - 使用 FlirOneSDK 通过 x 和 y 值获取温度