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!!
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);
}
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.
"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:
}
Related
I've been going back and forward on how to deal with this. I have been trying to take input from user in GradesApp.java and store in my variable "gradesPossible" then pass it to another class Grades.java. I don't mind if it is the same name variable or different. I was trying to use setter or getter method, but I am not very familiar with it.
GradesApp.java :
public class GradesApp {
public static void main(String[] args) {
System.out.print("Enter the total points possible for the class: ");
int gradesPossible = Integer.parseInt(s.nextLine());
I want to access "gradesPossible" in Grades.java
Grades.java:
public class Grades {
public double gradesFor3Classes()
{
double grade1 = (gradesPossible*3);
return grade1;
}
Edited typos
what do you want to do with value of the gradesPossible? If you want to calculate the value, maybe it's something like this:
public class GradesApp {
public static void main(String[] args) {
System.out.print("Enter the total points possible for the class: ");
int gradesPossible = Integer.parseInt(s.nextLine());
Grades grades = new Grades();
double gradeResult = grades.calculateGrade(gradesPossible);
System.out.print("Value Grade: " + gradeResult);
}
}
And this is for Grades class
public class Grades {
public double calculateGrade(int gradesPossible) {
double grade1 = (gradesPossible*3);
return grade1;
}
}
Hope this helps!
class pizza {
public int pizza (int price, int discount) {
int total = 0;
total = price - discount;
return total;
}
}
public class MyClass {
public static void main(String[] args) {
int itemNum;
int price;
String pizName;
boolean extraCheese;
itemNum = 1101;
pizName = "Pepperoni";
extraCheese = false;
System.out.println ("Your order a" +pizName+ "pizza will be served shortly.");
pizza pepperoni = new pizza (50, 10);
System.out.println("Your payment without discount is:" + pepperoni.price);
}
}
This is my code above any help would be appreciated. Thank you so much guys. Java is a general-purpose computer-programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible.
The name of the method and class should not be same. You are trying to initialise instance variable using constructor. But the syntax for the constructor is not correct and also it implicitly returns reference to the object.
I am trying to write a java program which have two classes. The second class will have the main method and for checking the balance of the account and. The first class will have three methods one for opening an bank account, one for deposit and one for withdrawal. All input needs to be given by user. I am new to java and stuck after at one point any help would be appreciated.
import java.util.Scanner;
class Balance {
static int account()
{ Scanner minimumAmount = new Scanner(System.in);
int openingAmount = minimumAmount.nextInt();
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account:" + openingAmount);
if (openingAmount > 1000)
{
System.out.println("Your Bank account has opened successfully");
int ac = minimumAmount.nextInt();
System.out.println("Enter your account number" + ac);
}
}
static int withdrawal() {
Scanner withdrawalAmount = new Scanner(System.in);
int w = withdrawalAmount.nextInt();
System.out.println("Withdrawal Amount is :" + w);
int b = openingAmount - w;
if (b < 100) {
System.out.println("Unable to process your request");
}
}
void deposit() {
Scanner depositAmount = new Scanner(System.in);
int d = depositAmount.nextInt();
System.out.println("Deposited amount is :" + d);
int b = openingAmount + d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
}
}
i) Is there a way where an user input variable declared under one method can be used in another method to declare another variable?
ii) ow to return a value from a method so that the value received works in different method while declaring a variable?
Is there a way where an user input variable declared under one method
can be used in another method to declare another variable?
You can declare your attribute in your class and use constructor to initialize it for example :
class A{
private String name;
public A(String name){
this.name = name
}
public int account(){
//can use and change the name
}
public int withdrawal(){
//can use and change the name
}
public int deposit(){
//can use and change the name
}
}
Main class
public class B{
public static void main(String[] args) {
A s = new A("Hello");
//------------^^---pass your attribute in the constructor
s.account();
s.withdrawal();
s.deposit();
}
}
How to return a value from a method so that the value received works
in different method while declaring a variable?
You can use the result of each method in another method for example :
s.withdrawal(s.account());
//--------------^^-------account return a result that can be used by withdrawal
I don't know what you really want to do, but I can explain some things.
Methods account() & withdrawal() don't have to be static.
You can use instance attribute like I do to store values.
Balance & AccountBalance should be in different files.
Take a look about private & public on attribut & methods (& getter/setter)
Scanner is a little bit tricky so you should declare it once, and reuse it.
If you want to use returned value from function, change void by int (in this case) and use "return var" (var is what you want to return). So when you can call the function like this -> int value = s.account();
Try this code, it works.
Cheers !
import java.util.Scanner;
class Balance {
private Scanner scanner;
public int userAccount;
public int userAccountNumber;
public Balance() {
scanner = new Scanner(System.in);
}
public void account() {
System.out.print("Please deposit an amount more than Rs. 1000.00 to open a Bank account : ");
int openingAmount = scanner.nextInt();
if (openingAmount > 1000) {
System.out.println("Your Bank account has opened successfully");
userAccount = openingAmount;
System.out.println("Enter your account number : ");
userAccountNumber = scanner.nextInt();
} else {
System.out.println("Not enought money");
this.account(); //Ask again for opening an account
}
}
public void withdrawal() {
System.out.println("Withdrawal Amount is : ");
int w = scanner.nextInt();
int b = userAccount - w;
if (b < 100) {
System.out.println("Unable to process your request");
} else {
userAccount = b;
}
}
public void deposit() {
System.out.println("Deposited amount is : ");
int d = scanner.nextInt();
userAccount += d;
}
}
public class AccountBalance {
public static void main(String[] args) {
Balance s = new Balance();
s.account();
s.withdrawal();
s.deposit();
System.out.println("Final amount is : "+s.userAccount);
}
}
I am currently learning about methods and using methods. It sometimes confuses my mind when deciding what to put inside the parameters. I have some code where I created three methods and all correspond. What I must do for this program is to display some services and prices and ask the user if he/she would like it. If they say yes, the prices add up until the end of the array. The part I am having trouble with is how to take in the price from main in my third method. I know that I should use a void method because I am not returning anything, just printing out the prices to the user.
Heres my piece of code for this program:
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("What automobile make do you own?");
Scanner keyboard = new Scanner(System.in);
String name = keyboard.nextLine();
make(name);
double price = carMaintenance(name);
finalPrice(price);
}
// First Method
public static void make(String name) {
System.out.println("Hello! We will be happy to service your " + name
+ " automobile today!");
}
// Second Method
public static double carMaintenance(String name) {
String[] services = { "Oil Change", "Tire Rotation", "Air Filter",
"Check Fluids" };
double[] prices = { 39.99, 49.99, 19.99, 10.99 };
double Total = 0;
for (int i = 0; i < services.length; i++) {
System.out.println("Do you want a " + services[i] + " for your "
+ name + " " + prices[i] + "? (y/n)");
String answer;
answer = keyboard.nextLine();
if (answer.equals("y"))
{
Total = Total + prices[i];
}
// Third method
public static void finalPrice ( ? )
Specifically this the part I am having trouble with:
// Third method
public static void finalPrice (double price )
The problem is finalPrice is an invalid type for the variabl which is pretty confusing about.
You have to change finalPrice() to accept a double parameter:
public static void finalPrice(double price) { ... }
And pass the value returned by carMaintenance() to finalPrice():
double price = carMaintenance(name);
finalPrice(price);
Note I am assuming you just forgot to paste the rest of the carMaintenance() method. In the end, of course, it should have the return Total statement.
Your second method is lacking a return statement. You can return the total to main and then send it to your third method, as such:
public static void main(String[] args) {
System.out.println("What automobile make do you own?");
Scanner keyboard = new Scanner(System.in);
String name = keyboard.nextLine();
make(name);
double finalPrice = carMaintenance(name);
printFinalPrice(finalPrice);
}
//first method code here
public static double carMaintenance(String name) {
//second method code here, plus:
return total;
}
// Third method
public static void printFinalPrice(double finalprice) {
System.out.println("Your final price is " + finalprice);
}
Pass double from carMaintance to finalPrice
double finalPriceDbl = carMaintenance(name);
finalprice(finalPriceDbl);
and accept double as parameter in finalPrice
public static void finalPrice ( double finalPrice );
also you should return value from carMaintenance with return statemenet
return Total;
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I just learned about constructors and had to use them in a recent program. I got it right however I still do not understand exactly what they do. If someone could give me a detailed explanation using this program as reference that would be great!
MAIN CLASS
public class Student
{
public static void main(String[]args)
{
String question, name, GPAStr, studentNumberStr;
int studentNumber;
double GPA;
question = JOptionPane.showInputDialog("Would you like to see if you Qualify for the Dean's List? (Y or N)");
while (question.equalsIgnoreCase("Y"))
{
name = JOptionPane.showInputDialog("Please enter your name.");
studentNumberStr = JOptionPane.showInputDialog("Please enter your student number.");
studentNumber = Integer.parseInt(studentNumberStr);
GPAStr = JOptionPane.showInputDialog("Please enter your GPA.");
GPA = Double.parseDouble(GPAStr);
StudentIO students = new StudentIO(name, GPA);
// ouput
JOptionPane.showMessageDialog(null, students.getDeansList());
question = JOptionPane.showInputDialog("Would you like to see if you Qualify for the Dean's List? (Y or N)");
if (question.equalsIgnoreCase("N"))
//display the content of players processed
{
JOptionPane.showMessageDialog(null,StudentIO.getCount());
}
}
}
}
SECOND CLASS(THE ONE WITH CONSTRUCTORS THEY ARE LABELED)
public class StudentIO
{
//instance fields
private String name;
private double GPA;
// static fields
private static final double GPAMIN=3.0;
private static int count = 0;
public StudentIO(String theName, double theGPA) // constructor
{
name = theName;
GPA= theGPA;
count = count +1;
}
public StudentIO() //no arg constructor
{
name = " ";
GPA = 0;
count = count +1;
}
public void setName(String theName)
{
name = theName;
}
public void setGPA(double theGPA)
{
GPA = theGPA;
}
public String getName()
{
return name;
}
public double getGPA()
{
return GPA;
}
public String getDeansList()
{
if(GPA >= GPAMIN)
return (name + ", has made the Dean's List!");
else
return(name + ", did not make the Dean's List!");
}
public static String getCount()
{
return ("You processed " + count + "students.");
}
}
StudentIO students = new StudentIO(name, GPA);
Will create a StudentIO object called students, and affect name and GPA parameters to your object created by using the first contractor:
public StudentIO(String theName, double theGPA) // constructor
{
name = theName;
GPA= theGPA;
count = count +1;
}
And that is equivalent to call :
StudentIO students = new StudentIO();
students.setName(name);
students.setGPA(GPA);
which will use the seconde contractor :
public StudentIO() //no arg constructor
{
name = " ";
GPA = 0;
count = count +1;
}
with the two methods
public void setName(String theName)
{
name = theName;
}
public void setGPA(double theGPA)
{
GPA = theGPA;
}
Finaly, the two approach give you the same result, its a style matter, and some times we are forced to use the seconds one in a strong coupled objects.
count = count +1;
It seems you are referring to this line in the constructors. The variable count is a static member in StudentIO class and is being used to keep track of number of StudentIO objects created using the parameterized or default constructor.
The construct instances of the StudentIO class. Their purpose is to set initial state for the new instance(s) of StudentIO. Each instance has its' own state. Static variables are shared among instances, so on each construction you're adding one to a count. It'll tell you how many instance(s) have been created (I guess).