如何使用 Java 中的用户输入填充构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20442044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to populate a constructor with user input in Java?
提问by auslander
I've hit a wall on an assignment and have been combing the site for anything helpful (came up empty). I'm required to create a class, a constructor within that class, and then a subclass to extend the superclass. Then, I'm required to create a new file with a main method to demonstrate both cases. No problem, conceptually.
我在一项任务上碰壁了,并且一直在梳理网站以寻找任何有用的东西(空空如也)。我需要创建一个类,该类中的一个构造函数,然后是一个子类来扩展超类。然后,我需要使用 main 方法创建一个新文件来演示这两种情况。没问题,概念上。
My question is this: how do I initialize an object using the constructor, but with user input?
我的问题是:如何使用构造函数初始化对象,但使用用户输入?
Right now the error I'm getting is: "constructor CarRental in class CarRental cannot be applied to given types; required: String,int,String,int found: no arguments reason: actual and formal argument lists differ in length"
现在我得到的错误是:“CarRental 类中的构造函数 CarRental 不能应用于给定类型;需要:String,int,String,int found:无参数原因:实际和形式参数列表的长度不同”
Please no snide remarks on "the error tells you what the problem is." No, it doesn't tell mewhat it is. I'm a wee babe in this stuff and need a little hand-holding.
请不要对“错误告诉您问题是什么”进行冷嘲热讽。不,它没有告诉我它是什么。我在这方面是个小宝贝,需要一点帮助。
I'll paste my 3 classes below. They will probably make you writhe in agony, since I'm such a newb (also, my class is an abbreviated 8-week course where virtually no time was dedicated to pseudocode, so I have the extra challenge of conceiving the logic itself).
我将在下面粘贴我的 3 个课程。它们可能会让你痛苦不堪,因为我是一个新手(而且,我的课程是一个 8 周的简短课程,几乎没有时间专门用于伪代码,所以我有一个额外的挑战来构思逻辑本身)。
I am not looking for anyone to do my homework for me, I am just looking for a helping hand in the UseCarRental.java file. Here's my code..
我不是在寻找任何人为我做作业,我只是在 UseCarRental.java 文件中寻找帮助。这是我的代码..
public class CarRental {
protected String renterName;
protected int zipCode;
protected String carSize;
protected double dailyRate;
protected int rentalDays;
protected double totalCost;
final double ECONOMY = 29.99;
final double MIDSIZE = 38.99;
final double FULLSIZE = 43.50;
public CarRental(String renterName, int zipCode, String carSize, int rentalDays){
totalCost = dailyRate * rentalDays;
}
public String getRenterName(){
return renterName;
}
public void setRenterName(String renter){
renterName = renter;
}
public int getZipCode(){
return zipCode;
}
public void setZipCode(int zip){
zipCode = zip;
}
public String getCarSize(){
return carSize;
}
public void setCarSize(String size){
carSize = size;
}
public double getDailyRate(){
return dailyRate;
}
public void setDailyRate(double rate){
switch (getCarSize()) {
case "e":
rate = ECONOMY;
break;
case "m":
rate = MIDSIZE;
break;
case "f":
rate = FULLSIZE;
break;
}
}
public int getRentalDays(){
return rentalDays;
}
public void setRentalDays(int days){
rentalDays = days;
}
public double getTotalCost(){
return totalCost;
}
public void setTotalCost(double cost){
totalCost = cost;
}
public void displayRental(){
System.out.println("==============================================");
System.out.println("Renter Name: " + getRenterName());
System.out.println("Renter Zip Code: " + getZipCode());
System.out.println("Car size: " + getCarSize());
System.out.println("Daily rental cost: $" + getDailyRate());
System.out.println("Number of days: " + getRentalDays());
System.out.println("Total cost: $" + getTotalCost());
}
}
the subclass LuxuryCarRental....
子类 LuxuryCarRental....
public class LuxuryCarRental extends CarRental {
final double chauffeur = 200.00;
final double dailyRate = 79.99;
protected String chauffeurStatus;
public LuxuryCarRental(String renterName, int zipCode, String carSize, int rentalDays) {
super(renterName, zipCode, carSize, rentalDays);
}
public String getChauffeurStatus(){
return chauffeurStatus;
}
public void setChauffeurStatus(String driver){
chauffeurStatus = driver;
}
public double getChauffeurFee(){
return chauffeur;
}
public void setTotalLuxuryCost(){
if (chauffeurStatus=="y")
setTotalCost((dailyRate * getRentalDays()) + (chauffeur * getRentalDays()));
else
setTotalCost(dailyRate * getRentalDays());
}
@Override
public void displayRental(){
System.out.println("==============================================");
System.out.println("Renter Name: " + getRenterName());
System.out.println("Renter Zip Code: " + getZipCode());
System.out.println("Car size: " + getCarSize());
System.out.println("Optional Chauffeur fee: $" + getChauffeurFee());
System.out.println("Daily rental cost: $" + getDailyRate());
System.out.println("Number of days: " + getRentalDays());
System.out.println("Total cost: $" + getTotalCost());
}
}
and now the class with the main method:
现在是带有 main 方法的类:
import java.util.Scanner;
public class UseRentalCar {
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
CarRental rentalCar = new CarRental();
System.out.println("==========================");
System.out.println("RENTAL CAR SELECTION");
System.out.println("==========================");
System.out.println("Enter your name: ");
rentalCar.setRenterName(keyboard.next());
System.out.println("Enter your zip code: ");
rentalCar.setZipCode(keyboard.nextInt());
System.out.println("Enter the car size ("e=Economy, m=Midsize, f=Fullsize: ");
rentalCar.setCarSize(keyboard.next());
System.out.println("Enter the number of days: ");
rentalCar.setRentalDays(keyboard.nextInt());
rentalCar.displayRental();
}
}
(omitted some cause it doesn't matter, mainly trying to get the object instantiation working)
(省略了一些无关紧要的原因,主要是试图让对象实例化工作)
thanks for any help!!
谢谢你的帮助!!
采纳答案by Hovercraft Full Of Eels
Create local variables in your main method, say String and int variables, and then after these variables have been filled with user input, use them to call a constructor.
在你的 main 方法中创建局部变量,比如 String 和 int 变量,然后在用用户输入填充这些变量后,使用它们来调用构造函数。
I will post a general example, since this is homework, it is better to show you the concept and then let youuse the concept to create the code:
我将发布一个通用示例,因为这是作业,最好向您展示概念,然后让您使用概念来创建代码:
public class Foo {
private String name;
private int value;
public Foo(String name, int value) {
this.name = name;
this.value = value;
}
}
elsewhere
别处
import java.util.Scanner;
public class Bar {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter name: ");
String name = keyboard.nextLine(); // local variable
System.out.print("Please enter value: " );
int number = keyboard.nextint(); // another local variable
keyboard.nextLine(); // to handle the end of line characters
// use local variables in constructor call
Foo foo = new Foo(name, number);
}
回答by lreeder
The compiler is complaining that the CarRental constructor needs four parameters (a String, an int, a String, and another int):
编译器抱怨 CarRental 构造函数需要四个参数(一个 String、一个 int、一个 String 和另一个 int):
"constructor CarRental in class CarRental cannot be applied to given types; required: String,int,String,intfound: no arguments reason: actual and formal argument lists differ in length"
“CarRental 类中的构造函数 CarRental 不能应用于给定类型;必需:String,int,String,int找到:没有参数原因:实际和形式参数列表的长度不同”
But in UseRentalCar, you haven't passed any:
但是在 UseRentalCar 中,您没有通过任何:
CarRental rentalCar = new CarRental();
CarRental rentalCar = new CarRental();
"constructor CarRental in class CarRental cannot be applied to given types; required: String,int,String,int found: no argumentsreason: actual and formal argument lists differ in length"
“CarRental 类中的构造函数 CarRental 不能应用于给定类型;必需:String,int,String,int找到:没有参数原因:实际和形式参数列表的长度不同”
If you don't provide a constructor for your class, Java will create a no-arg constuctor for you. If you provide your own (which you did in CarRental with 4 parameters), java will not create a no-arg constuctor, so you can't reference it. See http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.htmlfor more info on that.
如果您没有为您的类提供构造函数,Java 将为您创建一个无参数的构造函数。如果您提供自己的(您在 CarRental 中使用 4 个参数所做的),java 将不会创建无参数构造函数,因此您无法引用它。有关更多信息,请参阅http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html。
You could add a no-arg constructor yourself since Java didn't do it for you. Or since you provide setters for your rental car classes, you could just use those like you are now, and remove your 4-arg constructor in CarRental (and LuxuryCarRental) and let Java add the default one.
你可以自己添加一个无参数构造函数,因为 Java 没有为你做。或者因为你为你的租车类提供了 setter,你可以像现在一样使用它们,并删除 CarRental(和 LuxuryCarRental)中的 4-arg 构造函数,让 Java 添加默认的构造函数。
Alternatively, if you want to keep those constructors for some reason, you could save the user input in local variables and defer the call to the 4-arg constructor until after you have all the user input.
或者,如果您出于某种原因想要保留这些构造函数,您可以将用户输入保存在局部变量中,并将对 4-arg 构造函数的调用推迟到您拥有所有用户输入之后。
回答by switchride
"My question is this: how do I initialize an object using the constructor, but with user input?"
“我的问题是:如何使用构造函数初始化对象,但使用用户输入?”
some psuedo-ish code that might help
一些可能有帮助的伪代码
main{
Scanner input = new Scanner(system.in);
int x = input.nextInt();
yourClass myClass = new yourClass(x); //passes x into the constructor
}//end main
yourClass
{
int data;
public yourClass(int i)
{
data = x:
}