Calling methods from different classes | Java - java

I'm writing code for an application that keeps track of a student’s food purchases at a campus cafeteria. There's two classes - Student, which holds overloaded constructors & appropriate getter & setter methods; and MealCard, which holds a class variable to track the number of meal cards issued, appropriate getter & setter methods, a purchaseItem() method, a purchasePoints() method & an overriddden toString() method. There's a Tester class also.
In my MealCard class, the methods are written but in the Tester when I call them, they don't work correctly. I want to get the itemValue from the user but how do I do this in the MealCard class?
Same goes for the purchasePoints method, how do I get the topUpValue from user in MealCard class?
Code so far is:
public class Student {
// Instance Variables
private String name;
private int age;
private String address;
// Default Constructor
public Student() {
this("Not Given", 0, "Not Given");
}
// Parameterized constructor that takes in values
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress(){
return address;
}
public void setAddress(String address) {
this.address = address;
}
// toString() to be overriden
#Override
public String toString() {
return "Name: " + this.name + "\n" + "Age: " + this.age + "\n" + "Address: " + this.address;
}
}
`
public class MealCard extends Student {
static int numberOfMealCards;
private final static int DEFAULT_BALANCE = 1000;
private int itemValue;
private int topUpValue;
public int newBalance;
// Getters and Setters
public int getItemValue() {
return itemValue;
}
public void setItemValue(int itemValue) {
this.itemValue = itemValue;
}
public int getTopUpValue() {
return topUpValue;
}
public void setTopUpValue(int topUpValue) {
this.topUpValue = topUpValue;
}
// purchaseItem method for when students buy food
public int purchaseItem() {
newBalance = DEFAULT_BALANCE - itemValue;
return newBalance;
}
// purchasePoints method for students topping up their meal card balance
public int purchasePoints() {
newBalance = DEFAULT_BALANCE + topUpValue;
return newBalance;
}
// Overriden toString method
#Override
public String toString() {
return super.toString() + "Meal Card Balance: " + this.newBalance + "\n" + "Number of Meal Cards: " + numberOfMealCards;
}
}
`
import java.util.Scanner;
public class TestMealCard {
public static void main(String[] args) {
// Create instances of MealCard class
MealCard student1 = new MealCard();
MealCard student2 = new MealCard();
Scanner keyboard = new Scanner(System.in);
System.out.println("Name: ");
student1.setName(keyboard.nextLine());
System.out.println("Age: ");
student1.setAge(keyboard.nextInt());
System.out.println("Address: ");
student1.setAddress(keyboard.nextLine());
System.out.println("Meal Card Balace: ");
student1.newBalance = keyboard.nextInt();
System.out.println("Number of Meal Cards Issued: ");
student1.numberOfMealCards = keyboard.nextInt();
System.out.println("Name: ");
student2.setName(keyboard.nextLine());
System.out.println("Age: ");
student2.setAge(keyboard.nextInt());
System.out.println("Address: ");
student2.setAddress(keyboard.nextLine());
System.out.println("Meal Card Balace: ");
student2.newBalance = keyboard.nextInt();
System.out.println("Number of Meal Cards Issued: ");
student2.numberOfMealCards = keyboard.nextInt();
// Call purchaseItem
student1.purchaseItem();
// Call purchasePoints
student2.purchasePoints();
// Call tString to output information to user
}
}

In order to set the itemValue from the user you need to get get that input from the user using this setItemValue() method.
Ex.
System.out.print("Please enter the item value: ");
student1.setItemValue(keyboard.nextInt());
or
int itemVal = 0;
System.out.print("Please enter the item value: ");
itemVal = keyboard.nextInt();
student1.setItemValue(itemVal);
as for the other method call just call the setter for toUpValue.
Ex.
System.out.print("Please enter the item value: ");
student1.setTopUpValue(keyboard.nextInt());
or
int toUpVal = 0;
System.out.print("Please enter the item value: ");
itemVal = keyboard.nextInt();
student1.setTopUpValue(topUpVal);
Hope that helps =).

Related

How do I assign object from one class to another class and how do I calculate double and int inside an ArrayList?

