Mooc Helsinki Part 1 Week 4 Exercise 18 Java - java

The program described here should be implemented in the class PersonalInformationCollection. NB! Do not modify the class PersonalInformation.
After the user has entered the last set of details (they enter an empty first name), exit the repeat statement.
Then print the collected personal information so that each entered object is printed in the following format: first and last names separated by a space (you don't print the identification number). An example of the working program is given below:
Sample output
First name: Jean
Last name: Bartik
Identification number: 271224
First name: Betty
Last name: Holberton
Identification number: 070317
First name:
Jean Bartik
Betty Holberton
The PersonalInformation class:
public class PersonalInformation {
private String firstName;
private String lastName;
private String identificationNumber;
public PersonalInformation(String firstName, String lastName, String identificationNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.identificationNumber = identificationNumber;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getIdentificationNumber() {
return identificationNumber;
}
#Override
public String toString() {
return this.lastName + ", " + this.firstName + " (" + this.identificationNumber + ")";
}
}
My solution which I can only print all values instead of only Firstnames and the Lastnames from the array:
public class Main {
public static void main(String[] args) {
// write your code here
Scanner scanner = new Scanner(System.in);
ArrayList<PersonalInformation> infoCollection = new ArrayList<>();
while (true) {
System.out.println("First name: ");
String firstName = scanner.nextLine();
if (firstName.equals("")) {
break;
}
System.out.println("Last name: ");
String lastName = scanner.nextLine();
System.out.println("Identification number: ");
String identificationNumber = scanner.nextLine();
infoCollection.add(new PersonalInformation(firstName, lastName, identificationNumber));
}
System.out.println(infoCollection);
}
}
I need to modify the code. I am a beginner, an explanatory suggestion would be much appreciated.

Instead of
System.out.println(infoCollection);
you´ll have
infoCollection.stream().forEach(p -> System.out.println(p.getFirstName() + " " + p.getLastName()));

public class Main {
public static void main(String[] args) {
// write your code here
ArrayList<PersonalInformation> infoCollection = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("First name: ");
String firstName = scanner.nextLine();
if (firstName.equals("")) {
break;
}
System.out.println("Last name: ");
String lastName = scanner.nextLine();
System.out.println("Identification number: ");
String identificationNumber = scanner.nextLine();
infoCollection.add(new PersonalInformation(firstName, lastName, identificationNumber));
}
for (int i = 0; i < infoCollection.size(); i++) {
System.out.println(infoCollection.get(i).getFirstName() + " "
+ infoCollection.get(i).getLastName());
}
}
}

After the while statement, to print just the first and last names, try:
for (int i = 0; i < infoCollection.size(); i++) {
System.out.println(infoCollection.get(i).getFirstName() + " " + infoCollection.get(i).getLastName());
}

for (PersonalInformation personalInformation: infoCollection) {
System.out.println(personalInformation.getFirstName() + ' ' +
personalInformation.getLastName());
}

Related

Collections.sort() error occuring while sorting ArrayList [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to sort by name ArrayList elements but I couldn't solve problem . . . . . .
Could someone help?
ERROR At case 4: Collections.sort(contact);
ERROR "Required type: List Provided: List reason: no
instance(s) of type variable(s) T exist so that Data conforms to
Comparable<? super T>"
below code works fine without sort
public class AddressBook {
private static List<Data> contact = new ArrayList<Data>();
public static void main(String[] args) {
AddressBook addressBook = new AddressBook();
Scanner sc = new Scanner(System.in);
int menu;
String choice;
String choice2;
System.out.println(" =========================== ");
System.out.println(" | 0. Exit. |");
System.out.println(" | 1. Add contact. |");
System.out.println(" =========================== ");
try
{
menu = sc.nextInt();
while (menu != 0) {
switch (menu) {
case 1:
while (menu != 2) {
System.out.println("Enter First Name: ");
String firstName = sc.next();
System.out.println("Enter Last Name: ");
String lastName = sc.next();
System.out.println("Enter Phone: ");
String homePhone = sc.next();
if (homePhone.length()!=11 || !homePhone.startsWith("8")) {
System.out.println("Number should start with '8' and has '11' digit" );
}else {
System.out.println("Enter Email: ");
String personalWebSite = sc.next();
contact.add(new Data(firstName, lastName,
homePhone, personalWebSite));
}
System.out
.println("Would you like to add someone else? 1: Yes, 2: No");
menu = sc.nextInt();
}
break;
case 2:
System.out
.println("Enter First Name of contact that you would like to edit: ");
choice = sc.next();
addressBook.deleteByFirstName(choice);
System.out.println("Enter First Name: ");
String firstName = sc.next().toUpperCase();
System.out.println("Enter Last Name: ");
String lastName = sc.next();
System.out.println("Enter Phone: ");
String homePhone = sc.next();
System.out.println("Enter Email: ");
String personalWebSite = sc.next();
contact.add(new Data(firstName, lastName,
homePhone, personalWebSite));
break;
case 3:
System.out.println("------------------");
System.out.println("1. Search number: ");
System.out.println("2. Search name: ");
System.out.println("------------------");
int search= sc.nextInt();
if(search==1) {
System.out
.println("Enter Number of contact: ");
choice2 = sc.next();
addressBook.searchByPhoneNumber(choice2);
break;
}else {
System.out
.println("Enter First Name of contact: ");
choice = sc.next();
addressBook.searchByFirstName(choice);
break;
}
case 4:
Collections.sort(contact);
//ERROR occurring here
case 5:
System.out.println("This is a list of every contact");
System.out.println(addressBook.contact);
break;
case 6:
System.out.println("------------------");
System.out.println("1. Delete by name: ");
System.out.println("2. Delete all: ");
System.out.println("------------------");
int del= sc.nextInt();
if(del==1){
System.out
.println("Enter First Name of contact that you would like to delete: ");
choice = sc.next();
addressBook.deleteByFirstName(choice);
break;
}else{
System.out.println("Successfully Deleted");
System.out.println("");
contact.clear();
}
break;
default:
throw new IllegalStateException("Unexpected value: " + menu);
}
System.out.println(" =========================== ");
System.out.println(" | 0. Exit. |");
System.out.println(" | 1. Add contact. |");
System.out.println(" =========================== ");
menu = sc.nextInt();
}
}
catch(InputMismatchException exception)
{
System.out.println("This is not an integer");
}
System.out.println("Good-Bye!");
}
private void searchByFirstName(String firstName) {
for (Iterator<Data> iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getFirstName().equalsIgnoreCase(firstName)) {
System.out.println(temp);
return;
}
}
System.out.println("No contact with first name " + firstName
+ " was found.");
}
private void searchByPhoneNumber(String homePhone) {
for (Iterator<Data> iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getHomePhone().equalsIgnoreCase(homePhone)) {
System.out.println(temp);
return;
}
}
System.out.println("No contact with number " + homePhone
+ " was found.");
}
private void deleteByFirstName(String firstName) {
for (Iterator<Data> iterator = contact.iterator(); iterator.hasNext();) {
Data temp = iterator.next();
if (temp.getFirstName().equalsIgnoreCase(firstName)) {
iterator.remove();
return;
}
}
System.out.println("No contact with first name " + firstName
+ " was found.");
}
private void deleteAll(String all) {
for (Iterator<Data> iterator = contact.iterator(); iterator.hasNext();) {
iterator.remove();
return;
}
System.out.println("Deleting...");
}
private static int[] selectionSortAlg(int[] a, int n) {
for (int i = 0; i < n - 1; i++) {
int iMin = i;
for (int j = i + 1; j < n; j++) {
if (a[j] < a[iMin]) {
iMin = j; // index of smallest element
}
}
int temp = a[i];
a[i] = a[iMin];
a[iMin] = temp;
System.out.println("Pass..." + i + "..." + Arrays.toString(a));
}
return a;
}
public static class Data {
private String firstName = null;
private String lastName = null;
private String homePhone = null;
private String personalWebSite = null;
public Data(String firstName,String lastName, String homePhone, String personalWebSite) {
this.firstName = firstName;
this.lastName = lastName;
this.homePhone = homePhone;
this.personalWebSite = personalWebSite;
}
public String getFirstName() {
return firstName;
}
public String getHomePhone() {
return homePhone;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String toString() {
return String.format(firstName+" "+lastName+" "+homePhone+" "+personalWebSite);
}
}
}
class T {
private String firstName = null;
private String lastName = null;
private String homePhone = null;
private String personalWebSite = null;
public T(String firstName,String lastName, String homePhone, String personalWebSite) {
this.firstName = firstName;
this.lastName = lastName;
this.homePhone = homePhone;
this.personalWebSite = personalWebSite;
}
public String getFirstName() {
return firstName;
}
public String getHomePhone() {
return homePhone;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String toString() {
return String.format(firstName+" "+lastName+" "+homePhone+" "+personalWebSite);
}
}
I am not quite sure, but I think you need to do this(in your case 4):
Collections.sort(contact, new Comparator<Data>() {
#Override
public int compare(Data contact1, Data contact2) {
return contact1.getFirstName().compareTo(contact2.getFirstName());
}
});
Give it a try, I had used it somewhere else, and it worked. Hope it helps. Cheers :)
Use in this way
contact.sort( Comparator.comparing(Data::getFirstName) );
You have 2 options whether implement Comparable or provide comparator to sorting function, i.e.
Collections.sort(contact, (d1,d2) -> d1.firstName.compareTo(d2.firstName));
or
contact.sort((d1,d2) -> d1.firstName.compareTo(d2.firstName));
Your class Data you implement comparable, look at here:
https://www.geeksforgeeks.org/comparable-vs-comparator-in-java/
public static class Data implements Comparable<Data>
...
public int compareTo(Data m) {
...
}
Either pass a comparator in sort method or make Data class implement Comparable interface and implement compareTo()
#GiorgosDev gave an example in which data class is expected to implement comparable interface.
Either implement comparable in Data class or pass comparator in sort method. Example Collections.sort(contact, Comparator.comparing(Data::getFirstName));

How to call on a field from a new object

I created a class called "Person" here it is: (ignore the toString. I haven't done anything with that yet)
public class Person {
public String firstName;
public String middleName;
public String lastName;
public Person() {
firstName = "first";
middleName = "middle";
lastName = "last";
}
public Person(String first, String middle, String last) {
firstName = first;
middleName = middle;
lastName = last;
}
public String toString() {
return (firstName + " " + middleName + " " + lastName);
}
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
}
And then I created an implementation class in a new file, this is it:
import java.util.*;
public class TestProgPerson
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
String first;
String middle;
String last;
Person name = new Person("Joe", "Smith", "Blow");
System.out.println("Name: " + name);
System.out.println("Please enter a last name, to check if it corresponds with the persons last name: " );
last = console.nextLine();
if (last == (objectReference.lastName))
System.out.println("The last name you entered matches the persons last name");
else
System.out.println("The last name you entered does not match the persons last name");
}
}
So what I want it to do is this: Have an object with the first name, middle name, and last name. Output that name. (The program works this far). Then I want to have the user enter a last name, and the program checks to see if the entered last name is the same as the last name in the object. How do I go about calling just an individual string from that object?
Here you are calling the name object of the class but not any field of that class.
System.out.println("Name: " + name);
You can call fields here by using the object of the class and the dot operator.
For Example.
System.out.println("Name: " + name.firstName + " " + name.middleName + " " + name.lastName);
Moreover because strings are Objects and should be compared with the equals method.

