I am very new to Java and have searched through previously asked questions which haven't helped my issue...
How do I pass the int variable age, and the String name, from the main class to the Person class?
package engineers;
import java.util.Scanner;
public class Engineers {
public static void main(String[] args) {
// TODO code application logic here
Scanner scan = new Scanner(System.in); //declaration and ssignment of scanner
System.out.println("Enter name: "); //name prompt
String name = scan.next(); //reads name input from user
System.out.println("Enter age: "); //age prompt
int age = scan.nextInt(); //reads age input from user
System.out.println("Pay check amount: ");
double salary = scan.nextDouble();
Person person = new Person();
}
private static class Person {
/**
* A default constructor
*/
public Person() {
}
/**
* method for displaying the computation result
*/
double avgSalary = 40000 * Math.sqrt(Math.exp(0.04295 * age + 0.141) );
public void showData(int age, double pay){
System.out.printf( "%s earns $%4.3f for age %3d.\n", name, (pay*Math.sqrt(age)*.15), age);
}//end method showData
}
}
You should use Person constructor like this:
public Person(int age, String name) {
this.age = age;
this.name = name;
}
And add two fields in your Person class, before your constructor:
private int age;
private String name;
Then I am assuming you need to use this variables inside the person class, in order to do this, you can do something like this:
double avgSalary = 40000 * Math.sqrt(Math.exp(0.04295 * this.age + 0.141) );
To reference your variable:
public void showData(){
System.out.printf( "%s earns $%4.3f for age %3d.\n", this.name, (pay*Math.sqrt(this.age)*.15), this.age);
}//end method showData
Finnaly, you need to instantiate your Person object to use it:
Person p = new Person(name, age);
I would also recommend (since you are learning java), to understand the difference between getters/setters and constructor approach: Setter methods or constructors
You mean something like this?
int age;
String name;
class Person(int age, String name) {
this.age = age;
this.name = name;
}
Or (And)
void setAge(int age) {
this.age = age;
}
void setName(String name) {
this.name = name;
}
You would want to define a constructor with any argument another class may need for the most basic functioning.
A Person istance would be initialized with a name and age (even though It would be better to store a birth date and calculate the age against the current date).
To do this, you'd need the class Person to look like this:
public class Person{
private String name;
private Date birthdate;
//Constructor method
public Person(String n, Date bd){
name=n;
birthdate=bd;
}
//Other methods
}
In the main() method, you would then create a new istance of Person, after getting anything needed, like this:
Person p = new(name, date);
Related
In this example, I would like to add students of a school into an ArrayList and print the array list with Polymorphism format from another method defined in another class.
import java.util.ArrayList;
class Student{
public static String name;
public static String gender;
public static int age;
//setting default values for the member variables
public Student(){
name = "default name";
gender = "default gender";
age = 0;
}
//constructor of the parameters for the name, gender, and age.
public Student(String name, String gender, int age){
Student.name = name;
Student.gender = gender;
Student.age = age;
}
// Polymorphism to print with a specific format
public static void printInfo(){
System.out.println(name+", "+gender+", "+age+"\n");
}
}
// creating a class for Male students
class Male extends Student{
private static String gender;
public Male(String name, int age){
super(name, gender, age);
Male.gender = "Male";
}
}
// creating a class for Female students
class Female extends Student{
private static String gender;
public Female(String name, int age){
super(name, gender, age);
Female.gender = "Female";
}
}
// create a class for school to collect all the students
class School{
static ArrayList<Student> students;
public static void addStudent(Student a){
ArrayList<Student> students = new ArrayList<Student>();
students.add(a);
}
public void printAllInfo(){
//call the Student.printInfo method from the Student class
}
}
public class SchoolBuilder{
public static void main(String[] args){
School.addStudent(new Male("Sam",13));
School.addStudent(new Male("John",11));
School.addStudent(new Female("Elle",12));
School.addStudent(new Male("Paul",12));
School.addStudent(new Female("Javinia",11));
School.addStudent(new Male("Paperino",12));
//PRint all by calling School.printAllInfo should print the formatted ArrayList
}
}
The output should be like this:
Sam, Male, 13
John, Male, 11
Elle, Female, 12
Paul, Male, 12
Javinia, Female, 11
Paperino, Male, 12
I am new to JAVA and just can't figure out how to do it. It seems like it's easy.
I've made the two classes for gender because it is easy to add later a CSV file of all males or females and add them into the dataset calling the male and female classes respectively.
Thanks for your time and help with this.
In general, we do this by overriding the toString() method of some class, and then printing that.
Take the following as constructive criticism: there are a bunch of issues here.
You want to avoid the static context in this case, because static
variables belong to a class. Not every student will have the same
name, for example.
Similarly, you wouldn't call Student.function(), you would call this.function() to call that for only that student, not the class student. this is an instance of Student.
You definitely don't want to do ArrayList<Student> students = new
ArrayList<Student>(); within your addStudent() method. You're
resetting your list of students every time you add a student. Keep
that in the class level declaration or better yet, add a
constructor.
import java.util.ArrayList;
class Student{
public String name;
public String gender;
public int age;
//setting default values for the member variables
public Student(){
name = "default name";
gender = "default gender";
age = 0;
}
//constructor of the parameters for the name, gender, and age.
public Student(String name, String gender, int age){
this.name = name;
this.gender = gender;
this.age = age;
}
// Polymorphism to print with a specific format
public String printInfo(){
return name+", "+gender+", "+age+"\n";
}
}
// creating a class for Male students
class Male extends Student{
private static String gender;
public Male(String name, int age){
super(name, gender, age);
Male.gender = "Male";
}
}
// creating a class for Female students
class Female extends Student{
private static String gender;
public Female(String name, int age){
super(name, gender, age);
Female.gender = "Female";
}
}
// create a class for school to collect all the students
class School{
ArrayList<Student> students = new ArrayList<Student>();
public void addStudent(Student a) {
students.add(a);
}
public void printAllInfo(){
//call the Student.printInfo method from the Student class
}
public String toString() {
String string = "";
for (Student s : students) {
string += s.printInfo();
}
return string;
}
}
public class Work{
public static void main(String[] args){
School sch = new School();
sch.addStudent(new Male("Sam",13));
sch.addStudent(new Male("John",11));
sch.addStudent(new Female("Elle",12));
sch.addStudent(new Male("Paul",12));
sch.addStudent(new Female("Javinia",11));
sch.addStudent(new Male("Paperino",12));
System.out.println(sch.toString());
}
}
There are some error in your implementation:
The Student object should not has static fields. static means that they're not referred to a specific object, but to the class itself.
The object is a specific implementation of a class. You define a Student class to define how a student looks like, that with a specific instatiation you create a student.
When you declare the class, you say that a student has in general a name, gender and age.When you istantiate a student with the constructor (new Student("Sam", "Male", 13)) you define the specific implementation.
class Student {
public String name;
public String gender;
public int age;
//setting default values for the member variables
public Student(){
name = "default name";
gender = "default gender";
age = 0;
}
//constructor of the parameters for the name, gender, and age.
public Student(String name, String gender, int age){
this.name = name;
this.gender = gender;
this.age = age;
}
Class Male and Female has to be changed. It's not wrong to extend the Student class to set a default value to the gender field. It would be more useful to extend it if, for example, the Male class has a specific field (for example favouriteSoccerPlayer) which instead a general student should not have. In that case the Male class would inherit the fields from the parent class (Student) and add another extra field:
class Male extends Student {
private String favouriteSoccerPlayer;
public Male(String name, int age) {
super(name, "Male", age); // call the constructor of the super class
}
public Male(String name, int age, String favouriteSoccerPlayer) {
super(name, "Male", age); // call the constructor of the super class
this.favouriteSoccerPlayer = favouriteSoccerPlayer;
}
// getter and setter for only this field
}
then you can for example do something like this:
Male male = new Male("John", 32, "Maradona");
System.out.println(male.getName());
and you'll call the method that the Male object inherit from the Student class.
This would be class Male, same is for Female:
// creating a class for Male students
class Male extends Student{
private static final String gender = "Male";//This should be constant for all instances of class and because of that it is "static final"
public Male(String name, int age){
super(name, gender, age);
}
}
Next School would not have any static thing in it.
import java.util.ArrayList;
// create a class for school to collect all the students
class School {
private ArrayList<Student> students; //Should not be static, and initialization moved in constructor
public School() {
students = new ArrayList<>();
}
public void addStudent(Student a) {
students.add(a);
}
public void printAllInfo() {
for (Student s : students) {
s.printInfo();
}
}
}
Finally main class should create School instance, add students and print them:
public class SchoolBuilder{
public static void main(String[] args){
School school=new School();
school.addStudent(new Male("Sam",13));
school.addStudent(new Male("John",11));
school.addStudent(new Female("Elle",12));
school.addStudent(new Male("Paul",12));
school.addStudent(new Female("Javinia",11));
school.addStudent(new Male("Paperino",12));
school.printAllInfo();
}
}
Last, this method in Student should not have \n in String as it will add one more new line.
// Polymorphism to print with a specific format
public void printInfo(){
System.out.println(name+", "+gender+", "+age+"\n");
}
I have this program that has to ask the user if they want to enter the students name only or to enter the students name and banner ID. Then they can type either "just name" or "both", then the appropriate question will follow. Using the Student class I made, I have to use the appropriate constructor to print out the answer to the screen, either just students name or students name and banner ID. I think I'm getting messed up on how to create the constructors, the instructions say to create three constructors, one that takes the name and banner ID, one that takes just name, and one that takes no arguments and it wants me to create them inside the Student class, I thought they got created inside the main class to access the Student class.
package classwork6_2;
import java.util.Scanner;
public class ClassWork6_2 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Would you like to enter student's name only or name and banner ID?: ");
String response = s.nextLine();
String name;
long banID;
if(response.equalsIgnoreCase("just name")){
System.out.print("Enter student's name: ");
name = s.nextLine();
} else if(response.equalsIgnoreCase("both")){
System.out.print("Enter students name: ");
name = s.nextLine();
System.out.print("Enter student's banner ID: ");
banID = s.nextLong();
}
Student nameBanID = new Student();
nameBanID.setNameBanID(name, banID);
Student n = new Student();
n.setName(name);
System.out.print("Students name is: " + n.getName());
System.out.print("Student's banner ID is: " + n.getNameBanID());
}
}
Student class
package classwork6_2;
public class Student {
private String name;
private String bannerID;
Student nameBanID = new Student();
Student n = new Student();
Student none = new Student();
public String getNameBanID(){
return bannerID + name;
}
public String getName(){
return name;
}
public void setNameBanID(String name, long banID){
bannerID = bannerID + name;
}
public void setName(String name){
this.name = name;
}
}
You're getting a stack overflow error because of these lines in your Student class
Student nameBanID = new Student();
Student n = new Student();
Student none = new Student();
In your ClassWork6_2 when you call Student nameBanID = new Student(); you are creating an instance of the Student class and assigning it to the nameBanID variable. When you are creating an instance of the class it is immediately hitting the line that says Student nameBanID = new Student(); causing your code to go through a loop of creating a new student until a stack overflow error occurs.
Here are how the three constructors should look
private String name;
//changed bannerID to long to match input from code example
private long bannerID;
public Student(String name){
setName(name);
}
public Student(long bannerID){
setBannerID(bannerID);
}
public Student(String name, long bannerID){
setName(name);
setBannerID(bannerID);
}
Your current code does not define any constructors, but java will create a default constructor for you when you do not define one. Once your constructor is defined you can create a student object using those constructors.
String studentName = "Jeffery";
long bannerID = 123456789;
Student studentWithName = new Student(studentName);
Student studentWithBannerID = new Student(bannerID);
Student studentWithNameAndBannerID = new Student(studentName,bannerID);
Here are all of the modifications I made to your student class
class Student {
private String name;
private long bannerID;
public Student(String name){
setName(name);
}
public Student(long bannerID){
setBannerID(bannerID);
}
public Student(String name, long bannerID){
setName(name);
setBannerID(bannerID);
}
public Student(){}
public String getNameBanID(){
return bannerID + name;
}
public String getName(){
return name;
}
public long getBannerID(){
return bannerID;
}
public void setBannerID(long bannerID){
this.bannerID = bannerID;
}
public void setName(String name){
this.name = name;
}
}
When you create a new Student object, you then create and initialize another 3 Student objects. This causes a recursion of Student creation, resulting in a java.lang.StackOverflowError.
You also don't seem to have a constructor for your Student class (eg. public Student () {...}). Ideally, the constructor is where you would initialize your class variables.
Try this: instead of creating the 3 Student objects in the class itself, create them in the main method. Also add in a constructor method for your Student class
I have a question to keyword this and variables scope in methods.
In general I know how to use this keyword, but got confused when observed the same result for all 3 options below into method balance.
The question is, what is the correct implementation of option and why it treats all the options with the same result.
Does it mean that if there is no local variable in the method balance, this keyword is ignored?
Thanks a lot!
option#1
public int balance(int balance) {
this.age = this.age + balance;
return age;
}
option#2
public int balance(int balance) {
age = age + balance;
return age;
}
option#3
public int balance(int balance) {
age = age + balance;
return this.age;
}
Code
package com;
public class Elephant {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
public int balance(int balance) {
age = age + balance;
return age;
}
public int getAge() {
return age;
}
public Elephant(String name, int age) {
this.name = name;
if (age > 0) {
this.age = age;
}
}
}
package com;
import java.util.Scanner;
public class MainClass {
public static void main(String arg[]) {
Elephant e1 = new Elephant("Elephant1: ", 7);
System.out.printf("Elephant name: %s age: %s \n", e1.getName(), e1.getAge());
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
e1.balance(i);
System.out.printf("Entered deposit for e1: %d \n", i);
System.out.printf("Balance for e1: %s", e1.getAge());
}
}
Result for all 3 options is the same:
Elephant name: Elephant1: age: 7
11
Entered deposit for e1: 11
Balance for e1: 18
Apart from situations when you need to pass or store a reference to the object from inside its instance method, you need keyword this when resolving an unqualified name requires applying disambiguation rules.
For example, this code needs it:
public void setAge(int age) {
if (age > 0) {
this.age = age;
}
}
Identifier age could refer to the member field age or the parameter age. The compiler applies the rule that parameters and local variables "shadow" fields with identical names to remove ambiguity. That is why you must prefix age with this in the assignment; otherwise, the field wouldn't be assigned.
Your balance method, on the other hand, does not need keyword this at all, because it has no ambiguous name resolutions.
In Java, this is always a reference to the current object. Object properties and methods of the current object can be accessed without explicitly mentioning this. Which one you want to use (with or without mentioning this), is often merely a matter of clarity and coding style guides.
Also see:
What is the accepted style for using the this keyword in Java?
When should I use “this” in a class?
Using the this Keyword (Oracle Java Doc)
How do you test a default constructor in one class and then test it in a different class?
This is the code for the Person class which has the default constructor.
I'm not sure in the PersonTester class how to access this default constructor and how to test it - what I have so far for the second class is also below.
Any help will be muchly appreciated, thanks :)
class Person {
// Data Members
private String name; // The name of this person
private int age; // The age of this person
private char gender; // The gender of this person
// Default constructor
public Person() {
name = "Not Given";
age = 0;
gender = 'U';
}
// Constructs a new Person with passed name, age, and gender parameters.
public Person(String personName, int personAge, char personGender) {
name = personName;
age = personAge;
gender = personGender;
}
// Returns the age of this person.
public int getAge( ) {
return age;
}
// Returns the gender of this person.
public char getGender( ) {
return gender;
}
// Returns the name of this person.
public String getName( ) {
return name;
}
// Sets the age of this person.
public void setAge( int personAge ) {
age = personAge;
}
// Sets the gender of this person.
public void setGender( char personGender ) {
gender = personGender;
}
// Sets the name of this person.
public void setName( String personName ) {
name = personName;
}
} // end class
import java.util.Scanner;
public class PersonTester {
// Main method
public static void main(String[] args){
// TEST THE DEFAULT CONSTRUCTOR FIRSTLY.
// Create an instance of the Person class.
Person person1 = new Person();
Scanner input = new Scanner(System.in);
// Get the values from user for first instance of Person class.
System.out.println("Person 1 Name: ");
person1.setName(input.nextLine());
System.out.println("Person 1 Age: ");
person1.setAge(input.nextInt());
System.out.println("Person 1 Gender: ");
person1.setGender(input.next().charAt(0););
// Alternatively assign values to the Person class.
// person1.setName("Not Given");
// person1.setAge(0);
// person1.setGender("U");
}
}
Your test would look like:
#Test
public void testDefaultConsturctor(){
Person person = new Person();
Assert.assertEquals(person.getName(),"Not Given");
Assert.assertEquals(person.getAge(),0);
Assert.assertEquals(person.getGender(),'U');
}
You can test default constructor in the second class without using asserts with this code
Person defaultPerson = new Person();
System.out.print("My default name is: " + defaultPerson.getName());
System.out.print("My default age is: " + defaultPerson.getAge());
System.out.print("My default gender is: " + defaultPerson.getGender());
By the way, I don´t know what´s the problem, because you are calling default constructor in your second class (PersonTester)
can some one please help me am having a compilation error with the last part of this code
its saying create constructor please help
public class Officer {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the Soldier: ");
String name = input.nextLine();
System.out.print("Enter the sex of the Soldier: ");
String sex = input.nextLine();
System.out.print("Enter the Age of the Soldier: ");
String age = input.nextLine();
Soldier soldier = new Soldier(name, sex, age);
}
}
package officer;
public class Soldier {
private String soldierName;
private int soldierAge;
private char soldierSex;
public void Soldier( String name, char sex, int age) {
soldierName = name;
soldierSex = sex;
soldierAge = age;
}
public String getSoldierName() {
return soldierName;
}
public char getSoldierSex() {
return soldierSex;
}
public int getSoldierAge() {
return soldierAge;
}
}
The class Soldier needs to define a matching constructor
public Soldier (String name, String sex, String age) {
// do stuff
}
This is the method that what be executed, when you call new Soldier(name, sex, age)
It ok, except:
sex should be en enum type
age should be an integer (or float) type
you should validate user input
An SEX enum:
public enum SEX {
MALE, FEMALE
}
A constructor:
public Soldier (String name, SEX sex, int age) {
}
You would need something like:
public class Soldier {
public Soldier(String name, String sex, int age) {
}
}
edit: with the new info provided you should delete the void in the public void Soldier since void would mean public void Soldier is a method of class Soldier while it's supposed to be the constructor.