请解释如何在我的代码中实现main方法?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了请解释如何在我的代码中实现main方法?相关的知识,希望对你有一定的参考价值。
请解释如何实现main方法。我主要方法和主方法后的行有问题,为什么主方法后的行显示非法启动表达式?是因为我忘了把括号放在某处或我的代码错了?代码假设用分数执行算术。
公共类Rational {
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;
}
} }
答案
假设您必须创建一个打印总和的程序。您可以使用其中的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方法?的主要内容,如果未能解决你的问题,请参考以下文章
ASP.net MVC 代码片段问题中的 Jqgrid 实现