The only way around making them objects is as follows
class foo
{
int num1
int num2
public void someMethod()
{
Scanner scan = new Scanner(System.in);
Random rand = new Random();
num1 = rand.nextInt(100);
num2 = rand.nextInt(100);
}
}
That would make them global variables which can be accessed from anywhere inside the class without having to pass around objects. However is not the best practice to use. The best practice would be to make an objects which sets num1
and num2
and returns the result of changing the numbers.
That would be done as follows
public class foo
{
TwoNumbers t = new TwoNumbers();
public void someMethod()
{
Scanner scan = new Scanner(System.in);
Random rand = new Random();
int num1 = rand.nextInt(100);
t.setone(num1);
int num2 = rand.nextInt(100);
t.settwo(num2);
}
public void bar()
{
t.getone();
t.gettwo();
}
}
private static class TwoNumbers {
private Integer num1;
private Integer num2;
public void setone(int a) {
this.num1 = a;
}
public settwo(int b)
{
this.num2 = b;
}
public int getone()
{
return this.num1;
}
public int gettwo()
{
return this.num2;
}
}
If you want to keep having to get new numbers from a different method in the class here is how you would do that
public void bar()
{
while(true) //don't know what condtion you need
{
someMethod();
t.getone();
t.gettwo();
}
}