我在班级ranNumber
中生成一个随机整数Randomiser
,但我想在第二个班级NumberManipulation
中操纵这个号码。
我做了一次尝试,我有/ * * /'d代码。在运行时,NumberManipulation将运行Randomiser - 但这就是全部。
有什么想法吗?
第1课:
import java.util.Random;
public class Randomiser {
public Randomiser() {
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(3);
int ranNumber = 10 + randomInt;
System.out.println(ranNumber);
}
public void main(String[] args) {
new Randomiser();
}
}
第2课:
public class NumberManipulation {
public NumberManipulation(){
new Randomiser();
/*
int a1 = 20;
int building = ranNumber + a1;
System.out.println(building);
*/
}
public static void main(String[] args) {
new NumberManipulation();
}
}
答案 0 :(得分:2)
只是为了帮助你......("不完全"正确的方式......)
import java.util.Random;
public class Randomiser {
//attribut
public int ranNumber;
//constructeur, called everytime you instanciate an object of this class
public Randomiser() {
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(3);
this.ranNumber = 10 + randomInt;
System.out.println("ranNumber : "+this.ranNumber);
}
}
和
public class Test {
//Method
public static void numberManipulation(){
// instanciate an object of the class Randomiser
Randomiser randomiserInstance = new Randomiser();
int a1 = 20;
// get the attribute of the instance and add 20
int building = randomiserInstance.ranNumber + a1;
System.out.println("building : "+ building);
}
public static void main(String[] args) {
numberManipulation();
}
}
但正如Luiggi Mendoza所说,你必须阅读指南
(class / object),(attributes / getters / setters),(singleton,bit更复杂)