英文:
Exchange values between classes/Methods
问题
public class MainM {
public static void main(String[] args) {
Loop Q = new Loop();
Q.doOperation();
}
}
//------------------------------------------------------
public class Loop {
public double b;
Sum R = new Sum(); // Java 出现问题的地方:在 Sum.<init>(Sum.java:3)
public void doOperation() {
for (int i = 0; i < 10; i++) {
b = b + 2;
if (b <= 10) {
R.operationFor1();
}
}
}
}
//--------------------------------------------------
public class Sum {
Loop Q = new Loop();
public void operationFor1() {
System.out.println("b " + Q.b);
}
}
请注意,我只对代码进行了翻译,不包括代码中的问题或错误。如果您需要进一步的帮助,可以详细描述问题,我将尽力回答。
英文:
i recently learned the use of public, private and double in my different classes. But for some reason i cant understand why this is not working. My intention was to use three different classes as an exercise: I want Do() to make numbers from 0 to 20 and show only the numbers 0 till 10 on my console using the method for1() in a different class. Can someone please fix this issue? I dont need a shorter code or a code in just 1 class since i need it to educate myself using many classes. I would thank anyone if you could fix this issue using this kind of setup. Thanks in advance.
public class MainM {
public static void main(String[] args) {
loop Q = new loop();
Q.Do();
}
}
//------------------------------------------------------
public class loop {
public double b;
Sum R = new Sum(); // Java shows the problem is here : at Sum.<init>(Sum.java:3)
public void Do() {
for (int i = 0; i < 10; i++) {
b = b + 2;
if (b <= 10) {
R.for1();
}
}
}
}
//--------------------------------------------------
public class Sum {
loop Q = new loop();
public void for1() {
System.out.println("b " + Q.b);
}
}
</details>
# 答案1
**得分**: 0
你可以只保留 `print` 语句的 `Sum` 类,并且 `for1()` 方法应该有一个参数。以下是我的建议:
```java
public class Sum {
public void for1(double b) {
System.out.println("b " + b);
}
}
而你的循环类将会是:
public class Loop {
public double b;
Sum R = new Sum();
public void Do() {
for (int i = 0; i < 10; i++) {
b = b + 2;
if (b <= 10) {
R.for1(b);
}
}
}
}
英文:
You can have your Sum class only with the print statement and the method for1() should have one parameter. Bellow is my suggestion
public class Sum {
public void for1(double b) {
System.out.println("b " + b);
}
}
And your loop class will be
public class loop {
public double b;
Sum R = new Sum();
public void Do() {
for (int i = 0; i < 10; i++) {
b = b + 2;
if (b <= 10) {
R.for1(b);
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论