Making output match whats needed - java

I have a practice problem that I need to complete and have done everything however I cannot get the output to match whats needed. I have tried some of the google answers but nothing seems to be working. Below is the code and the output I get vs what I want. We are not allowed to modify the main method but only the classes.
I am just confused on how to make the output from each class start on a new line.
There is this statement in the instructions but I don't understand how to go about it:
the Student class should have a public display function that calls the parent class’ display
function,
Code:
public class H255{public static void main (String[] args){while (JPL.test()){
Person pObj = new Person("Albert","Einstein");
Student sObj = new Student("John","Smith",123456,"First Year","Pullan");
Teacher tObj = new Teacher("Wayne","Pullan","Computer Science",100000,"Lecturer");
System.out.println("Person :");
pObj.Display();
System.out.println("");
System.out.println("Student :");
sObj.Display();
System.out.println("");
System.out.println("Teacher :");
tObj.Display();
}}}
class Person{
private String FirstName;
private String LastName;
public Person(String fName, String lName){
this.FirstName = fName;
this.LastName = lName;
}
public void Display(){
System.out.println("First Name: " + FirstName + " Last Name: " + LastName);
}
}
class Student extends Person{
private int id;
private String standard;
private String instructor;
public Student(String fName, String lName, int nId, String stnd, String instr){
super(fName, lName);
this.id = nId;
this.standard = stnd;
this.instructor = instr;
}
public void Display(){
System.out.println("ID: " + id + "Standard: " + standard + "Instructor: " + instructor);
}
}
class Teacher extends Person{
private String mainSubject;
private int salary;
private String type;
public Teacher(String fName, String lName, String sub, int slry, String sType){
super(fName, lName);
this.mainSubject = sub;
this.salary = slry;
this.type = sType;
}
public void Display(){
System.out.println("Main Subject: " + mainSubject + "Salary: "
+ salary + "Type: " + type );
}
}
Output:

the writing of main method like these code:
System.out.print("Person :");
pObj.Display();
System.out.print("Student :");
sObj.Display();
System.out.print("Teacher :");
tObj.Display();
because:the println method has a build in wrap feature, so just replace println with print.

Related

Mooc Helsinki Part 1 Week 4 Exercise 18 Java Weird Occurrence

