arraylist with method - java

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.

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.

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;
}
...
}

Error when trying to add user input to an array

I am quite new to java and am having a problem trying to store user input to an array to later be able to call the list, however I am getting an error when trying to do so. The error comes on the newvoter.add(); line. Sorry if I'm being ignorant in any way, I feel like I'm being stupid!
public class admin {
public static Scanner sc = new Scanner (System.in);
public static List<voter> Voters = new ArrayList<voter>();
public static int promptUserInput() {
System.out.print("\n\tEnter: ");
int option = sc.nextInt();
return option;
}
public static int getOption() {
int option = promptUserInput();
switch(option){
case 1:
addVoter();
break;
case 2:
//deleteVoter();
break;
case 3:
Questions openQuestions = new Questions();
openQuestions.addQuestion();
break;
case 4:
break;
case 5:
System.out.println("Programme Ended");
System.exit(0);
default:
break;
}
return option;
}
public static void main(String[] args) {
printMenu();
}
public static void printMenu(){
System.out.println("\nAdmin Options Menu\n"
+ "\t\nPlease enter an option:\t\n"
+ "\n\t\t1: Create Voter\t\n"
+ "\t\t2:Delete Voter\t\n"
+ "\t\t3:Add Questions\t\n"
+ "\t\t4: View Questions List\t\n"
+ "\t\t5: Delete Question\t\n");
getOption();
}
private static void addVoter(){
voterAdd newvoter = new voterAdd(); // Creates a new voter
System.out.println("Enter First Name: ");
String firstName = sc.next();
System.out.println("Enter Surname Name: ");
String surname = sc.next();
System.out.println("Enter Voter ID: ");
int voterID = sc.nextInt();
System.out.println("Enter City: ");
String city = sc.next();
newvoter.setVoter(firstName, surname, voterID, city);//calls the 'setVoter' method inherited from 'voter'
newvoter.add();//adds the 'newVoter' to the ArrayList 'voter'
System.out.println("\n New voter identification has been created and stored.\n");
listVoters();
}
Here is the class it calls from..
public class voterAdd {
private String firstName = "";
private String surname = "";
private int voterID = 0; //voterID of the voter
private String city = "";
public void setVoter(String firstName, String surname, int voterID, String city) {
this.firstName = firstName;
this.surname = surname;
this.voterID = voterID;
this.city = city;
}
public String getFirstName()
{
return firstName;
}
public String getsurname()
{
return surname;
}
public int getID()
{
return voterID;
}
public String getCity()
{
return city;
}
}
It's Voters.add(newvoter);, not newvoter.add(). Also, variable names should start with a lowercase letter or an underscore. Classes should start with uppercases.
Well one of your problems is that you are calling in your List the voter class, when maybe it should be the voteradd class like such:
List<voteradd> listName = new List<voteradd>();
Another thing, common java principles expect java classes to start with a capital letter(camel case), it's just good conventions and good practice. Hopefully this helped, best of luck :)

Making output match whats needed

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.

Categories