Scanner issue, input information not working - java

the question, I look at the code millions of times, may be I just can't see the simple answer but why at the point of Author name and Author Surname, system print out like this:
Enter author Name: Enter author Surname:
and it should be like this...
Enter author Name:
Enter author Surname:
and if I input information in system remember only Author first name and I can't put information for surname.
import java.util.Scanner;
public class BookTest {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
Book bookIn = new Book();
System.out.print("Enter book title: ");
bookIn.setTitleBook(scan.nextLine());
System.out.print("Enter author Name: ");
bookIn.setFirstName(scan.nextLine());
System.out.print("Enter author Surname: ");
bookIn.setSecondName(scan.nextLine());
System.out.print("Enter author Nationality: ");
bookIn.setNationality(scan.nextLine());
System.out.print("Enter book price: ");
bookIn.setPriceBook(scan.nextDouble());
System.out.print("Enter book ISBN: ");
bookIn.setIsbn(scan.nextInt());
System.out.println("Title: " +bookIn.getTitleBook());
System.out.println("Author: "+ bookIn.getFirstName()+ " " + bookIn.getSecondName());
System.out.println("Price: "+bookIn.getPriceBook());
System.out.println("ISNB Number: "+bookIn.getIsbn());
System.out.println("Aurhor Nationality: " + bookIn.getNationality());
}
}
Book Class
public class Book {
private double priceBook;
private int isbn;
private String titleBook;
private String firstName;
private String secondName;
private String nationality;
public void setTitleBook(String titleBook){
this.titleBook = titleBook;
}
public String getTitleBook(){
return titleBook;
}
public void setPriceBook(double priceBook) {
this.priceBook = priceBook;
}
public double getPriceBook() {
return priceBook;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
public int getIsbn() {
return isbn;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public String getSecondName() {
return secondName;
}
public void setNationality(String nationality) {
this.nationality = nationality;
}
public String getNationality() {
return nationality;
}
}

Move the scanner to the next line after reading the ISBN. When using Scanner.nextInt the input only reads the number and not the new line character created when you press enter. Calling Scanner.nextLine after Scanner.nextInt reads the new line character and clears the buffer.
import java.util.Scanner;
public class BookTest {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
Book title = new Book();
Book price = new Book();
Book isbn = new Book();
Book fName = new Book();
Book sName = new Book();
Book nation = new Book();
System.out.print("Enter book title: ");
title.setTitleBook(scan.nextLine());
System.out.print("Enter book price: ");
price.setPriceBook(scan.nextDouble());
System.out.print("Enter book ISBN: ");
isbn.setIsbn(scan.nextInt());
scan.nextLine(); //NOTICE CHANGE HERE
//System.out.println(); THIS WAS REMOVED
System.out.print("Enter author Name: ");
fName.setFirstName(scan.nextLine());
System.out.print("Enter author Surname: ");
sName.setSecondName(scan.nextLine());
System.out.print("Enter author Nationality: ");
nation.setNationality(scan.nextLine());
System.out.println("Title: " +title.getTitleBook());
System.out.println("Price: "+price.getPriceBook());
System.out.println("ISNB Number: "+isbn.getIsbn());
System.out.println("Author: "+ fName.getFirstName() + sName.getSecondName());
System.out.println("Aurhor Nationality: " + nation.getNationality());
}
}

Related

How can i access the variable from different class method

This is the main file, im trying to print the result of the Age, Name, Birthdate, etc.
LabExercise1
package labexercise1;
/**
*
* #author user
*/
public class LabExercise1{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
NewClass newClass = new NewClass();
NewClass.getFirstName();
NewClass.getLastName();
NewClass.getAge();
NewClass.getBirthDate();
NewClass.getGWA();
// TODO code application logic here
System.out.println("My name is " + FirstName + "." + " I am " + Age + " years old and the day that i was born is on " + BirthDate + ". My general weighted average this semester is " + GWA + ".");
}
NewClass
package labexercise1;
import java.util.Scanner;
/**
*
* #author user
*/
public class NewClass {
public static void getFirstName(){
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter First Name: ");
String FirstName = myObj.nextLine(); // Read user input
}
public static void getLastName(){
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter Last Name: ");
String LastName = myObj.nextLine(); // Read user input
}
public static void getAge(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your age: ");
int Age = myObj.nextInt();
}
public static void getBirthDate(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your BirthDate: ");
String BirthDate = myObj.nextLine();
}
public static void getGWA(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your GWA: ");
float GWA = myObj.nextFloat();
}
}
A lot of this is basic Java 101, concepts and ideas which you should be building around "what is an object".
I would, highly, recommend taking the time to go through things like...
Declaring Member Variables
Defining Methods
Providing Constructors for Your Classes
Passing Information to a Method or a Constructor
Understanding Class Members
For example...
import java.text.ParseException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws ParseException {
new Main();
}
public Main() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter First Name: ");
String firstName = scanner.nextLine();
System.out.print("Enter Last Name: ");
String lastName = scanner.nextLine();
System.out.print("Enter Age: ");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter Birthdate: ");
String dateOfBirth = scanner.nextLine();
System.out.print("Enter GWA: ");
int gwa = scanner.nextInt();
scanner.nextLine();
Person person = new Person(firstName, lastName, age, dateOfBirth, gwa);
System.out.println("First name = " + person.getFirstName());
System.out.println("Last name = " + person.getLastName());
System.out.println("Age = " + person.getAge());
System.out.println("Date of birth = " + person.getDateOfBirth());
System.out.println("GWA = " + person.getGwa());
}
public class Person {
private String firstName;
private String lastName;
private int age;
private String dateOfBirth;
private int gwa;
public Person(String firstName, String lastName, int age, String dateOfBirth, int gwa) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.dateOfBirth = dateOfBirth;
this.gwa = gwa;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public int getGwa() {
return gwa;
}
}
}
Please keep in mind, Stack overflow is NOT a tutorial site/forum and you will, ultimately, be expected to make the effort to learn these basic concepts.

