Reputation: 13683
I have the following class:
class Area
{
//Get User Input for classes
int length;
int width;
public Area(int x,int y)
{
length = x;
width = y;
}
public int getArea() {
return width * length;
}
public static void main(String[] args)
{
Area folk = new Area(4,5);
System.out.println("Area of 4 * 5 is: " + folk.getArea());
}
}
I have another class that i use to get user input:
import java.util.Scanner;
class Incoming
{
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number");
//get user input for a
int a = reader.nextInt();
System.out.println("Input Value Is: " + a);
}
}
In the first class i want a user to provide the input instead of the predefined values (i.e. Area folk = new Area(4,5)
)
How can that be done?
Upvotes: 0
Views: 11582
Reputation: 15766
I'm not sure why you have a main in both of your classes. Maybe I'm mis-understanding something, but this will fix it the way you want (I think).
class Area
{
//Get User Input for classes
int length;
int width;
public Area(int x,int y)
{
length = x;
width = y;
}
public int getArea() {
return width * length;
}
public static void main(String[] args)
{
int x, y;
Incoming inc = new Incoming();
x = inc.getInt();
y = inc.getInt();
Area folk = new Area(x,y);
System.out.println("Area of " + x + " * " + y + " is: "
+ folk.getArea());
}
}
And the other class:
import java.util.Scanner;
class Incoming
{
public static int getInt(String[] args)
{
Scanner reader = new Scanner(System.in);
System.out.println("Enter the first number");
//get user input for a
int a = reader.nextInt();
return a;
}
}
Upvotes: 0
Reputation: 1
how about:
Scanner reader = new Scanner(System.in);
Area folk = new Area(reader.nextInt(),reader.nextInt());
system.out.println(folk.getArea());
Upvotes: 0
Reputation: 25666
It looks like you're looking for a way to use the input provided in Incoming
elsewhere in your program.
To do this, move the code to get input out of the main
method. Declare a new method in Incoming
that returns an int
and put it there.
Then, in the main
method of Area
, create an instance of Incoming
and call the new method to get an int
. Do this twice, then pass the resulting values to the Area
constructor.
Upvotes: 1