Wagner Maximiliano Wagner Maximiliano - 1 year ago 39
Java Question

How do I make two classes to work together in Java?

I have been trying for weeks in this project where I have to make one class that generates 500 random numbers from 1-250 and in a second class I have to inherit the first class properties and write all those numbers in a text file but when I have being having problems getting the properties and work with it and I haven't found a way to do it online.

My First class is

import java.util.Random;

public class GenKeys {

public static void random(){
for (int i = 0; i < 250; i++) {

int x = (int) (Math.random() * 100);

and my second code is

import java.util.Random;
import java.io.*;
import java.lang.*;
public class MainProg extends GenKeys{

public static void main(String[] args){

public static void random(){
try {

BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));

out.write( x + System.getProperty("line.separator"));// when i compile the x is not found!!!

} catch (IOException e) {

How can I make the two classes work together?

Answer Source

and i havent found a way to do it online.

I'm not sure you've looked hard enough.

How to get your code working

Firstly, you want to change the type and name of your method to an int.

public static int randomNum()

Then, remove the loop from the code, and just return the random number generated:

return (int)Math.Random() * 100; //By the way there is a Random class.

In the random method, you want the loop:

for(int x = 0; x < 250; x++)
    BufferedWriter out = new BufferedWriter(new FileWriter("file.txt"));
    out.write( randomNum() + System.getProperty("line.separator"));


The various issues with your code

You're mis-using inheritance here. Your class is not a type of GenKey. It simply uses it, so it should be a field in your class.

Secondly, a method can only return one value, or one object. It can not return 250 numbers as is. You're assigning 250 numbers to x. This is only going to store the last number generated.