I have an assignment but i have problem trying to do some part of it. Appreciate if anyone can give me a hand.
Assignment brief: https://pastebin.com/3PiqvfTE
Main Method: https://pastebin.com/J2kFzB3B
import java.util.ArrayList;
import java.util.Scanner;
public class mainMethod {
public static void main(String[] args) {
//scanner
Scanner scanner = new Scanner (System.in);
//subject object
Subject subject = new Subject (0,null,0);
System.out.println("How many subject do you want to enter: ");
int subjectNumber = scanner.nextInt();
for (int j = 0; j < subjectNumber; j++) {
//subject ID
System.out.println("Please enter the subject ID: ");
int subID = scanner.nextInt();
//subject Name
System.out.println("Please enter subject name: ");
String subName = scanner.next();
//subject fee
System.out.println("Please enter subject fee: ");
double subFee = scanner.nextDouble();
//add subject
subject.addSubject(subID, subName, subFee);
}
//display subject
System.out.println(subject.getSubject());
/*
//loop for part time teacher
System.out.println("Please enter how many part time teacher do you have: ");
int PTcounter = scanner.nextInt();
for (int i = 0; i < PTcounter; i++) {
*/
Teacher teach = new Teacher (0,null,null);
//teacher employee ID
System.out.println ("Please enter the teacher employee ID: ");
int tid = scanner.nextInt();
//teacher name
System.out.println("Please enter the teacher name: ");
String tname = scanner.next();
//teacher gender
System.out.println("Please enter the teacher gender: ");
String tgender = scanner.next();
//add teacher details
teach.addTeacher(tid, tname, tgender);
//display teacher details
System.out.println(teach.getTeacher());
//call address class
Address address = new Address (0,null,null,0);
//address house number
System.out.println("Please enter house number: ");
int addyNum = scanner.nextInt();
//address street name
System.out.println("Please enter street name: ");
String StreetName = scanner.next();
//address city
System.out.println("Please enter city: ");
String City = scanner.next();
//address post code
System.out.println("Please enter postcode: ");
int Postcode = scanner.nextInt();
//add address
address.addAddress(addyNum, StreetName, City, Postcode);
//display address
System.out.println(address.getAddress());
//call Part Time Salary class
PartTimeSalary ptSalary = new PartTimeSalary(0,0);
//max hours
System.out.println("Please enter maximum work hours: ");
int maxHours = scanner.nextInt();
//hourly rate
System.out.println("Please enter hourly rate: ");
double hourlyRate = scanner.nextDouble();
ptSalary.addPTSalary(maxHours, hourlyRate);
System.out.println(ptSalary.getHourlyRate());
//System.out.printf("Teacher details is %s, Subject details is %s, Address is %s", teach.toString(),subject.toString(),address.toString());
}
}
1st problem. I have a subject class and a teacher class. Teacher will be able to teach maximum of 4 subject. I have prompt user to enter subject details before entering teacher details, so when user enter teacher details they will be able to assign subject to teacher just by using the subjectID. I have problem implementing this. My subject is already store in an ArrayList but how to I connect this with teacher. And in the end the program will display what subject each teacher teaches.
Subject Class: https://pastebin.com/iBYFqYDN
import java.util.ArrayList;
import java.util.Arrays;
public class Subject {
private int subjectID;
private String subjectName;
private double fee;
private ArrayList <Subject> subjectList = new ArrayList <Subject>();
public Subject(int subjectID, String subjectName, double fee) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
}
public int getSubjectID () {
return subjectID;
}
public void setSubjectID (int subjectID) {
this.subjectID = subjectID;
}
public String getSubjectName () {
return subjectName;
}
public void setSubjectName (String subjectName) {
this.subjectName = subjectName;
}
public double getFee () {
return fee;
}
public void setFee (double fee) {
this.fee = fee;
}
#Override
public String toString() {
return "[subjectID=" + subjectID + ", subjectName=" + subjectName + ", fee=" + fee + "]";
}
public void addSubject (int subjectID, String subjectName, double fee) {
subjectList.add(new Subject(subjectID, subjectName, fee) );
}
public String getSubject () {
return Arrays.toString(subjectList.toArray());
}
}
Teacher class: https://pastebin.com/Np7xUry2
import java.util.ArrayList;
import java.util.Arrays;
public class Teacher {
private int employeeID;
private String name;
private String gender;
private ArrayList <Teacher> teacherDetailsList;
public Teacher (int employeeID, String name, String gender) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.teacherDetailsList = new ArrayList <Teacher>();
}
public int getEmployeeID () {
return employeeID;
}
public void setEmployeeID (int employeeID) {
this.employeeID = employeeID;
}
public String getName () {
return name;
}
public void setName (String name) {
this.name = name;
}
public String getGender () {
return gender;
}
public void setGender (String gender) {
this.gender = gender;
}
#Override
public String toString() {
return "[employeeID=" + employeeID + ", name=" + name + ", gender=" + gender + "]";
}
public void addTeacher (int employeeID, String name, String gender) {
teacherDetailsList.add(new Teacher (employeeID,name,gender));
}
public String getTeacher () {
return Arrays.toString(teacherDetailsList.toArray());
}
}
2nd problem. Teacher will either be part time or full time teacher. Part time teacher will have a maximum work hour they can work and an hourly rate they will be paid for, so the final salary of part time teacher will be "maximum hours" multiply by "hourly rate". I have store "hourly rate" and "maximum work hours" in an ArrayList but how do I call them to make the multiplication then displaying at the end.
Part time salary class: https://pastebin.com/iGKpu87Y
import java.util.ArrayList;
public class PartTimeSalary {
private int maxHour;
private double hourlyRate;
private double hourlySalary;
private ArrayList <PartTimeSalary> PTSalary = new ArrayList <PartTimeSalary>();
private ArrayList <Double> finalHourlySalary = new ArrayList <Double>();
public PartTimeSalary (int maxHour, double hourlyRate) {
this.maxHour = maxHour;
this.hourlyRate = hourlyRate;
}
public int getMaxHours () {
return maxHour;
}
public void setMaxHour (int maxHour) {
this.maxHour = maxHour;
}
public double getHourlyRate () {
return hourlyRate;
}
public void setHourlyRate (double hourlyRate) {
this.hourlyRate = hourlyRate;
}
public double getHourlySalary() {
hourlySalary = hourlyRate*maxHour;
return hourlySalary;
}
public void addPTSalary (int maxHour, double hourlyRate) {
PTSalary.add(new PartTimeSalary(maxHour,hourlyRate));
}
public void FinalHourlySalary (double hourlySalary) {
hourlySalary = hourlyRate * maxHour;
finalHourlySalary.add(hourlySalary);
}
public ArrayList<Double> getFinalSalary () {
return (new ArrayList <Double>());
}
}
3rd question. I have an address class which is suppose to be part of the Teacher class. I can't seem to connect the address class with teacher class.
Address class: https://pastebin.com/s2HN5p80
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Address {
private int houseNum;
private String streetName;
private String city;
private int postcode;
private List <Address> address = new ArrayList <Address>();
public Address (int houseNum, String streetName, String city, int postcode) {
this.houseNum = houseNum;
this.streetName = streetName;
this.city = city;
this.postcode = postcode;
}
public int getHouseNum() {
return houseNum;
}
public void setHouseNum (int houseNum) {
this.houseNum = houseNum;
}
public String getStreetName() {
return streetName;
}
public void setStreetName (String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity (String city) {
this.city = city;
}
public int getPostcode() {
return postcode;
}
public void setPostcode (int postcode) {
this.postcode = postcode;
}
public void addAddress (int houseNum, String streetName, String city, int postcode) {
address.add(new Address (houseNum,streetName,city,postcode));
}
#Override
public String toString() {
return "[houseNum=" + houseNum + ", streetName=" + streetName + ", city=" + city + ", postcode="
+ postcode + "]";
}
public String getAddress () {
return Arrays.toString(address.toArray());
}
}
Thank you 😃😊
Question 1)
Put the "teacherDetailsList" and "subjectList" ArrayLists in the main method, not the consructors. Add the teachers and subjects in main methods, not constructors.
Add a new ArrayList called "mySubjects" as a field for the Teacher Class
Add the following 2 method to the Teacher class:
public Teacher (int employeeID, String name, String gender, ArrayList<Subject> s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects=s;
}
public Teacher (int employeeID, String name, String gender, Subject s) {
this.employeeID = employeeID;
this.name = name;
this.gender = gender;
this.mySubjects.add(s);
}
public void addSubject(Subject s, boolean b){
if(mySubjects.size()<4)mySubjects.add(s);
else throw OutOfBoundsError;
}
public void removeSubject(Subject s, boolean b){
mySubject.remove(s);
}
public void addSubject(Subject s){
s.changeTeacher(s);
}
public void removeSubject(Subject s){
mySubject.remove(s);
}
Add the following methods & fields to Student class
private Teacher teacher;
public Subject(int subjectID, String subjectName, double fee, Teacher t) {
this.subjectID = subjectID;
this.subjectName = subjectName;
this.fee = fee;
this.setTeacher(t);
}
public void setTeacher(Teacher t){
try{
t.addSubject(this);
teacher=t;
}
catch(OutOfBoundsError e){
System.out.println(t.getName()+" already has a full schedule.");
}
}
public void changeTeacher(Teacher t){
teacher.removeSubject(this);
teacher = t;
t.addSubject(this);
}
Question 2)
make a new double field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called maxHour in the class Subject
add a double field to the teacher class called salary. If the teacher is part-time, set this to 0 in the constructor.
add this method to Teacher class:
public double getSalary(){
if(salary!=0) return salary;
double s=0;
for(Subject i: mySubjects) s+=i.getFee()*i.getMaxHours();
return s;
}
You honestly no longer need the PartTimeSalary class now.
Question 3
make a new Address field, constructor parameter (for every constructor in the class), mutator method and accessor mutator called myAddress in the class Teacher
Don't bother with the ArrayList stuff in your Address Class

