How to pass user input to constructor in java
There is a problem with this line Student pupil = new Student(name, course, student_num);
You reference instance variable here from static context...so it doesn't work.
Actually this line must be the last one when you got all input from user and you create new student from these input.
How to populate a constructor with user input in Java?
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);
}
Can I pass user input to my constructor
Of course you can. You just have to implement a constructor that receives the parameters you want and uses them and then call that contstructor instead. Easy as pie. :-)
NewCamper(String firstName, String lastName){
first = firstName;
last = lastName;
}
and
NewCamper a = new NewCamper(fName, lName);
Having trouble with constructors and user-input
Basically, your code is trying to call the PetInfo
constructor that takes a single string as input. But based on the code you have, no such constructor exists. You just have the large multi-parameter constructor for PetInfo
. You need to call the scanner for input several times before you call the constructor. See the code below:
private static void collectInfo(PetInfo[] info) {
Scanner input = new Scanner(System.in);
try {
for (int i = 0; i < info.length; i++) {
System.out.print("Enter pet name: ");
String petName = input.nextLine();
System.out.print("Enter pet type: ");
boolean petType = input.nextBoolean();
input.nextLine();
System.out.print("Enter pet breed: ");
String petBreed = input.nextLine();
System.out.print("Enter pet age: ");
double petAge = input.nextDouble();
input.nextLine();
System.out.print("Enter pet weight: ");
double petWeight = input.nextDouble();
input.nextLine();
System.out.print("Enter pet owner: ");
String petOwner = input.nextLine();
info[i] = new PetInfo(petName, petType, petBreed, petAge, petWeight, petOwner);
}
}
finally {
input.close();
}
}
Hopefully the code above gives you a good illustration of what I'm talking about. Also, don't forget to call input.nextLine()
after calls to nextBoolean()
and nextDouble()
. Lastly, don't forget to close your input
scanner to avoid a resource leak.
Hope that helps.
Decide what constructor call based on user input
Factory MethodsHave you considered the Factory Method Pattern? Basically, you have a method that's something like this:
public Figure createInstance(int numSides) {
Figure figure = null;
switch(numSides) {
case 0:
figure = new Circle();
break;
case 3:
// etc...
// Make a case for each valid number of sides
// Don't forget to put a "break;" after each case!
default:
// Not a valid shape; print your error message
}
return figure;
}
And let that factory method do the deciding instead.
How to declare a C++ constructor depending on user input?
If you really wanted to use dynamic class hierarchies here, a simple factory function would do the trick.
#include <string_view>
#include <memory>
struct distribution {
virtual float generate() = 0;
virtual ~distribution() = default;
};
struct uniform : distribution {
uniform(float, float);
float generate() final;
};
struct normal : distribution {
normal(float, float);
float generate() final;
};
std::unique_ptr<distribution> make_distribution(std::string_view name,
float x,
float y)
{
// for a large amount of different names, using a
// std::unordered_map<std::string, distribution*(*)(float,float)>
// may be more efficient than an if/else chain
if (name == "uniform") {
return std::make_unique<uniform>(x, y);
}
else if (name == "normal") {
return std::make_unique<normal>(x, y);
}
else {
return nullptr;
}
}
However, I would also consider different approaches, such as using a std::variant
of different distributions, or simply a std::function
or function pointer, assuming that the distributions only have a single virtual function.
Using Scanner class to take user input for constructor Variables
You should read all variables you need to construct your TargetHeartRateCalculator
instance.
System.out.print("Please enter your first name: ");
String firstName = input.next();
System.out.print("Please enter your lastname: ");
String lastName = input.next();
System.out.print("Please enter your birthday day: ");
String birthdayDay = input.nextInt();
System.out.print("Please enter your birthday month: ");
String birthdayMonth = input.nextInt();
System.out.print("Please enter your birthday year: ");
String birthdayYear = input.nextInt();
TargetHeartRateCalculator patient = TargetHeartRateCalculator(firstName, lastName,
birthdayDay, birthdayMonth, birthdayYear);
Then, you can call your static methods after initialized your TargetHeartRateCalculator
.
TargetHeartRateCalculator.displayTargetHeartRate(patient);
But, instead of putting everything into a class and using static methods in TargetHeartRateCalculator
, you should divide your TargetHeartRateCalculator
into two which can be Patient
and TargetHeartRateCalculator
.
Patient class can be like this:
import java.time.LocalDateTime;
public class Patient {
private String fName;
private String lName;
private int dOB;
private int bMonth;
private int bDay;
private int bYear;
private int ageYears;
private int currentYear = LocalDateTime.now().getYear();
private int currentMonth = LocalDateTime.now().getMonthValue();
private int currentDay = LocalDateTime.now().getDayOfMonth();
public Patient(String fName, String lName, int bMonth, int bDay, int bYear) {
this.fName = fName;
this.lName = lName;
this.bMonth = bMonth;
this.bDay = bDay;
this.bYear = bYear;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public int getbMonth() {
return bMonth;
}
public void setbMonth(int bMonth) {
this.bMonth = bMonth;
}
public int getbDay() {
return bDay;
}
public void setbDay(int bDay) {
this.bDay = bDay;
}
public int getbYear() {
return bYear;
}
public void setbYear(int bYear) {
this.bYear = bYear;
}
public int getAgeYear(){
return currentYear -bYear;
}
public int getAgeMonth(){
return currentMonth - bMonth;
}
public int getAgeDay(){
return currentDay - bDay;
}
}
The calculations will be in another class that take Patient
object as an parameter and make calculations.
Related Topics
How to Pass JavaScript Values to Scriptlet in Jsp
How to Prevent Duplicate Results in Hibernate
String Match of Only 3 Specific Words
Enter Array Without Knowing Its Size
Setonclicklistener() on a Null Object Reference Error
Retrieving Data from Biometric Fingerprint Attendance Device
Tomcat Server Error - Port 8080 Already in Use
How to Mock a Generic Parameter for a Unit Test in Java
Java 8: How to Write Lambda Stream to Work With Jsonarray
How to Pass an Array to Constructor
How to Remove Line Breaks from a File in Java
How to Return a Zip File to the Browser Via the Response Outputstream
Convert Yyyy-Mm-Dd Hh:Mm:Ss.Sss Zzz Format Strin to Date Object
Chrome Browser Is Not Opening in Selenium Webdriver
Using Streams to Convert a List of Objects into a String Obtained from the Tostring Method
Java.Lang.Classcastexception: [Ljava.Lang.Object; Cannot Be Cast to Classname