Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to populate a constructor with user input in Java?

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.

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"

Please no snide remarks on "the error tells you what the problem is." No, it doesn't tell me what 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).

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..

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....

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:

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!!

like image 717
auslander Avatar asked Dec 07 '13 13:12

auslander


People also ask

Can constructors take input parameters?

A Java class constructor initializes instances (objects) of that class. Typically, the constructor initializes the fields of the object that need initialization. Java constructors can also take parameters, so fields can be initialized in the object at creation time.

How do you allow user input in Java?

You can get user input like this using a BufferedReader: InputStreamReader inp = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(inp); // you will need to import these things. String name = br. readline();

What are the 3 ways to input in Java?

Java provides three classes to take user input: BufferedReader, Scanner, and Console.

Can we declare variables in constructor?

Constructors act like any other block of code (e.g., a method or an anonymous block). You can declare any variable you want there, but it's scope will be limited to the constructor itself.


3 Answers

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.

I will post a general example, since this is homework, it is better to show you the concept and then let you use 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);    
}
like image 89
Hovercraft Full Of Eels Avatar answered Sep 19 '22 18:09

Hovercraft Full Of Eels


The compiler is complaining that the CarRental constructor needs four parameters (a String, an int, a String, and another int):

"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"

But in UseRentalCar, you haven't passed any:

CarRental rentalCar = new CarRental();

"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"

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.html for more info on that.

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.

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.

like image 40
lreeder Avatar answered Sep 20 '22 18:09

lreeder


"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:
}
like image 23
switchride Avatar answered Sep 21 '22 18:09

switchride