Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

uber basc java - making the leap from non-object to object oriented

alright, so im doing some java, and in the books i can somehow follow logic when there are multiple java files (when the program is truely object oriented).

I created a program that only has a main method, and out of curiosty, i want to make it object oriented, even though it would probably require more work. Ive been dinking around with the code, and somehow i can't make the leap

here is my code, with a single main method. my question about it is how can i break down this code into a main method as well as a object that is called to accomplish the exact same thing.

import java.util.Scanner;
import java.util.Random;

public class part3_c
{
public static void main (String[] args)
{
//constructing the scanner class so that use can input values

Scanner scan = new Scanner (System.in);

//contructing random generator

Random generator = new Random();

//declaring variable that will house the user's input
int one;
int rone;
int rtwo;
int rthree;

System.out.println("Enter a number");

one = scan.nextInt();

//creating three random intergers that are all less than the first inputed interger
rone = generator.nextInt(one);
rtwo = generator.nextInt(one);
rthree = generator.nextInt(one);

//printing out the result
System.out.println("The number you picked and three random numbers less than it where " + one + "," + rone + "," + rtwo + "," + rthree);
//printing out the average of all 4 numbers
System.out.println("The average of your numbers is " + (one + rone + rtwo + rthree)/3 );
}

}
[1922 byte] By [shabam] at [2007-11-11 7:51:41]
# 1 Re: uber basc java - making the leap from non-object to object oriented
Take all that code from inside your main method, and put it into the constructor of a new class. A class constructor looks like a method, but it has no return type and has the same name as the class it belongs to.

public class Part3C
{
//constructor
public Part3C()
{
//put your code in here
}

public static void main()
{
Part3C object = new Part3C();
}
}

Now just run the main method and i'll do the same thing as before. An alternative would be to put the code inside of a different method instead of the contructor. Put your code in a method called public void run().

Part3C object = new Part3C();
object.run(); //runs your code now
Phaelax at 2007-11-11 22:37:13 >