[英]providing user input for a java class
我有以下 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());
}
}
我还有另一个 class 用于获取用户输入:
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);
}
}
在第一个 class 中,我希望用户提供输入而不是预定义值(即Area folk = new Area(4,5)
)
那怎么办?
看起来您正在寻找一种方法来在程序的其他地方使用Incoming
中提供的输入。
为此,请移动代码以从main
方法中获取输入。 在Incoming
中声明一个返回int
的新方法并将其放在那里。
然后,在Area
的main
方法中,创建一个Incoming
的实例并调用新方法来获取一个int
。 这样做两次,然后将结果值传递给Area
构造函数。
我不确定为什么你的两个班级都有一个 main 。 也许我误解了某些东西,但这会按照你想要的方式解决它(我认为)。
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());
}
}
另一个 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;
}
}
怎么样:
扫描仪阅读器=新扫描仪(System.in);
Area folk = new Area(reader.nextInt(),reader.nextInt());
system.out.println(folk.getArea());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.