How can I find a problem in my Java code?

I'm trying to do homework for my IT classes and we just started programming a bit. We have 2 classes, Main and Okej. It is just a simple code where the getters and setters have to check if the user input the right number. But the IF statements just do not work.
package okej;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner program = new Scanner(System.in);
System.out.println("Please, type your Name.");
String name = program.nextLine();
System.out.println("Please, type your age.");
int age = program.nextInt();
System.out.println("Please, type your weight.");
double weight = program.nextDouble();
Okej you = new Okej(name, age, weight);
System.out.print(you);
}
}
package okej;
import java.util.Scanner;
public class Okej {
String name = "";
int age = 0;
double weight = 0.0;
public Okej(String name, int age, double weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
System.out.println("Okay, your name is " + name + ".");
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 18) {
if (age < 99) {
this.age = age;
System.out.println("Okay, your age is " + age + ".");
}
}
else {
System.out.println("You have put an invalid age for this program.");
System.out.println("Setting the number to 20.");
this.age = 20;
}
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
if (weight > 30) {
if (weight < 300) {
this.weight = weight;
System.out.println("Okay, your weight is " + weight + ".");
}
}
else {
System.out.println("You have put an invalid weight for this program.");
System.out.println("Setting the number to 50.");
this.weight = 50;
}
}
#Override
public String toString() {
return "Okay, your name is " + name + ", your age is " + age + ", and you weight "+ weight +".";
}
}
It is not working because logic which validates your inputs are inside setters and you are not calling it. You are creating your object through constructor which doesn't execute any validation. You can do one of following:
move validation codes to static method and call it in constructor to validate before assigning values
use builders with validation code inside
create empty object (with default constructor) and use setters to set values which will trigger your validation
...

