我是java语言的初学者,我使用“文本垫”。我的简单程序有问题。我的任务是输入2个值并完全显示“总和”,“差异”,“产品”和“商”。 (简单吧?)其中,下面是应该做算术工作的类。在我编译的时候“正确”。
public class mathclass
{
int x;
int y;
int total;
void add ()
{
total = x+y;
}
void sub ()
{
total = x-y;
}
void multi ()
{
total = x*y;
}
void div ()
{
total = x/y;
}
}
这是主程序,它应该是程序的输入和输出。 我的问题在于我无法将2个变量(num1和num2)传递给“mathclass” 我研究了如何将2个变量传递给另一个类。但是我的一切都没有。我确实使用了一些像变量上的“私人或公共”。 我的老师说要使用BufferedReader进行输入。而且我很难如何使这个程序正确。 (对不起,如果我错了英语(如果我错了。)
import java.io.*;
public class mathmain
{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[]args)throws IOException
{
mathclass math1 = new mathclass();
System.out.print("Enter 1st Number :");
num1 = Integer.parseInt(br.readLine());
System.out.println(" ");
System.out.print("Enter 2nd Number :");
num2 = Integer.parseInt(br.readLine());
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
math1.add();
{
System.out.print("Sum : ");
System.out.println(math1.total);
}
System.out.println(" ");
math1.sub();
{
System.out.print("Difference : ");
System.out.println(math1.total);
}
System.out.println(" ");
math1.multi();
{
System.out.print("Product : ");
System.out.println(math1.total);
}
System.out.println(" ");
math1.div();
{
System.out.print("Quotient : ");
System.out.println(math1.total);
}
}
}
答案 0 :(得分:0)
目前还不清楚你在这里要做什么。 (例如,add
为什么不采用两个参数?)
也许你的事情是这样的:
// Set up arguments
math1.x = num1;
math1.y = num2;
// Perform the add.
math1.add();
// { <-- brace completely useless.
// Print the result
System.out.print("Sum : ");
System.out.println(math1.total);
// } <-- brace completely useless.
但是,我建议您使用返回值和使用参数:
class MathClass {
public int add(int a, int b) {
return a + b;
}
...
}
然后使用像
这样的类int sum = math1.add(num1, num2);
System.out.println("Sum: " + sum);
答案 1 :(得分:0)
你应该看看如何用Java编写代码,因为你的方法是错误的。
要么创建一个构造函数来初始化x&amp;或者你把它们放在方法add(x,y)中,这将导致你使方法静态并删除x&amp;的引用来自班级。对于应该返回函数的总数也是如此。
答案 2 :(得分:0)
试试这个,
对mathmain类使用两个参数构造函数...
public mathmain(int x, int y){
this.x = x;
this.y = y;
}
请使用大写字母作为类名的拳头字母(例如:MathMain),
是的,使用Camel Case在java中编写Class,Variables,Method等名称。
答案 3 :(得分:0)
自从你开始以来,我不会指出设计缺陷。您的问题来自于您使用读取值的方式。您将值读入num1和num2,但您从未在mathclass对象中设置它们:
math1.x = num1;
math1.y = num2;
根据aioobe的说法,你应该看看java设计规则,以帮助你创建健壮,有用的类。我还鼓励您封装您的课程,并尽可能使用参数和返回值。
祝学习java好运,我希望这有帮助!