I'm trying to learn the array object in Java but don't understand. I did understand how to store input into an array object but fail to understand how to compare each items inside an array to do #7 and #8. I tried to search up on the internet but stuck from there.
Create a class Student with following attributes: Name, Age, Address, Email address
Create an empty constructor that initializes empty values to all the attributes.
Create a constructor that takes all the parameters and initializes all the attributes with it.
Create accessor and mutator methods for all attributes.
Create a toString method to return the details of the student.
Ask the user to enter the details of any 5 students and store them in an array.
Ask the user to enter an address and print all the students who live in that address.
Print all the students whose email address contains “gmail.com”.
import java.util.*;
public class Student{
private String name;
private int age;
private String address;
private String email;
public Student(){}
public Student(String name, int age, String address, String email){
this.name = name;
this.age = age;
this.address = address;
this.email = email;
}
public void setName(String newName){
name = newName;
}
public void setAge(int newAge){
age = newAge;
}
public void setAddress(String newAddress){
address = newAddress;
}
public void setEmail(String newEmail){
email = newEmail;
}
public String getName(){
return name;
}
public int getAge(){
return age;
}
public String getAddress(){
return address;
}
public String getEmail(){
return email;
}
public String toString() {
return "Name: " + name + ", Age: " + age + ", Address: " + address + ", Email: " + email;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Student[] s= new Student[];5
for(int i = 0; i < 5; i++){
System.out.print("Name: ");
String name = sc.nextLine();
System.out.print("Age: ");
int age = sc.nextInt();
System.out.print("Address: ");
sc.nextLine();
String address = sc.nextLine();
System.out.print("Email: ");
String email = sc.nextLine();
s[i] = new Student(name,age,address,email);
}
for(int i = 0; i < s.size(); i++){
if(s)
}
System.out.println(Arrays.toString(s));
}
}
For 7, use the scanner to retrieve a string from the user, then compare it to each user's address
System.out.print("Please enter an address: ");
String anyAddress = sc.nextLine();
for (int i = 0; i < s.length; i++) {
if (s[i].getAddress().equals(anyAddress))
System.out.println(s[i]);
}
For 8, it's quite the same, iterate on the student (I show there a for-each loop), then verify if "gmail.com"is in their email, if true, then print it
for (Student student : s) {
if (student.getEmail().contains("gmail.com"))
System.out.println(student);
}
Related
I have a class Student with 3 attributes,
public static class Student {
public String firstname;
public String lastname;
public int studentnumber;
}
that I want to initialize in an array in a suitable loop in an external class. The attributes of each student are to be initialized using user input (for that I have a Terminal class):
public class main {
public static void main(String[] args) {
int numberofstudents = Terminal.askInt("How many students to you want to enter? ");
Student[] array = new Student[numberofstudents];
for (int i = 0; i < numberofstudents; i++) {
array[i].firstname = Terminal.askString("Enter student's firstname ");
array[i].lastname = Terminal.askString("Enter student's lastname ");
array[i].studentnumbere = Terminal.askString("Enter student's number ");
}
}
}
But every time I initialize a value of the Array,
array[i].firstname = Terminal.askString("Student's firstname ");
I get the
Exception in thread "main" java.lang.NullPointerException
You need to initialize the array index with a new Student() before you can update the value at this array index. By default, Student[] contains null at each index and therefore you will get NullPointerException if you try to perform any operation (e.g. assigning a value to array[i].firstname) on it without initializing it will a non-null value.
for(int i = 0;i<numberofstudents;i++){
array[i] = new Student();
array[i].firstname = Terminal.askString("Enter student's firstname ");
array[i].lastname = Terminal.askString("Enter student's lastname ");
array[i].studentnumbere = Terminal.askString("Enter student's number ");
}
Your Student array is empty! It has a length of your input, but has no student objects in it.
Create a new Student, and add it to the list first!
for(int i = 0;i<numberofstudents;i++) {
array[i] = new Student();
array[i].firstname = Terminal.askString("Enter student's firstname ");
// ...
}
You need to initialize each items of an array with new Student();
It's better to have a normal Student class (NOT static one). It seems that you want to hold total student count number so you can only have that variable as a static attribute (private static int studentNumber), and whenever you create a new instance of Student just ++ the value of studentNumber. In this case you don't need to get students number each time.
And it's better to have private attributes and access them via getters and setters rather than public attributes.
public class Student {
private static int studentNumber = 0;
private String firstName;
private String lastName;
private Long studentId;
public Student(String firstName, String lastName, Long studentId) {
this.firstName = firstName;
this.lastName = lastName;
this.studentId = studentId;
studentNumber++; // increase students count after each initialization
}
public static int getStudentNumber() {
return studentNumber;
}
public static void setStudentNumber(int studentNumber) {
Student.studentNumber = studentNumber;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
}
In your Main class, you need to initialize each items of an array with new Student();
public class Main {
public static void main(String[] args) {
int numberOfStudents = Terminal.askInt("How many students to you want to enter? ");
// this line just create an empty array that can hold Student objcets in it
Student[] array = new Student[numberOfStudents];
for (int i = 0; i < array.length; i++) {
// you need to initialize each items of an array with new()
array[i] = new Student(Terminal.askString("Enter student's firstname "),
Terminal.askString("Enter student's lastname "),
Terminal.askString("Enter student's ID "));
}
}
}
Don't forget to follow indentation rules, and start all classes name with Uppercase (Main, Student, Terminal, etc.). Finally use camel-case (studentNumbers, firstName, lastName).
You can add a constructor with three fields to the Student class and simplify your code as follows:
public static class Student {
public String firstname;
public String lastname;
public int studentNumber;
public Student(String firstname, String lastname, int studentNumber) {
this.firstname = firstname;
this.lastname = lastname;
this.studentNumber = studentNumber;
}
}
public static void main(String[] args) {
int numberOfStudents =
Terminal.askInt("How many students to you want to enter? ");
Student[] array = new Student[numberOfStudents];
for (int i = 0; i < numberOfStudents; i++) {
array[i] = new Student(
Terminal.askString("Enter student's firstname "),
Terminal.askString("Enter student's lastname "),
Terminal.askString("Enter student's number "));
}
}
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
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 =).
first of all sorry for my english it is not perfect.
I got a little problem (for me a huge problem) in java.
package test;
import java.util.Scanner;
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public void setadress(String adress)
{
this.adress = adress;
}
public String getadress()
{
return adress;
}
public void setcity(String city)
{
this.city = city;
}
public String getcity()
{
return city;
}
public void setpostcode(int postcode)
{
this.postcode = postcode;
}
public int getpostcode()
{
return postcode;
}
public void output (String adress, String city, int postcode) {
Scanner a = new Scanner (System.in);
System.out.println("How much values?");
int b = a.nextInt();
int [] c = new int [b];
for (int i=0; i<c.length; i++) {
Scanner input = new Scanner (System.in);
System.out.println("Adress?");
String temp = input.nextLine();
setadresse(temp);
Scanner input3 = new Scanner (System.in);
System.out.println("City?");
String temp2 = input3.nextLine();
setcity(temp2);
Scanner input4 = new Scanner (System.in);
System.out.println("Postcode?");
int temp3 = input4.nextInt();
setpostcode(temp3);
this.adress = adress;
this.city = city;
this.postcode = postcode;
System.out.println("Adress: "+adress+"City"+city+"postcode"+postcode);
}
}
}
Now, i want to save the values in a new class in a array
package test;
public class save {
adress [] saver = new adress[10];
public adressenpool (String adress, String city, int postcode){
for(int i =0; i<10;i++)
saver[i] = ????? ; //i have tried several things here, but it will not work. i know it is just a little problem but i can't get it the mistake
}
}
}
How can i get the values from address class an copy it as an array in the saver class?
It looks like you are attempting to put 10 objects of class address in an object of class save, as opposed to just the information within address. This is generally a good idea so I encourage you to continue.
In order to create the address within method adressenpool you need to use its constructor. At present class address only had a default constructor, which creates an effectively empty address. I would add a new constructor that fully creates the object
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public adress(String adress, String city, int postcode, String ergebnis){
this.adress=address;
this.city=city;
this.postcode=postcode;
this.ergebnis=ergebnis;
}
//you can have several constructors so you can keep the empty constructor if you want to set the elements piece by piece
public adress(){
}
......
other methods as before
}
Having added the constructor you can now make addresses easily
public adressenpool (String adress, String city, int postcode,String ergebnis){
saver[0] = new adress(adress, city, postcode,ergebnis);
}
However, your method adressenpool only contains enough information to create 1 adress. You may wish to set which index to save it at. Or you may want to change from an array to an arraylist so you can just add new adress as you go.
public adressenpool (String adress, String city, int postcode,String ergebnis, int index){
saver[index] = new adress(adress, city, postcode,ergebnis);
}
Notes
Classes always start with an uppercase letter. Objects with
lowercase. So it should be class Save and class Address
For loops (and if statements) without braces are considered a dangerous thing to do. Always include {} with your loops even if it contains a single statement. So
for(int i =0; i<10;i++){
saver[i] new Adress(adress, city, postcode,ergebnis);
}
I think you should be more specific of what you want to do exactly.
Your first class has 4 members (3 String and 1 int) and you want to save the values from address class as an array in the saver class? What do you mean by the last one?
I am guessing you need to fill each address instance in the array you define (saver) by calling the appropriate setters. (You haven't defined setadresse() by the way). This can be done in a loop for example.
Also this is not very straight forward: //i have tried several things here, but it will not work. What have you tried and did not work?
Of course you need a main() function also to run your program.
I hope that helped a bit...
This will solve the issue
package temp;
import java.util.Scanner;
public class adress {
String adress;
String city;
int postcode;
String ergebnis;
public void setadress(String adress)
{
this.adress = adress;
}
public String getadress()
{
return adress;
}
public void setcity(String city)
{
this.city = city;
}
public String getcity()
{
return city;
}
public void setpostcode(int postcode)
{
this.postcode = postcode;
}
public int getpostcode()
{
return postcode;
}
public void setAddress () {
Scanner input = new Scanner (System.in);
System.out.println("Adress?");
String temp = input.nextLine();
setadress(temp);
Scanner input3 = new Scanner (System.in);
System.out.println("City?");
String temp2 = input3.nextLine();
setcity(temp2);
Scanner input4 = new Scanner (System.in);
System.out.println("Postcode?");
int temp3 = input4.nextInt();
setpostcode(temp3);
}
#Override
public String toString() {
// TODO Auto-generated method stub
return "Adress: "+adress+"City"+city+"postcode"+postcode;
}
}
And the second class
package temp;
import java.util.Scanner;
public class save {
adress [] saver;
public save(){
saver = new adress[10];
}
public void adressenpool(){
Scanner a = new Scanner (System.in);
System.out.println("How much values?");
int b = a.nextInt();
adress address1 = null;
for (int i=0; i<b; i++) {
address1 = new adress();
address1.setAddress();
this.saver[i] = address1;
}
}
public static void main(String[] args) {
save saveTemp = new save();
saveTemp.adressenpool();
for(int i=0; i<2; i++){
System.out.println(saveTemp.saver[i].toString());
}
}
}
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.