How do I get a string user input and increase value by +1 using Java ArrayList?

I have the following code and I want to ask the user after an name that's already stored in the Arraylist and increase that (dogs) age by +1.
Here's the most important (I guess) part of the code. This is the Register Class.
import java.util.Scanner;
import java.util.ArrayList;
public class Register {
private Scanner keyboard = new Scanner(System.in);
private ArrayList<Dog> dogs = new ArrayList<>();
private String readString() {
return keyboard.nextLine();
}
public int readInt() {
int i = keyboard.nextInt();
keyboard.nextLine();
return i;
}
public double readDouble() {
double d = keyboard.nextDouble();
keyboard.nextLine();
return d;
}
public void registrateDog(){
System.out.println("Dogs name: ");
String name = readString();
System.out.println("Dogs breed: ");
String breed = readString();
System.out.println("Dogs age: ");
int age = readInt();
System.out.println("Dogs weight: ");
double weight = readDouble();
Dog newDog = new Dog(name, breed, age, weight);
dogs.add(newDog);
System.out.println(newDog.toString() + " is added");
}
public void increaseAge(){ //Here's the problem
System.out.print("Enter dog who has aged: ");
String newDogAge = readString();
int addAge = 1;
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
addAge = (dogs.get(i).getAge());
dogs.set(i, dogs.get(i));
System.out.println("Dog " + newDogAge + " is now " + addAge);
return;
}
}
private void exitProgram(){
System.out.println("Goodbye!");
keyboard.close();
}
private void run(){
setUp();
runCommandLoop();
exitProgram();
}
public static void main(String[] args){
new Register().run();
//setUp();
}
}
And
public class Dog {
private String name;
private String breed;
private int age;
private double weight;
private double tailLenght;
private String tax = "tax";
public Dog(String name, String breed, int age, double weight){
this.name = name;
this.breed = breed;
this.age = age;
this.weight = weight;
if (breed.equals(tax)) {
this.tailLenght = 3.7;
} else {
this.tailLenght = (age*weight) / 10;
}
}
public String getName(){
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBreed(){
return breed;
}
public int getAge(){
return age;
}
public void setAge(int age){
this.age = age;
}
public int newAge(){
return age = age + 1;
}
public double getWeight(){
return weight;
}
public double getTailLenght(){
return tailLenght;
}
public String toString()
{ return String.format("%s, %s, %d years old, %.1f kg, "
+ "tail lenght %.1f cm", name, breed, age, weight, tailLenght);
}
}
So in this code you're finding the Dog by its name. Which is great.
public void increaseAge() {
System.out.print("Enter dog who has aged: ");
String newDogAge = readString();
int addAge = 1;
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
addAge = (dogs.get(i).getAge());
dogs.set(i, dogs.get(i));
System.out.println("Dog " + newDogAge + " is now " + addAge);
return;
}
}
Inside of your Dog class you have a method which returns the age, what you want to do is modify it to:
public int newAge(){
this.age++; // This will take the current age of the dog and add one to it
}
Now going back to the increaseAge() method you want to modify the for loop to look like:
for (int i = 0; i < dogs.size(); i++) {
if(dogs.get(i).getName().equals(newDogAge))
dogs.get(i).newAge(); // This will update the Dogs age by 1 year
System.out.println("Dog " + dogs.get(i).getName() + " is now " + dogs.get(i).getAge());
return;
}
Where are you incrementing the age ? Call the newAge() method as you have defined in the Dog class.`
Dog dog = dogs.get(i);
dog.setAge(dog.newAge());
dogs.set(i,dog);`
We've fetched the particular dog who's details matched. Then we incremented it's age and set it back in the list at that position.