UserId cannot be resolved to a type error java

I am new to methods such as the public void stuff on Java.
If someone enters First Name as: John and surname: Smith. My program should display the UserID as jsmith. That all works fine when I put it all in the main method. I want it all on the same class (UserID) I also get an error message saying Insert assignment operator expression where it says:
process.userID;
Here's the code:
import java.util.Scanner;
public class UserID {
Scanner myScan = new Scanner (System.in);
char firstLetter;
String firstName;
String minCharacters;
String surname;
String userID;
public void firstName () {
System.out.print("Please enter your firstname: ");
firstName = myScan.nextLine();
}
public void surname () {
System.out.print("Please enter your surname: ");
surname = myScan.nextLine();
}
public void userID (String userID) {
firstLetter = firstName.charAt(0);
minCharacters=surname.substring(0, 5);
userID = firstLetter+minCharacters;
System.out.print("User ID = " + userID.toLowerCase());
System.out.println ("\nPlease keep a note of your User ID");
myScan.close();
}
public static void main(String[] args) {
String userID;
userID process = new UserID();
process.userID;
}
}
Adding on top of Daniel Stanley's answer, you are not calling firstname() and surname() methods in your main method or inside userId() method which takes input from Command Line.
This line:
userID process = new UserID();
should be:
UserID process = new UserID(); //capital 'U'
and then:
process.userID("SomeString"); //add brackets
public void userID () {
firstLetter = firstName.charAt(0);
minCharacters=surname.length()>=5?surname.substring(0, 5):surname;
userID = firstLetter+minCharacters;
System.out.print("User ID = " + userID.toLowerCase());
System.out.println ("\nPlease keep a note of your User ID");
myScan.close();
}
public static void main(String[] args) {
UserID process = new UserID();
process.firstName();
process.surname();
process.userID();
}
Updated your code. It works. First issue was with UserID as Daniel pointed. Later, the surname can be less than 5 digit so it takes care of that. since you are using firstname and surname then you do not need to pass userId in the method.
Try this, Code have some logical and Java naming convention errors;
I have edited you code respectively.
public class UserID {
Scanner myScan = new Scanner(System.in);
char firstLetter;
String firstName;
String minCharacters;
String surName;
String userID;
public void setFirstName() {
System.out.print("Please enter your firstname: ");
this.firstName = myScan.nextLine();
}
public void setSurName() {
System.out.print("Please enter your surname: ");
this.surName = myScan.nextLine();
}
public void generateUserID() {
firstLetter = firstName.charAt(0);
minCharacters = surName;
userID = firstLetter + minCharacters;
System.out.print("User ID = " + userID.toLowerCase());
System.out.println("\nPlease keep a note of your User ID");
myScan.close();
}
public static void main(String[] args) {
String userID;
UserID process = new UserID();
process.setFirstName();
process.setSurName();
process.generateUserID();
}
}
Feel free to ask anything.

