【问题标题】:please explain how to implement main method in my code?请解释如何在我的代码中实现主要方法?
【发布时间】:2018-08-14 15:38:39
【问题描述】:

请解释如何实现 main 方法。我在使用 main 方法和 main 方法之后的行时遇到问题,为什么 main 方法之后的行显示非法的表达式开始?是因为我忘了把括号放在某处还是我的代码错误??该代码假设使用分数执行算术。

公共类理性{

public static void main(String [] args){
    public int numerator;
    public int denominator;

public Rational(int numerator, int denominator)

{
    this.numerator = numerator;
    this.denominator = denominator;
    reduce();
}

public Rational add(Rational other)
{
    int num = numerator * other.denominator + other.numerator * denominator;
    int den = denominator * other.denominator;
    return new Rational(num, den);
}

public Rational subtract(Rational other)
{
    int num = numerator * other.denominator - other.numerator * denominator;
    int den = denominator * other.denominator;
    return new Rational(num, den);
}

public Rational multiply(Rational other)
{
    int num = numerator * other.numerator;
    int den = denominator * other.denominator;
    return new Rational(num, den);
}

public Rational divide(Rational other)
{
    int num = numerator * other.denominator;
    int den = denominator * other.numerator;
    return new Rational(num, den);
}

private void reduce()
{
    int min = 0;
    if(numerator > denominator)
    {
        min = denominator;
    }
    else
    {
        min = numerator;
    }

    for(int i = min; i > 1; i--)
    {
        boolean isNumDiv = numerator % i == 0;
        boolean isDenDiv = denominator % i == 0;

        if(isNumDiv && isDenDiv)
        {
            numerator = numerator / i;
            denominator = denominator / i;
            break;
        }
    }
}

public String toString()
{
    return numerator + " / " + denominator;
}

} }

【问题讨论】:

  • 请为您使用的编程语言添加标签。
  • 这里显示的缺乏努力是惊人的
  • 请说清楚点。你的代码应该做什么?在这个 sn-p 中,您的主要方法似乎是空的,并且您似乎在其中声明了全局字段。尝试详细说明您的问题,以便我们为您提供帮助。
  • 对不起,我认为我不应该把整个代码放得太大,我会解决我的问题,不过感谢您的评论:)

标签: java methods


【解决方案1】:

假设您必须创建一个打印总和的程序。您可以创建一个包含 Sum 类的文件 Sum.java。像这样:

public class Sum {
    public int x;
    public int y;

    public Sum(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int sumMyNumbers() {
        return x + y;
    }

}

现在您可以使用 Main 类创建一个名为 Main.java 的文件,该文件将作为程序的入口点,它可能是这样的:

public class Main {
    public static void main(String[] args) {
        // It will print the number 4 on your console
        System.out.println(new Sum(2, 2).sumMyNumbers());

        // Or like this:
        Sum mySum = new Sum(2,2);
        System.out.println(mySum.sumMyNumbers());

        // Or even like this:
        int i = new Sum(2, 2).sumMyNumbers();
        System.out.println(i);
    }
}

所以你的第一个错误是你把所有东西都放在了你的 main 方法中。

【讨论】:

    猜你喜欢
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    相关资源
    最近更新 更多