how to output the book's title, author, and show the bookID seperately?

I'm a new java learner. Now I need to set the bookID from 1000, and according to the total number of input IDs, book author, and book title, respectively show the book's information.
For example, when users enter 2, The Lord of the Rings; J. R. R. Tolkien; The Hunger Games; Suzanne Collins;
The output is Book ID: 1000 Title: The Lord of the Rings Author: J. R. R. Tolkien Status: Available Book ID: 1001 Title: The Hunger Games Author: Suzanne Collins Status: Available.
I have completed part of the programming, but now I do not how to write the code in the BOOK[] array.
code:
import java.util.Scanner;
class Book{
private Integer bookID = 1000;
static Integer nextID;
private String title;
private String author;
private boolean isBorrowed;
public Book(String title, String author){
this.title = title;
this.author = author;
this.isBorrowed = false;
this.nextID = bookID++;
}
public void borrowBook(){
isBorrowed = true;
}
public void returnBook(){
isBorrowed = false;
}
public boolean isBookBorrowed(){
return isBorrowed;
}
public void show() {
System.out.println("Book ID: " + bookID);
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.print("Status: ");
if (isBorrowed)
System.out.println("Not Available");
else
System.out.println("Available");
System.out.println();
}
}
public class MyClass {
public static void main(String args[]) {
Scanner input=new Scanner(System.in);
int num=input.nextInt();
input.nextLine();
Book[] books = new Book[num];
String title;
String author;
for (int i=0; i<num; i++) {
books[i] =input.nextBook();
title = input.nextLine();
author = input.nextLine();
}
}
}
The following is my programming code, please help me see how to write the code of the array part, thank you very much!
This is how it should be done:
nextId must be static because it's the one and only variable that has your last book id.
bookID should not be static because it's different for each book.
Book class:
class Book{
private static Integer nextID = 1000;
private Integer bookID;
private String title;
private String author;
private boolean isBorrowed;
public Book(String title, String author){
this.title = title;
this.author = author;
this.isBorrowed = false;
this.bookID = nextID++;
}
public void borrowBook(){
isBorrowed = true;
}
public void returnBook(){
isBorrowed = false;
}
public boolean isBookBorrowed(){
return isBorrowed;
}
public void show() {
System.out.println("Book ID: " + bookID);
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.print("Status: ");
if (isBorrowed)
System.out.println("Not Available");
else
System.out.println("Available");
System.out.println();
}
}
Main class:
import java.util.Scanner;
public class MyClass{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = input.nextInt();
input.nextLine();
Book[] books = new Book[num];
String title;
String author;
for (int i = 0; i < num; i++) {
title = input.nextLine();
author = input.nextLine();
books[i] = new Book(title,author);
}
for (int i = 0; i < num; i++) {
books[i].show();
}
}
}
The following code has a "database" of 2 books. The user is prompted to enter the book id as you stated, it starts with 1000. If the book is found they see your information via the show() method. If this isn't what you want let me know. OR if you want to add a feature that allows the user to input books we can do that too..
Please always give user prompts like "enter a number" when you use scanner.
I went ahead and added so that the user can enter a book and immediately see that the book was stored with the correct id. its alternate main below
import java.util.Scanner;
public class Book {
private static Integer nextID = 1000;
private Integer bookID;
private String title;
private String author;
private boolean isBorrowed;
public Book(String title, String author){
this.title = title;
this.author = author;
isBorrowed = false;
bookID = nextID++;
}
public void borrowBook(){
isBorrowed = true;
}
public void returnBook(){
isBorrowed = false;
}
public boolean isBookBorrowed(){
return isBorrowed;
}
public void show() {
System.out.println("Book ID: " + bookID);
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.print("Status: ");
if (isBorrowed)
System.out.println("Not Available");
else
System.out.println("Available\n");
}
public static void main(String[] args) {
// here we will create an array of 2 books as your data
Book books[] = new Book[2];
books[0] = new Book("blah", "blah bhal hald");
books[1] = new Book("java", "girl power");
Scanner input = new Scanner(System.in);
System.out.println("Enter the book id:");
int num = input.nextInt();
for (int i = 0; i < books.length; i++){
if (books[i].bookID == num){
books[i].show();
}
}
}
}
alternate main:
```public static void main(String[] args) {
// here we will allow the user to input book data and see the data
// returned with the new id.
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of books you wish to add:");
int num = input.nextInt();
input.nextLine();
Book[] books = new Book[num];
String title;
String author;
for (int i = 0; i < num; i++) {
System.out.println("enter the title:");
title = input.nextLine();
System.out.println("enter the author");
author = input.nextLine();
books[i] = new Book(title,author);
System.out.println("The book you entered is:");
books[i].show();
}
}

Why do I keep getting null instead of the output I want?

This assignment requires me to take in input and print it out. The first half of the output is printing currently, but the other half is giving me null. What's wrong here?
Heres my code:
This is the main class.
import java.util.*;
public class Assignment4 {
public static void main(String[] args) {
// local variables, can be accessed anywhere from the main method
char input1 = 'Z';
// String inputInfo= "";
String courseName, firstName, lastName, office, university;
String line = new String();
// instantiate a Course object
Course cse110 = null;
printMenu();
// Create a Scanner object to read user input
Scanner scan = new Scanner(System.in);
do // will ask for user input
{
System.out.println("What action would you like to perform?");
line = scan.nextLine();
if (line.length() == 1) {
input1 = line.charAt(0);
input1 = Character.toUpperCase(input1);
// matches one of the case statement
switch (input1) {
case 'A': // Add a course
System.out.print("Please enter the Instructor information:\n");
System.out.print("Enter instructor's first name:\t");
firstName = scan.nextLine();
System.out.print("Enter instructor's last name:\t");
lastName = scan.nextLine();
System.out.print("Enter instructor's office number:\t");
office = scan.nextLine();
Instructor myInstructor = new Instructor(firstName, lastName, office);
System.out.print("\nPlease enter the Course information:");
System.out.print("\nEnter course name:\t");
courseName = scan.nextLine();
System.out.print("Enter university name:\t");
university = scan.nextLine();
cse110 = new Course(courseName, myInstructor, university);
break;
case 'D': // Display course
System.out.print(cse110.toString());
break;
case 'Q': // Quit
break;
case '?': // Display Menu
printMenu();
break;
default:
System.out.print("Unknown action\n");
break;
}
} else {
System.out.print("Unknown action\n");
}
} while (input1 != 'Q' || line.length() != 1);
scan.close();
}
/** The method printMenu displays the menu to a user **/
public static void printMenu() {
System.out.print("Choice\t\tAction\n" + "------\t\t------\n" + "A\t\tAdd Course\n" + "D\t\tDisplay Course\n"
+ "Q\t\tQuit\n" + "?\t\tDisplay Help\n\n");
}
}
Heres the Course class:
import java.util.*;
public class Course
{
//----------------------------------------------------------------------
// ATTRIBUTES
private String courseName;
private Instructor instructor;
private String university;
//----------------------------------------------------------------------
// CONSTRUCTOR
public Course()
{
courseName = "?";
university = "?";
instructor = null;
}
public Course(String name, Instructor inst, String univer)
{
this.setName(name);
this.setInstructor(name, Instructor.lastName, Instructor.officeNum);
this.setUniversity(univer);
}
//----------------------------------------------------------------------
// ACCESSORS
public String getName()
{
return courseName;
}
public String getUniversity()
{
return university;
}
public Instructor getInstructor()
{
return instructor;
}
//----------------------------------------------------------------------
//METHODS
public void setName(String someName)
{
this.courseName = someName;
}
public void setUniversity(String someUniversity)
{
this.university = someUniversity;
}
public void setInstructor(String firstName, String lastName, String office)
{
Instructor.firstName = firstName;
Instructor.lastName = lastName;
Instructor.officeNum = office;
}
public String toString()
{
return "Course name:\t" + courseName + " at " + university + "\nInstructor Information:" + instructor + "\n";
}
}
Heres the Instructor class:
import java.util.*;
public class Instructor
{
//----------------------------------------------------------------------
// ATTRIBUTES
public static String firstName;
public static String lastName;
public static String officeNum;
//----------------------------------------------------------------------
// CONSTRUCTOR
public Instructor()
{
firstName = "?";
lastName = "?";
officeNum = "?";
}
public Instructor(String first, String last, String office)
{
this.setFirstName(first);
this.setLastName(last);
this.setOfficeNum(office);
}
public Instructor(Instructor inst)
{
firstName = inst.firstName;
lastName = inst.lastName;
officeNum = inst.officeNum;
}
//----------------------------------------------------------------------
// ACCESSORS
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getOfficeNum()
{
return officeNum;
}
//----------------------------------------------------------------------
//METHODS
public void setFirstName(String someFirstName)
{
this.firstName = someFirstName;
}
public void setLastName(String someLastName)
{
this.lastName = someLastName;
}
public void setOfficeNum(String someOffice)
{
this.officeNum = someOffice;
}
public String toString()
{
return ("\nLast Name:\t" + lastName +
"\nFirst Name:\t " + firstName +
"\nOffice Number:\t" + officeNum);
}
}
And finally heres the output:
> Choice Action
------ ------
A Add Course
D Display Course
Q Quit
? Display Help
What action would you like to perform?
A
Please enter the Instructor information:
Enter instructor's first name: John
Enter instructor's last name: Appleseed
Enter instructor's office number: 501
Please enter the Course information:
Enter course name: Intro to Java
Enter university name: ASU
What action would you like to perform?
D
Course name: Intro to Java at ASU
Instructor Information:null
What action would you like to perform?
Instead of Information:null, it should be printing out:
Last name: Appleseed
First name: John
Office Number: 501
How can I fix this?
Thanks!
You've never set the instructor property inside Course, after it is initialized as null. You should not use static fields in Instructor. You should create a new Instructor() and assign the instructor instance to the instructor property of Course
First fix your Instructor class:
public class Instructor
{
/******These should not be public static********/
private String firstName;
private String lastName;
private String officeNum;
...
}
Next fix your Course class
public class Course
{
private String courseName;
private Instructor instructor;
private String university;
public Course(String name, Instructor inst, String univer)
{
this.setName(name);
this.setInstructor(inst);
this.setUniversity(univer);
}
public void setInstructor(Instructor inst)
{
this.instructor = inst;
}
...
}

How to insert and display arraylist in java program?

This is the output of the program:
Enter your last name: Dela Cruz
Enter your first name: Juan
Enter your course: BSCS
Enter your year: 4th Year
Display Array List
[0] - Dela Cruz | Juan | BSCS | 4th Year
Add More (y/n): if yes it will add more entry...
Use following code.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class IO {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String continueAdd = "y";
List<Student> studentList = new ArrayList<>();
Student student;
while ("y".equalsIgnoreCase(continueAdd)) {
student = new Student();
System.out.println("Enter your last name:");
student.lastName = scn.nextLine();
System.out.println("Enter your first name:");
student.firstName = scn.nextLine();
System.out.println("Enter your course:");
student.course = scn.nextLine();
System.out.println("Enter your year:");
student.year = scn.nextLine();
studentList.add(student);
System.out.println("Add More (y/n): ");
continueAdd = scn.nextLine();
}
int i = 0;
for(Student studentTemp : studentList){
System.out.println("["+i+"] - " + studentTemp);
i++;
}
}
}
class Student {
String firstName;
String lastName;
String course;
String year;
#Override
public String toString(){
return lastName+" | "+ firstName +" | "+course+" | "+year;
}
}
You need :
public class Entries {
private String lname;
private String fname;
private String course;
private String year;
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
and then your mainApp :
public class MainApp {
public static void main(String[] args) {
List<Entries> students = new ArrayList<Entries>();
Scanner scan = new Scanner(System.in);
System.out.println("Enter a student:(y/n)");
String option = scan.nextLine();
while(option.equalsIgnoreCase("y")||option.equalsIgnoreCase("yes")){
Entries stud = new Entries();
System.out.println("Enter student's first name");
stud.setFname(scan.nextLine());
System.out.println("Enter student's last name");
stud.setLname(scan.nextLine());
System.out.println("Enter student's course");
stud.setCourse(scan.nextLine());
System.out.println("Enter student's year");
stud.setYear(scan.nextLine());
students.add(stud);
System.out.println("Enter another student:(y/n)");
option = scan.nextLine();
}
if(option.equalsIgnoreCase("n")||option.equalsIgnoreCase("no")){
System.out.println("Do you want to dispay all students? (y/n");
String display = scan.nextLine();
if(display.equalsIgnoreCase("y")||display.equalsIgnoreCase("yes"))
for (Entries entrie : students) {
System.out.println(entrie.getLname()+" |"+
entrie.getFname()+" |"+
entrie.getCourse()+" |"+
entrie.getYear());
} else {
System.exit(0);;
}
} else {
System.out.println("option not availabe");
System.exit(0);
}
}
use this code
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class hi {
static String n,c,y;
static String option="";
static ArrayList al= new ArrayList();
static Scanner s=new Scanner(System.in);
public static void input(){
System.out.println("Enter the name");
n=s.next();
System.out.println("Enter the course");
c=s.next();
System.out.println("Enter the year");
y=s.next();
al.add(n+"|"+c+"|"+y);
System.out.println("Add More (y/n)");
option=s.next();
System.out.println(option);
if(option.equals("y")|| option.equals("Y")){
input();
}
else{
System.out.println(al);
//System.exit(0);
}
}
public static void main(String args[]) throws InstantiationException, IllegalAccessException{
input();
}
}
It would probably be better to have a class and work with objects but here is with List.
boolean flag = true;
List<String> list = new ArrayList<>();
int i = 0;
while (flag) {
String lastname, firstname, code, year;
Scanner sc = new Scanner(System.in);
System.out.println("Enter lastname");
lastname = sc.nextLine();
System.out.println("Enter firstname");
firstname = sc.nextLine();
System.out.println("Enter code");
code = sc.nextLine();
System.out.println("Enter year");
year = sc.nextLine();
list.add(i, lastname + " | " + firstname + " | " + code + " | " + year);
System.out.println(list.get(i));
i++;
System.out.println("add more? y/n");
if (!"y".equals(sc.next())) {
flag = false;
}
}

Using polymorphism to display output of a arraylist

I need to display the first and last names of all contact entered when user selected Display contacts from the menu. I also need to display all details of the contacts when the user inputs the Contact ID entered into the ArrayList.
All I can get to display is the last contact entered. Am I not keeping the ArrayList once I go through once then go back to the menu and enter another contact? Or am I just not calling the print function right still to print all contacts in the arraylist.
If I enter 3 now it just goes back to the first line of the array and wants me to enter a contact ID, and goes through creating a contact again, not displaying what is already there.
package ooo1;
import java.util.ArrayList;
import java.util.Scanner;
public class ContactList {
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
int type = 0;
while(type != 4){
System.out.println("Please select an option:");
System.out.println("Personal Contact: Enter 1");
System.out.println("Business Contact: Enter 2");
System.out.println("Display Contacts List: Enter 3");
System.out.println("4 to quit");
type = input1.nextInt();
if(type == 4){
System.out.println("Goodbye");
break;
}
ArrayList<Contact> contacts = new ArrayList<Contact>();
Scanner input = new Scanner(System.in);
System.out.println("Please enter ContactId : ");
String contactId = input.nextLine();
System.out.println("Please enter First Name : ");
String firstName = input.nextLine();
System.out.println("Please enter Last Name : ");
String lastName = input.nextLine();
System.out.println("Please enter Address : ");
String address = input.nextLine();
System.out.println("Please enter Phone Number : ");
String phoneNumber = input.nextLine();
System.out.println("Please enter Email Address : ");
String emailAddress = input.nextLine();
if(type == 1){
System.out.println("Please enter Birthday: ");
String dateofBirth = input.nextLine();
Contact pcontact = new PersonalContact(contactId, firstName, lastName, address, phoneNumber, emailAddress, dateofBirth);
contacts.add(pcontact);
for (Contact showcontact: contacts){
System.out.println(showcontact.displayContact());
}
}
else if(type == 2){
System.out.println("Please enter Job Title: ");
String jobTitle = input.nextLine();
System.out.println("Please enter Organization: ");
String organization = input.nextLine();
Contact bcontact = new BusinessContact(contactId, firstName, lastName, address, phoneNumber, emailAddress, jobTitle, organization);
contacts.add(bcontact);
for (Contact showcontact: contacts){
System.out.println(showcontact.displayContact());
}
}
else if(type ==3){
for (Contact listcontacts: contacts){
System.out.println(listcontacts.displayFullName());
}
}
}
}
}
Parent Class:
package ooo1;
public abstract class Contact {
String contactId;
String firstName;
String lastName;
String address;
String phoneNumber;
String emailAddress;
public Contact(String contactId,String firstName,String lastName, String address, String phoneNumber, String emailAddress)
{
this.contactId = contactId;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.phoneNumber = phoneNumber;
this.emailAddress = emailAddress;
}
public void setContactId(String input){ this.contactId = input; }
public String getContactId(){ return this.contactId; }
public void setFirstName(String input){ this.firstName = input; }
public String getFirstName(){ return this.firstName; }
public void setLastName(String input){ this.lastName = input; }
public String getLastName(){ return this.lastName; }
public void setAddress(String input){ this.address = input; }
public String getAddress(){ return this.address; }
public void setPhoneNumber(String input){ this.phoneNumber = input; }
public String getPhoneNumber(){ return this.phoneNumber; }
public void setEmailAddress(String input){ this.emailAddress = input; }
public String getEmailAddress(){ return this.emailAddress; }
public String displayFullName(){
System.out.println("Contact List:");
return ("First Name:" + this.getFirstName() + "Last Name:" + this.getLastName());
}
public String displayContact(){
return ("ContactID:" + this.getContactId() + "First Name:" + this.getFirstName() + "Last Name:" + this.getLastName() + "Address:" + this.getAddress() + "Phone Number:" + this.getPhoneNumber() + "Email Address" + this.getEmailAddress());
}
}
One of the subclasses: Other same just adds more variables:
package ooo1;
public class PersonalContact extends Contact {
private String dateofBirth;
public PersonalContact(String contactId, String firstName, String lastName, String address, String phoneNumber, String emailAddress, String dateofBirth){
super(contactId, firstName, lastName, address, phoneNumber, emailAddress);
this.dateofBirth = dateofBirth;
}
public void setDateofBirth(String input){ this.dateofBirth=input; }
public String getDateofBirth(){ return this.dateofBirth; }
#Override
public String displayContact(){
System.out.println("Personal Contacts:");
return super.displayContact() + "Date of Birth: " + this.getDateofBirth();
}
}
So here is a small example on how to use polymorphism, it's basically your classes stripped down to a bar minimum (this is what the SSCCE is about - stripping what's not relevant, like comments and multiple attributes that behaves the same etcetera).
When you call the displayContact() method in the on the Contact objects stored in the ArrayList polymorphism makes sure the correct displayContact method is used.
The reason PersonalContact.displayContacts(); won't work is that you need to call the method on on object as it's not a static method.
I hope this example helps:
// Contact.java
public abstract class Contact {
private final String name;
public Contact(String name) {
this.name = name;
}
public String displayContact() {
return "Contact name: "
+ name + ". Contact type: "
+ this.getClass().getName() + ". ";
}
}
// PersonalContact.java
public class PersonalContact extends Contact {
private final String dateofBirth;
public PersonalContact(String name, String dateOfBirth) {
super(name);
this.dateofBirth = dateOfBirth;
}
#Override
public String displayContact() {
return super.displayContact() + "Date of birth: " + dateofBirth + ".";
}
}
// BusinessContact.java
public class BusinessContact extends Contact {
private final String organization;
public BusinessContact(String name, String org) {
super(name);
this.organization = org;
}
#Override
public String displayContact() {
return super.displayContact() + "Organization: " + organization + ".";
}
}
// ContactList.java
import java.util.ArrayList;
public class ContactList {
public static void main(String[] args) {
ArrayList<Contact> contacts = new ArrayList<>();
PersonalContact personalContact1 = new PersonalContact("John", "1980-01-01");
BusinessContact businessContact1 = new BusinessContact("theCompany", "The Company");
contacts.add(personalContact1);
contacts.add(businessContact1);
for (Contact contact : contacts) {
System.out.println(contact.displayContact());
}
}
}
EDIT added some more referencing issues mentioned in a comment.
The reason you can't print out anything is that the block of code asking for input is always executed as it's not contained in the type 1 or 2 blocks. To remedy that I'd suggest the following changes:
First, move the ArrayList and Scanner to the start of the main method:
ArrayList<Contact> contacts = new ArrayList<Contact>();
Scanner input = new Scanner(System.in);
Then enclose the entire block of code dealing with input in an if block so it looks like this:
if(type==1 || type==2){
Contact contact = null;
System.out.println("Please enter ContactId : ");
String contactId = input.nextLine();
System.out.println("Please enter First Name : ");
String firstName = input.nextLine();
System.out.println("Please enter Last Name : ");
String lastName = input.nextLine();
System.out.println("Please enter Address : ");
String address = input.nextLine();
System.out.println("Please enter Phone Number : ");
String phoneNumber = input.nextLine();
System.out.println("Please enter Email Address : ");
String emailAddress = input.nextLine();
if(type == 1){
System.out.println("Please enter Birthday: ");
String dateofBirth = input.nextLine();
contact = new PersonalContact(contactId, firstName, lastName, address, phoneNumber, emailAddress, dateofBirth);
}
else if(type == 2){
System.out.println("Please enter Job Title: ");
String jobTitle = input.nextLine();
System.out.println("Please enter Organization: ");
String organization = input.nextLine();
contact = new BusinessContact(contactId, firstName, lastName, address, phoneNumber, emailAddress, jobTitle, organization);
}
// add the new contact
contacts.add(contact);
// print out the newly created contact here
System.out.println(contact.displayContact());
}
Also, you don't really need two Scanner-objects, just reuse one of them :)
And you should consider moving the if(type==4) to after the other blocks so that it comes in order (that's just a matter of style though).

Categories