Having a problem here with this error which the solution to is simply beyond me.
FAIL: PersonalInformationCollectionTest testInputFirst
Something weird occurred. It could be that the void main (String[] args) method of the class class PersonalInformationCollection has disappeared or your program crashed due to an exception. More information: java.util.NoSuchElementException.
It then says the same thing but for testInputSecond as well.
Can't find any reason for whats wrong. Looked online at a correct solution and perhaps it's just my poor eye sight but i couldn't see a single difference between my somehow incorrect code and their correct code.
Thanks for any help in advance.
import java.util.ArrayList;
import java.util.Scanner;
public class PersonalInformationCollection {
public static void main(String[] args) {
// implement here your program that uses the PersonalInformation class
ArrayList<PersonalInformation> infoCollection = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("First name: ");
String firstName = scanner.next();
if (firstName.isEmpty()){
break;
}
System.out.println("Last name: ");
String lastName = scanner.next();
System.out.println("Identification number: ");
String idNumber = scanner.next();
infoCollection.add(new PersonalInformation(firstName, lastName, idNumber));
}
for (PersonalInformation personalInfo : infoCollection){
System.out.println(personalInfo.getFirstName() + " " + personalInfo.getLastName());
}
}
}
Solved by using scanner.nextLine() rather than scanner.next(). No idea how that made such a difference in this case
Use the more general type for your variables as you can, because it doesn't change the logic if you would use an LinkedList instaed of an Arraylist and also it has the same methods you are using.
For strings use scanner,nextLine()
numberId or simply id should be a number integer would be great so use scanner.nextInt() to get only integer in here
implement/override the toString methode in your class PersonalInformation to have the string reprensetation at one point
class PersonalInformation
public class PersonalInformation {
private final int id;
private final String firstName;
private final String lastName;
public PersonalInformation(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
private int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
#Override
public String toString() {
return "PersonalInformation{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
class PersonalInformationCollection
public static class PersonalInformationCollection {
public static void main(String[] args) {
// implement here your program that uses the PersonalInformation class
List<PersonalInformation> infoCollection = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Identification number: ");
int id = scanner.nextInt();
if (id < 0){
break;
}
System.out.print("First name: ");
String firstName = scanner.nextLine();
System.out.print("Last name: ");
String lastName = scanner.next();
infoCollection.add(new PersonalInformation(id, firstName, lastName));
}
for (PersonalInformation personalInfo : infoCollection){
System.out.println(personalInfo);
}
scanner.close();
}
}

How can I solve with Java's map containsKey() method?

I checked the code and saving data to the HashMap is correct, when typing ADD. Then after choosing option FIND I can get to the dedicated function but the method is unable to show me found object even if it is correct 100%.
Please check this code out and tell me why it does not find right objects in "public void showInfo(String name, String secondName)" for class Company that is sparked by TYPING "FIND" in class CompanyApp
import java.util.InputMismatchException;
import java.util.Objects;
import java.util.Scanner;
public class CompanyApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
options[] values = options.values();
int choose;
int EXIT_NR = 2;
Company ref = new Company();
do {
System.out.println("Available options: ");
for (options one : values) {
System.out.println(one.getDescription() + " - " + one.name());
}
System.out.println("Choose one: ");
try {
choose = options.valueOf(in.nextLine()).ordinal();
if (Objects.equals(EXIT_NR, choose)) break;
if (choose < 0 || choose >= options.values().length) {
throw new IllegalArgumentException("Choose 0, 1 or 2!");
}
options(choose);
} catch (InputMismatchException e) {
System.out.println("Choose a number ");
}
} while (1 == 1);
}
static void options(int choose){
Company ref = new Company();
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to
find: ");
String secondName2 = info.nextLine();
ref.showInfo(name2, secondName2);
break;
}
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Company {
private Map<String, Employee> map = new HashMap<>();
public void add(Employee employee){
String key = employee.getName() + " " + employee.getSecondName();
if(!map.containsKey(key)){
map.put(key, employee);
System.out.println("Added object to map");}
}
public void showInfo(String name, String secondName){
String key = name + " " + secondName;
System.out.println("in showinfo method");
if(map.containsKey(key)){
System.out.println("found an object");
Employee employee = map.get(key);
System.out.println(employee.getName());
}}}
enum options {
ADD("Add employee "), FIND("Find employee"), EXIT("Exit program");
private String description;
options(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "options{" +
"description='" + description + '\'' +
'}';
}
}
String name;
String secondName;
double salary;
public Employee(String name, String secondName, double salary) {
this.name = name;
this.secondName = secondName;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", secondName='" + secondName + '\'' +
", salary=" + salary +
'}';
}
}
The problem is in the method static void options(int choose). You need to pass the Company-Object and use it there like this:
Call from main method (ref is the Company-Object you create in the main method)
options(choose, ref);
The options-method with the Company as second parameter:
static void options(int choose, Company ref){
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
//use the passed Company here
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to find: ");
String secondName2 = info.nextLine();
//and here
ref.showInfo(name2, secondName2);
break;
}
}
Explanation what is happening in your code
As mentioned, the problem is in the method static void options(int choose).
Here you create a new Company-Object which is not passed in any way to the main method.
This is what happens, when you use ADD and a FIND afterwards:
Call options from main method with ADD
new Company-Object is created in options
new Employee-Object is added to the Company from the previous point
the method ends -> the created Company-Object is "thrown away" (eligible for Garbage Collection)
Call options from main method with FIND
new Company-Object is created in options(therefore no Employees in it)
no Employee can be found, because there is no entry in the map of the newly created Company
The map is empty at the time when you're trying to get the data from it using FIND option. The reason for that is you recreate the Company object in the options method:
Company ref = new Company();
At the same time also the map is recreated so there are no records inside.
Also, the Company object in the main method is not used.

