java - 如何将变量的值从主类传递到另一个类?
问题描述
大家好,我目前正在创建一个简单的程序。我有 2 个类,第一个是计算器,第二个是 parameters_return。我想要发生的是,当我在第二堂课中读取 x 和 y 的值时,我想在第一堂课中使用它们 不幸的是,我无法运行该程序,因为它有错误。下面的代码请帮助我解决这个问题。我只是自学我真的很想学习Java。
(一等)计算器类中的代码是:
class calculator {
//with parameters with return type
int add(int a, int b) {
return (a + b);
}
//with parameters without return type
void sub(int a, int b) {
System.out.print(a - b);
}
//without parameters with return type
int mul() {
parameters_return s1 = new parameters_return();
int c = (s1.x) * (s1.y);
return c;
}
//without parameters without return type
void div() {
parameters_return s2 = new parameters_return();
int c = (s2.x) / (s2.y);
System.out.println("Division = " + c);
}
}
我的(二等)parameters_return 类中的代码是:
class parameters_return {
int x, y;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
x = sc.nextInt();
y = sc.nextInt();
calculator perform = new calculator();
//addition
int z = perform.add(x, y);
System.out.println("Added value = " + z);
//subtraction
System.out.println("Subtracted value = ");
perform.sub(x, y);
//multiplication
z = perform.mul();
System.out.println("Multiplication value = ");
//division
perform.div();
}
}
有没有办法从主类中获取值并可以在另一个类中使用?
解决方案
import java.util.*;
class ParametersReturn {
static int x, y;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
x = sc.nextInt();
y = sc.nextInt();
Calculator perform = new Calculator();
//addition
int z = perform.add(x, y);
System.out.println("Added value = " + z);
//subtraction
System.out.println("Subtracted value = ");
perform.sub(x, y);
//multiplication
z = perform.mul();
System.out.println("Multiplication value = " + z);
//division
perform.div();
}
}
这应该是您的 ParametersReturn 类,并确保您应该以大写字母开头您的类名,您正在使用 Scanner 类来使用它,您必须导入 java.util 包。并在 Calculator 类中使用这些变量使这些变量静态
class Calculator {
//with parameters with return type
int add(int a, int b) {
return (a + b);
}
//with parameters without return type
void sub(int a, int b) {
System.out.print(a - b);
}
//without parameters with return type
int mul() {
ParametersReturn s1 = new ParametersReturn();
int c = (s1.x) * (s1.y);
return c;
}
//without parameters without return type
void div() {
ParametersReturn s2 = new ParametersReturn();
int c = (s2.x) / (s2.y);
System.out.println("Division = " + c);
}
}
在乘法中你忘记打印 z 的值
推荐阅读
- matlab - 在 MATLAB 中更改通过 FIT 函数生成的表面网格
- c - C程序启动定义不清楚
- kotlin - 无法解析 TLS 数据包头 android studio
- allennlp - 在每个 epoch 后保存模型 - AllenNLP
- sql - BigQuery 子查询返回上个月的分组字段
- python - SyntaxError: 文件中的非 ASCII 字符 '\xe2' 但未声明编码
- webpack - 在 image-minimizer-webpack-plugin (mozjpeg, pngquant) 中使用有损模块时出错
- reactjs - 当我使用表单发送输入时,我无法更改状态
- angular - 使用 httpclient 时查看变量未从错误处理程序代码更新
- python - cv2.findContours() 和 cv2.drawContours() 未显示预期结果