Why is my program returning null,null,0 ,0?

My program is supposed to store the info submitted by the users into another class. It is then supposed to perform a small calculation to determine age. The final part is to create an instance of the secondary class in the Driver and then print out all the info using toString. My results are null, null, 0 ,0 everytime. What am I doing wrong?
public class CustomerInfoProgram {
public static Scanner scan = new Scanner(System.in);
public static String firstName;
public static String lastName;
public static String address;
public static String phoneNumber;
public static int dob;
public static int currentYear;
public static int age;
public static String name;
public static void main(String[] args) {
Customer in = new Customer();
getCustomerName();
getPhone();
getAddress();
getDOB();
getCurrentYear();
in.toString();
}
public static String getCustomerName() {
System.out.println("What is your first name?");
firstName = scan.nextLine();
System.out.println("What is your last name?");
lastName = scan.nextLine();
name = firstName + " " + lastName;
return name;
}
public static String getAddress() {
System.out.println("What is your address?");
address = scan.nextLine();
return address;
}
public static String getPhone() {
System.out.println("What is your phone number?");
phoneNumber = scan.nextLine();
return phoneNumber;
}
public static int getDOB() {
System.out.println("What year were you born?");
dob = scan.nextInt();
return dob;
}
public static int getCurrentYear() {
System.out.println("What is the current year?");
currentYear = scan.nextInt();
return currentYear;
}
}
Secondary class:
import java.util.Scanner;
public class Customer {
public static int age;
public static String allInfo;
public static String name = CustomerInfoProgram.name;
public static String address = CustomerInfoProgram.address;
public static String phoneNumber = CustomerInfoProgram.phoneNumber;
public static int dob = CustomerInfoProgram.dob;
public static int currentYear = CustomerInfoProgram.currentYear;
private int getAge() {
age = (currentYear - dob);
return age;
}
public String toString() {
getAge();
allInfo = (name + " " + address + " " + phoneNumber + " " + dob + " " + age);
System.out.println(allInfo);
return toString();
}
}
public static String name = CustomerInfoProgram.name;
This only sets the value of CustomerInfoProgram.name when the field is initialized, i.e. once, when the Customer class is loaded - it does not update when CustomerInfoProgram.name is updated.
The Customer class is (at the latest) loaded when you call new Customer(), which happens before you run any methods to set the value of CustomerInfoProgram.name, so it is null when you attempt to use name.
If you want to use the current value of CustomerInfoProgram.name, just refer to that field directly. Alternatively, you can add a getter, which will return its current value:
public static String getName() {
return CustomerInfoProgram.name;
}
then call the getter in place of name:
allInfo = (getName() + " " + ...
(Exactly the same applies to the other fields).
You also will get a StackOverflowError from you toString() method:
public String toString() {
getAge();
allInfo = (name + " " + address + " " + phoneNumber + " " + dob + " " + age);
System.out.println(allInfo);
return toString();
}
You are unconditionally calling toString() inside toString(), so this will just keep calling itself until it runs out of stack space.
Instead, just return allInfo:
public String toString() {
getAge(); // This actually does nothing - do you intend to use it in the return value?
return (name + " " + address + " " + phoneNumber + " " + dob + " " + age);
}
and call System.out.println in your main method:
System.out.println(in); // Implicitly calls toString().
See #Andy's answer for the cause of your problem.
The usual approach to this would be to collect the values to be stored in your Customer object before you create it, then use a nondefault constructor call. A partial example might look like this:
// get individual values here
getCustomerName();
getPhone();
// etcetera
Customer in = new Customer(name, phone, address, dob);
The rest I leave as an exercise for the reader.
Being static attributes the initialization in both the classes would be only once. So post you get the input from user those values are not set to the attributes. Hence the null.

two person object

import cs1.Keyboard;
import java.util.Scanner;
class Person
{
private String name;
private String persnr;
private String adress;
private int age;
public Person(String _name, String _persnr, String _adress, int _age)
{
name = name;
persnr = persnr;
adress = adress;
age = age;
}
public void byterNamn(String _name)
{
name = _name;
}
public void byterAdress(String _adress)
{
adress = _adress;
}
public void fyllerAr()
{
age = age + 1;
}
public String hamtaNamn()
{
return name;
}
public String hamtaPersonnmmer()
{
return persnr;
}
public String hamtaAdress()
{
return adress;
}
public int hamtaAlder()
{
return age;
}
public String toString()
{
String _toString;
_toString = "Namn: " + name + "\nÅlder: " + age;
_toString = _toString + "\nPersonnummer: " + persnr + "\nAdress: " + adress;
return _toString;
}
public p1()
{
System.out.print("namn: ");
name = Keyboard.readString();
System.out.print( "adress: " );
String adress = Keyboard.readString();
System.out.print( "ålder: " );
Integer age = new Integer();
age.parseInt(Keyboard.readint());
System.out.print( "personnummer: " );
String persnr = Keyboard.readString();
}
public p2()
{
System.out.print("namn: ");
name = Keyboard.readString();
System.out.print( "adress: " );
String adress = Keyboard.readString();
System.out.print( "ålder: " );
Integer age = new Integer();
age.parseInt(Keyboard.readint());
System.out.print( "personnummer: " );
String persnr = Keyboard.readString();
}
public static void main(String[] args)
{
String name = Keyboard.readString();
String persnr = Keyboard.readString();
String adress = Keyboard.readString();
int age = Keyboard.readint();
Person p1 = new Person(name, age, adress, personnummer);
String name = Keyboard.readString();
String persnr = Keyboard.readString();
String adress = Keyboard.readString();
int age = Keyboard.readint();
Person p2 = new Person(name, age, adress, personnummer);
}
}
hello.
I try to do so it is 2 people. where you should enter the age, name, address of both people and then print it after you enter what you want when the program runs. and i wondering how do i do return on public p1() and public p2() so i can do it. Or is it a easier way to do it?
This code does not compile. public p1() and public p2() are not valid method declarations. You must at least add a method return type after the public and before the method name, for example:
public Person p1()
Then I guess what you want to do is return a Person object from each of those two methods. Inside the method you must create a new Person object and then return it from the method:
return new Person(name, persnr, adress, age);
See Defining Methods and Returning a Value from a Method in Oracle's Java Tutorials.

Categories

Resources