Trouble with calling methods from other classes

My code is not compiling and my biggest issue is that line 32 compiles but 42 does not and the methods they come from are written exactly the same. The error message is error cannot find symbol.
import java.util.*;
import java.text.*;
public class CourseApp{
public static void main(String[] args){
Scanner s = new Scanner (System.in);
DecimalFormat df = new DecimalFormat("$0.00");
int initialSize;
boolean q = true;
System.out.println("Enter how many courses you would like to enter info rmation for? ");
try{initialSize = s.nextInt();}
catch(NumberFormatException sonic){
while(initialSize <= 0){
System.out.println("Please enter an integer greater than 0 (ie5). ");
initialSize = s.nextInt();}}
ArrayList <Course> courseArrayList = new ArrayList<Course> (initialSize);
String number="";
String name="";
String instr="";
String text="";
for (int i = 0; i < initialSize; i++){
courseArrayList.add(new Course(number, name, instr, text));
System.out.println("Enter in course information. ");
do{
courseArrayList.get(i).setNumber("");
System.out.println("Please enter the course number: ");
courseArrayList.get(i).setNumber(s.nextLine());
}while(courseArrayList.get(i).getNumber().equals(""));
do{
courseArrayList.get(i).setName("");
System.out.println("Please enter the course name: ");
courseArrayList.get(i).setName(s.nextLine());
}while(courseArrayList.get(i).getName().equals(""));
do{
courseArrayList.get(i).setLastName("");
System.out.println("Please enter the Instructor's last name: ");
courseArrayList.get(i).setLastName(s.nextLine());
}while(courseArrayList.get(i).getLastName().equals(""));
do{
courseArrayList.get(i).setFirstName("");
System.out.println("Please enter the Instructor's first name: ");
courseArrayList.get(i).setFirstName(s.nextLine());
}while(courseArrayList.get(i).getFirstName().equals(""));
do{
courseArrayList.get(i).setUserName("");
System.out.println("Please enter the Instructor's user name: ");
courseArrayList.get(i).setUserName(s.nextLine());
}while(courseArrayList.get(i).getUserName().equals(""));
String[] instrr = new String[3];
instrr[0]=courseArrayList.get(i).getLastName()+", ";
instrr[1]=courseArrayList.get(i).getFirstName()+"\n";
instrr[2]=courseArrayList.get(i).getUserName()+"#K-State.ksu";
instr = instrr[0]+instrr[1]+instrr[2];
System.out.println("Please enter the required text book's title: ");
courseArrayList.get(i).setTitle(s.nextLine());
System.out.println("Please enter the required text book's author: ");
courseArrayList.get(i).setAuthor(s.nextLine());
System.out.println("Please enter the required text book's price: ");
try{courseArrayList.get(i).setPrice(s.nextDouble());}
catch(NumberFormatException shadow){
while(courseArrayList.get(i).setPrice(s.nextDouble()) < 0){
System.out.println("Please enter a positive numerical value. ");
courseArrayList.get(i).setPrice(s.nextDouble());}}
String[] textt = new String[3];
textt[0]=courseArrayList.get(i).getTitle()+"\n";
textt[1]=courseArrayList.get(i).getAuthor()+"\n";
textt[2]=df.format(courseArrayList.get(i).getPrice())+"\n";
text = textt[0]+textt[1]+textt[2];}
for (int i = 0; i < initialSize; i++){
System.out.println("Press enter to display each of the courses");
s.nextLine();
courseArrayList.get(i).toString();}
System.out.println("Please enter a course number");
String a = s.nextLine();
for (int i = 0; i < initialSize; i++){
if (a.equals(courseArrayList.get(i).getNumber())){
courseArrayList.remove(i);}
else if (! a.equals(courseArrayList.get(initialSize-1).getNumber())){
do {
System.out.println("Course number not found.");
System.out.println("Please enter a valid course number: ");
a = s.nextLine();
for (int j = 0; j < initialSize; j++){
if (a.equals(courseArrayList.get(j).getNumber())){
q=false;
courseArrayList.remove(j);}}
} while (q=true);}
else {}}
for (int i = 0; i < initialSize; i++){
System.out.println("Press enter to display each of the courses");
s.nextLine();
courseArrayList.get(i).toString();}}}
this is from a different class and this part does not compile
public void setLastName(String lname){
lastName=lname;}
the instructor class is:
public class Instructor
{
private String lastName; // Last name
private String firstName; // First name
private String userName; // Username ID
public Instructor(String lname, String fname, String un){
lastName = lname;
firstName = fname;
userName = un;}
public Instructor(Instructor object2){
lastName = object2.lastName;
firstName = object2.firstName;
userName = object2.userName;}
public void setLastName(String lname){
lastName=lname;}
public String getLastName(){
return lastName;}
public void setFirstName(String fname){
firstName=fname;}
public String getFirstName(){
return firstName;}
public void setUserName(String un){
userName=un;}
public String getUserName(){
return userName;}
public String toString()
{
return str;
}
}
this is from a different class and this part does compile
public void setName(String name){
courseName=name;}
the course class is:
public class Course
{
private String courseNumber; // e.g. CIS 200
private String courseName; // e.g. Programming Fundamentals
private Instructor instructor; // Course instructor (object)
private TextBook textBook; // Required Course textbook (object)
public Course(String number, String name, String instr, String text){
courseNumber = number;
courseName = name;
instructor = new Instructor(instr);
textBook = new TextBook(text);}
public String getName(){
return courseName;}
public void setName(String name){
courseName=name;}
public String getNumber(){
return courseNumber;}
public void setNumber(String number){
courseNumber=number;}
public Instructor getInstructor(){return new Instructor(instructor);}
/**getTextBook method
#return A reference to a copy of this course's TextBook object.*/
public TextBook getTextBook(){return new TextBook(textBook);}
/**toString method
#return A string containing the course information.*/
public String toString(){
String str = courseNumber + " " + courseName+ "\n"+
instr+"\n" +
text;
return str;}}
And finally the TextBook class:
import java.text.*;
import java.util.*;
public class TextBook
{
DecimalFormat df = new DecimalFormat("$0.00");
private String title; // Title of the book
private String author; // Author's last name
private double price; // Wholesale cost of the book
public TextBook(String t, String a, double p){
title = t;
author = a;
price = p;}
public TextBook(TextBook object2){
title = object2.title;
author = object2.author;
price = object2.price;}
public void setTitle(String t){
title=t;}
public void setAuthor(String a){
author=a;}
public void setPrice(String p){
price=p;}
public void getTitle(){
return title;}
public void getAuthor(){
return author;}
public void getPrice(){
return price;}
public String toString(){
String str = "Required Textbook: \n" + " " + title+", " + author + ", " + df.format(price);
return str;}}
why does .setLastName() not work but .setName() does
In your class that has this
public void setLastName(String lname){
lastName=lname;
}
Make sure lastName exists as class variable. I am guessing this should be like:
private String lastName;
If you post your Course.java code, we all would be better equipped to explain what might be missing.