Having trouble using the compareTo method

Hey all I've recently been trying to learn the compareTo method but this is extremely confusing.
The goal of this program was to hardcode information into a array of objects and sort it by the test score. The problem is compareTo method which I'm having trouble creating since the book I'm using doesn't go in to detail about this method. Here is the code so far.
public class janesj_Lab7 {
public static void main(String[] args) {
CS_UnderGradStudent no1 = new CS_UnderGradStudent(101,"Nancy","Brown","abc#kean.edu",70.0);
CS_UnderGradStudent no2 = new CS_UnderGradStudent(102,"John", "May","def#kean.edu",90);
CS_GradStudent no3 = new CS_GradStudent(103,"William","Smith","xyz#kean.edu",70,"Database");
Object[] arrays = new Object[3];
arrays[0] = no1;
arrays[1] = no2;
arrays[2] = no3;
int x = (int)Student.getGrade();
Arrays.sort(arrays,0,3);
for(int i = 0;i<arrays.length;i++) {
System.out.println(arrays[i].toString());
}
}
public static abstract class Student implements Comparable<Student>{
public static int studentId;
public static String firstName;
public static String lastName;
public static String email;
public static double testScore;
public static String STUDENT_TYPE;
public static double getGrade(){
return testScore;
}
public static String getStudent() {
return STUDENT_TYPE;
}
public Student(int id,String fname, String lname, String email, double testScore){
this.studentId = id;
this.firstName = fname;
this.lastName = lname;
this.email =email;
this.testScore = testScore;
}
#Override
public String toString() {
String x = Double.toString(testScore);
return "\tStudent ID: " + studentId + " name: "+ firstName + ","+ lastName + " Email: " + email + " testScore: " + x;
}
public abstract String computeGrade();
}
public static class CS_UnderGradStudent extends Student implements Comparable<Student>{
String STUDENT_TYPE ="CS_UnderGradStudent";
public CS_UnderGradStudent(int id,String fname, String lname, String email, double testScore) {
super(id,fname,lname,email,testScore);
}
public String computeGrade() {
if( testScore>=70) {
return "Pass";
}
else {
return "Fail";
}
}
public String toString(){
String x = Double.toString(testScore);
return"student type: " + STUDENT_TYPE + "\n" + super.toString() + "\n\t" + "Grade: " + computeGrade();
}
}
public static class CS_GradStudent extends Student implements Comparable<Student>{
String STUDENT_TYPE = "CS_GradStudent";
String researchTopic;
public CS_GradStudent(int id,String fname, String lname, String email, double testScore,String r) {
super(id,fname,lname,email,testScore);
researchTopic = r;
}
public String computeGrade() {
if(testScore>= 80) {
return "Pass";
}
else {
return "Fail";
}
}
public String toString() {
String x = Double.toString(testScore);
return"student type: " + STUDENT_TYPE + "\n" + super.toString() + "\n" + "Grade: " + computeGrade() + "\nResearch Topic: " + researchTopic;
}
}
}
```

arraylist with method

As my last question obviously was a little bit unclear (I applogise for that), I'm making a new try, and this time I will really try to be clear.
Here is the code I have written so far
Main class:
import java.util.*;
public class Head {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String fname, lname;
int choice;
ArrayList<People>list = new ArrayList<>();
People p1 = new People("Mia", "Wallace", "1111");
People p2 = new People("Marcellus", "Wallace", "2222");
list.add(p1);
list.add(p2);
System.out.println("Welcome");
System.out.println("1) Add person \n2) Last name \n3) Print list");
choice = scan.nextInt();
switch(choice){
case 1:
People.walk(); //calling the method
break;
case 2:
People.run();
break;
case 3:
People.crawl();
break;
}
}
}
People class:
import java.util.*;
public class People {
static Scanner scan = new Scanner(System.in);
private static String fname;
private static String lname;
private static String dob;
public People(String fname, String lname, String dob){
this.fname = fname;
this.lname = lname;
this.dob = dob;
}
public String getFname(){
return fname;
}
public String getLname(){
return lname;
}
public String getDob(){
return dob;
}
public static void walk(){
System.out.println("Enter first name: ");
fname = scan.next();
System.out.println("Enter last name: ");
lname = scan.next();
System.out.println("Enter dob: ");
dob = scan.next();
list.add(new People(fname, lname, dob)); **//list cannot be resolved**
}
public static void run(){
System.out.println("Remove people");
}
public static void crawl(){
int peoplenumber = 0;
System.out.println("\nNumber of peoples: " + list.size()); **//list cannot be resolved**
for(People p : list){ **//list cannot be resolved**
peoplenumber += 1;
System.out.println("#" + peoplenumber + "\n" + p.toString());
}
}
public String toString(){
return "First name: " + this.fname + "\nLast name: " + this.lname + "\nDateOfBirth: " + this.dob;
}
}
I do understand why I get the error, but I don't know how to get around it. Any help?
Am I right when I try to move code from the main-class to the costructors?
If you guys have any comments or ideas how I should solve this, or move on with java, I will gladly here them.
Thank you very much for your time and your help :)
The arraylist should be in the main class. If it were in the person class, it would be created once for every person object you create. To access a method for that person, you want to call the name of the OBJECT (not the type), the .method(parameters).
If you wanted to call run on p1 (not really sure what you want to call it on), you would use:
p1.run();
That would perform the code in the run method where it is defined.

how to create and use a print method using java

Based on the code below, I need to modify the code in the Employee class by creating a specialised print method called employee print() and show how it will be used to print in the employee Test class! Any help please? Here is the code:
class Employee1{
String empName;
String empNum;
String empEmailAddress;
int yearOfBirth;
}
public class employeeTest {
public static void main(String[] args) {
Employee1 emp1 = new Employee1();
emp1.empName = "Sam";
emp1.empNum = "213-23-978";
emp1.empEmailAddress = "sammy#company.za";
Employee1 emp2 = new Employee1();
emp2.empName = "Tasha";
emp2.empNum = "315-90-274";
emp2.yearOfBirth = 1982;
System.out.println("Employee Name: " + emp1.empName);
System.out.println("Employee Number: " + emp1.empNum);
System.out.println("Email Adress: " + emp1.empEmailAddress);
System.out.println("Year of Birth: " + emp1.yearOfBirth);
System.out.println("Employee Name: " + emp2.empName);
System.out.println("Employee Number: " + emp2.empNum);
System.out.println("Email Address: " + emp2.empEmailAddress);
System.out.println("Year of Birth: " + emp2.yearOfBirth);
}
}
You add a method called print to the employee class called print
class Employee1{
String empName;
String empNum;
String empEmailAddress;
int yearOfBirth;
public void print() {
System.out.println("Employee name:" + empName);
System.out.println("Employee number:" + empNum);
// etc
}
}
and call it like this:
// these lines replace the System.out.println block in your code
emp1.print();
emp2.print();
class Employee1
{
String empName;
String empNum;
String empEmailAddress;
int yearOfBirth;
#Override toString(){
System.out.println(empName + empNum + empEmailAddress + yearOfBirth);
}
}
emp.toString();
You can override toString() method in class Employee like this
class Employee1{
String empName;
String empNum;
String empEmailAddress;
int yearOfBirth;
#Override
public String toString(){
return empName + emNum +.....
}
}
And use this to print in EmployeeTest sysout(instanceOfEmployee)

Categories