ArrayList Object

I am using the ArrayList Object to create an employee object of type employee...I implement the class and it seems to work, but my problem is that when I insert the employees into the ArrayList it is automatically doesn't insert it. Why is that?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author
*/
import java.util.*;
class Employee {
private String fname;
private String lname;
public Employee (String fname, String lname){
this.fname = fname;
this.lname = lname;
}
public Employee (){
}
public String getLastName(){
return this.lname;
}
public void setLastName(String lname){
this.lname = lname;
}
public String getFirstName(){
return this.fname;
}
public void setFirstName (String fname){
this.fname = fname;
}
public String toString(){
return this.getClass().getName() +" [ "
+ this.fname + " "
+ this.lname + " ]\n ";
}
public Object clone(){ //Object is used as a template
Employee emp;
emp = new Employee(this.fname, this.lname);
return emp;
}
}
//start of main
public class main
{
static Scanner input = new Scanner(System.in);
public static final int MAX_EMPLOYEES = 10;
public static void main(String[] args) {
String fname, lname;
int num;
System.out.print("Enter the number of employees in your system: ");
num = input.nextInt();
ArrayList<Employee> emp = new ArrayList<Employee>(num);
System.out.print("Enter the first name: ");
fname = input.next();
System.out.println();
System.out.print("Enter the last name: ");
lname = input.next();
System.out.println();
for (int x = 1; x < num; x++)
{
System.out.print("Enter the first name: ");
fname = input.next();
System.out.println();
System.out.print("Enter the last name: ");
lname = input.next();
System.out.println();
emp.add(new Employee(fname,lname));
}
num = emp.size();
System.out.println(num);
System.out.println(emp);
}
}
Add:
emp.add(new Employee(fname,lname));
just before your for loop or rewrite your for loop conditional as:
for (int x = 0; x < num; x++)
and get rid of the
System.out.print("Enter the first name: ");
fname = input.next();
System.out.println();
System.out.print("Enter the last name: ");
lname = input.next();
System.out.println();
before the for loop.
Your loop is running 1 less time than is required.
for(int i=0;i<num; i++){
This should fix it.

Categories