I'm implementing a class called "BorrowerTUI" to an existing project for an assignment. I've been trying for hours and I just can't work out how to add to my ArrayList using the TUI. The information that needs to be added is in a class called "Borrower". Here is the constructor:
public Borrower(String fName, String lName, String lNumber, int numberOfBooks,
String street, String town, String postcode)
{
firstName = fName;
lastName = lName;
libraryNumber = lNumber;
noOfBooks = numberOfBooks;
address = new Address(street, town, postcode);
}
Previously, I added the object to the ArrayList using a different class called "BorrowerList". Here is the method:
public void addBorrower(Borrower borrower)
{
borrowers.add(borrower);
}
That works with no problems. Now what I'm trying to do is use a TUI to add the same information to the same ArrayList. Here is the constructor for "BorrowerTUI" and the options the user will have:
private BorrowerList borrowerList;
private Scanner myScanner;
public BorrowerTUI()
{
myScanner = new Scanner (System.in);
borrowerList = new BorrowerList();
Borrower borrower;
}
private void displayMenu()
{
System.out.println("To add a borrower........................[1]");
System.out.println("To get the total number of borrowers.....[2]");
System.out.println("To remove a borrower.....................[3]");
System.out.println("To show all borrowers....................[4]");
System.out.println("To show a single borrower................[5]");
System.out.println("To close Borrowers.......................[0]");
}
private void addBorrower()
{
borrowerList.addBorrower();
}
That doesn't work and I have tried to implement other solutions with no joy. I tried something along the lines of:
private void addBorrower()
{
myScanner = new Scanner(System.in);
String firstName;
String lastName;
borrower = (firstName, lastName);
System.out.println("Enter your first name: ");
myScanner.nextLine() = firstName;
System.out.println("Enter your last name: ");
myScanner.nextLine() = lastName;
borrowerList.add(borrower);
}
That was a bit of guess work as we haven't actually covered this material in class, we're expected to work it out ourselves having briefly touched on TUIs. Hopefully this is enough information, please let me know if you need me to elaborate or provide any additional code.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have an assignment that goes like this:
Create a program that functions as an address book. It should have entries containing the following information: first and last name, phone number and email address. The entries should be sorted by last name. Every new contact will be inserted in such a way as to maintain the alphabetical order. Upon each change a display of all the entries is required.
Ive read several articles in this site but none of them worked, I tried the sort method but it didnt work.
edit: Hi! I tried your suggestions and its now printing like this, I also updated the code.
[com.mycompany.test.contact#b4c966a, com.mycompany.test.contact#2f4d3709, com.mycompany.test.contact#4e50df2e]
public class NewClass {
String firstname;
int phone;
String email;
int i=0;
public static void main(String[]args){
String lastname;
String firstname;
int phone;
String email;
Scanner scanner = new Scanner(System.in);
contact[] contacts = new contact[3];
for(int i=0; i<contacts.length; i++){
System.out.println("Please enter Last name:");
lastname = scanner.next();
System.out.println("Please enter sFirst name:");
firstname = scanner.next();
System.out.println("Please enter Phone number:");
phone = scanner.nextInt();
System.out.println("Please enter Email address:");
email = scanner.next();
contacts[i] = new contact(lastname,firstname, phone, email);
}
Arrays.sort(contacts);
for (int i=0; i<contacts.length; i++) {
System.out.println(Arrays.toString(contacts));
}
}
}
public class contact implements Comparable {
private String lastname;
private String firstname;
private int phone;
private String email;
public contact(String lastname, String firstname, int phone, String email){
this.lastname=lastname;
this.firstname=firstname;
this.phone=phone;
this.email=email;
}
public String getlastname(){
return lastname;
}
public String getfirstname(){
return firstname;
}
public int phone(){
return phone;
}
public String getlastemail(){
return email;
}
#Override
public int compareTo(contact contact){
return lastname.compareTo(contact.lastname);
}
public String tostring(){
return "Lastname: "+ this.lastname + "Firstname: " + this.firstname + "Phonenumber :" + this.phone + "Email: " + this.email;
}
}
You need to either implement Comparable or Comparator interfaces and override their respective methods.
Also, use TreeSet to maintain the address book. All newly added contacts will be automatically sorted. I have created a quick example:-
import java.lang.Comparable;
import java.util.*;
public class ContactTester{
public static void main(String args[]){
Contact c1 = new Contact("PA" , "GC", "000-987-9876","a#b.com");
Contact c2 = new Contact("VA" , "AA", "000-987-9876","a#b.com");
Contact c3 = new Contact("SA" , "AA", "000-987-9876","a#b.com");
Contact c4 = new Contact("AC" , "AB", "000-987-9876","a#b.com");
TreeSet<Contact> addressBook = new TreeSet();
addressBook.add(c1);
addressBook.add(c2);
addressBook.add(c3);
addressBook.add(c4);
for (Contact c : addressBook)
System.out.println(c.toString());
Contact c5 = new Contact("TT" , "AT", "000-987-9876","a#b.com");
addressBook.add(c5);
for (Contact c : addressBook)
System.out.println("after " + c.toString());
}
}
class Contact implements Comparable<Contact>{
private String firstname;
private String lastname;
private String phoneNumber;
private String email;
public Contact(String firstname, String lastname, String phoneNumber, String email){
this.firstname = firstname;
this.lastname = lastname;
this.phoneNumber = phoneNumber;
this.email = email;
}
#Override
public int compareTo(Contact contact){
int last = this.lastname.compareTo(contact.lastname);
return last ==0 ? this.firstname.compareTo(contact.firstname) : last;
}
#Override
public String toString(){
return "firstname "+ this.firstname + " lastname " + this.lastname + " phoneNumber " + this.phoneNumber + " email " + this.email;
}
}
It's been a while since I did Java programming, but there's a lot of formatting and some syntax advice I could give, but that's not on topic at the moment. I've edited the Q to make some things a little better to read, including putting the code in a code block, if that gets approved.
So first things first:
Your array sort is in the loop, which it shouldn't be. You should only do that after you've done all your input. At least in this case. There may be times when it's appropriate to put a sort in a loop, but not this time.
Secondly:
You also need to move the println outside the loop as well, which means you'll need to create a new loop to display all the contacts. You can reuse the i variable, since it'll be out of scope of the first loop, so there's no problems with mangling other uses of that variable.
You can also take a look at the below Question if you have any questions about that.
List an Array of Strings in alphabetical order
Third:
I said I wasn't going to talk about formatting, but I'll take a brief dive into it. Your contact variable should be a different name than your contact class. Even if that means capitalizing the class name, that should be good enough for most cases, at least while you're still learning. It's not usually good for a seasoned professional, but sometimes it happens anyway. But it should be rare.
Also, you could create a new instance of a blank contact, then simply assign the values directly to that object, instead of having the extra variables. Those variables could retain data that gets leaked to other contact. The below Question shows how to add an element to an existing array. It's about ints, but it works the same for all arrays.
Adding integers to an int array
And this Question is about how to assign to a variable from an object property. It's the opposite of what you're doing, but you just need to reverse the assignment. Their example is double height1 = oldRectangle.height;, so reversing it would be oldRectangle.height = height1;.
How to assign an object property value to a variable in Java?
Since you don't include the contact class definition, I don't know the specifics, but I'll guess that you can do something like this:
Contact newContact = new Contact(); // at the beginning of the loop
...
newContact.LastName = scanner.next();
...
newContact.FirstName = scanner.next();
...
newContact.Phone = scanner.next();
...
newContact.Email= scanner.next();
...
contact.Add(newContact); // at the end of the loop
This also assumes that a new contact doesn't require those parameters and you can just create a blank contact. If it does require those params, you can still do it but instead do new Contact("", "", "", "");. It might annoy your instructor, or it might be a requirement of the assignment to use variables and the current instantiation, with my suggestions being ahead of your current learning point.
Hmm, that wasn't so brief. Sorry. I'm sure your prof/teacher/instructor will teach you more about proper formatting and other Best Practices later, so I really won't go further than I already have.
I'm new to java and programming. I am stuck on one section of an assignment given to me in which I have to create a login for two different types of user which will display two different menus depending on which login is used. I am using Eclipse and the console.
The two different types of user are Boss and Worker and they must login using a username and password. The Boss menu must have the following menu options after logging in:
Setup Worker Schedule
View Worker Schedule
Move Worker
The Worker menu must have the following menu options after logging in:
View Schedule
I'd really appreciate any help with this, thanks in advance.
EDIT:
Okay, so I now have the following code:
import java.util.Scanner;
public class Depot {
public static void main(String[] arguments){
String bossName;
String bossPassword;
String workerName;
String workerPassword;
System.out.println("Enter your name: ");
Scanner authenticate = new Scanner(System.in);
String userName = authenticate.nextLine();
System.out.println("Your username is " + userName);
System.out.println("Enter your password: ");
String passWord = authenticate.nextLine();
System.out.println("Your password is " + passWord);
if (userName.equals(bossName) && passWord.equals(bossPassword)) {
int selection;
Scanner bossMenu = new Scanner(System.in);
System.out.println("1. Setup Worker Schedule");
System.out.println("2. View Worker Schedule");
System.out.println("3. Move Worker");
System.out.println("4. Quit");
do {
selection = bossMenu.nextInt();
if (selection == 1) {
System.out.println("1");
}
else if (selection == 2) {
System.out.println("2");
}
else if (selection == 3) {
System.out.println("3");
}
else {
System.out.println("4");
}
}
while(selection != 4);
bossMenu.close();
}
else if (userName.equals(workerName) && passWord.equals(workerPassword)) {
int selection;
Scanner userMenu = new Scanner(System.in);
System.out.println("1. View Worker Schedule");
System.out.println("2. Quit");
do {
selection = userMenu.nextInt();
if (selection == 1) {
System.out.println("1");
}
}
while(selection != 2);
userMenu.close();
}
}
}
However, the following two lines of code are giving me an error:
if (userName.equals(bossName) && passWord.equals(bossPassword)) {
and
else if (userName.equals(workerName) && passWord.equals(workerPassword)) {
bossName, bossPassword, workerName and workerPassword may not have been initialized?
First, get the credentials through using the Scanner, here is a basic way to construct a Scanner object, you will need to have the following import statement at the very beginning of your code, before anything else:
import java.util.Scanner;
To create a Scanner, do the following:
Scanner scannerName = new Scanner(System.in);
That tells the Scanner to read from the input stream, which will be the keyboard. To get data from the Scanner, first prompt the user for the data you need, then use one of the Scanner's .next___ methods to retrieve the input and store in a variable. I'm not going to tell you which one to use, check out the Scanner page in the Java API and see if you can figure it out on your own.
It should look something like this:
System.out.println("Enter your name");
String userLoginString = scannerName.next____();
System.out.println("Enter your password");
String userPasswordString = scannerName.next____();
Once you have the credentials stored in String variables, I'll use userLoginString and userPasswordString as examples, you will need to validate these credentials against some stored values. So, create String variables bossName, bossPassword, workerName, workerPassword.
Once you have the user's credentials, I would perform validation on these login credentials. You could do that using the logical operators and methods of the String class, like so:
if (userLoginString.equals(bossName) && userPasswordString.equals(bossPassword)) {
// print the boss menu
}
else if (userLoginString.equals(workerName) && userPasswordString.equals(workerPassword)) {
// print the user menu
}
The logical && ("and") operator will ensure that the correct menu will be displayed only if the user's credentials match the stored credentials. If the user enters the correct name (boss or worker) but the wrong password (or vice-versa), the statements inside the braces will NOT execute.
UPDATE Here is a commented version of your code so far with some hints as to how to make it better. It will compile and run fine if you just provide values for the String variables at the top, but I have some more suggestions to make it a little nicer:
import java.util.Scanner;
public class Depot {
public static void main(String[] arguments){
// you need to initialize these to some value or else there is
// nothing to compare them with. I tried some dummy values and
// your code worked as expected, as long as the user entered the
// correct values in the prompt.
String bossName;
String bossPassword;
String workerName;
String workerPassword;
// you can just use one Scanner for the whole program, since they are
// both just reading input from the standard input stream. Replace the
// other Scanners with "input" and close "input" at the end
Scanner input = new Scanner(System.in);
System.out.println("Enter your name: ");
// not needed
Scanner authenticate = new Scanner(System.in);
String userName = authenticate.nextLine();
System.out.println("Your username is " + userName);
System.out.println("Enter your password: ");
String passWord = authenticate.nextLine();
System.out.println("Your password is " + passWord);
if (userName.equals(bossName) && passWord.equals(bossPassword)) {
// this could be declared at the top of the program instead of
// redeclaring in the if...else
int selection;
Scanner bossMenu = new Scanner(System.in);
System.out.println("1. Setup Worker Schedule");
System.out.println("2. View Worker Schedule");
System.out.println("3. Move Worker");
System.out.println("4. Quit");
do {
selection = bossMenu.nextInt();
if (selection == 1) {
System.out.println("1");
}
else if (selection == 2) {
System.out.println("2");
}
else if (selection == 3) {
System.out.println("3");
}
else {
System.out.println("4");
}
} while(selection != 4); // this is usually here
bossMenu.close();
}
else if (userName.equals(workerName) && passWord.equals(workerPassword)) {
// this could be declared at the top of the program instead of
// redeclaring in the if...else
int selection;
// don't need this one, just use "input" Scanner
Scanner userMenu = new Scanner(System.in);
System.out.println("1. View Worker Schedule");
System.out.println("2. Quit");
do {
selection = userMenu.nextInt();
if (selection == 1) {
System.out.println("1");
}
} while(selection != 2); // this is usually here
// you would close the "input" Scanner here
userMenu.close();
}
}
}
UPDATED AGAIN!!! A better way to implement the Boss and Worker would be through using inheritance and polymorphism. Start with an abstract superclass that has common characteristics of the Boss and Worker. I'll call this the Employee superclass. It has firstName, lastName, and password instance variables, and you should add getters and setters for each:
// abstract class, CANNOT be instantiated but can be used as the supertype
// in an ArrayList<Employee>
public abstract class Employee {
private String firstName;
private String lastName;
private String password;
public Employee() {
// don't have to do anything, just need this so you can instantiate
// a subclass with a no-arg constructor
}
// constructor that takes only the name of the Employee
public Employee(String firstName, String lastName) {
this(firstName, lastName, null);
}
// constructor that takes name and password
public Employee(String firstName, String lastName, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
// and so on, for the lastName and password....
// you must implement this specifically in any subclass!
public abstract void getMenu();
}
Then, your Boss and Worker classes could extends this Employee class and they would have all of the same methods and instance variables. You just must provide an overridden getMenu() method in each, since that one was abstract in the Employee class. Here is a sample of what your Boss class should look like, you need to implement the getMenu() yourself and the Worker class:
public class Boss extends Employee {
// notice we don't need the instance variables in the class declaration,
// but they are here since they are part of Employee
public Boss() {
// don't need to do anything here, just allows no-arg constructor
// to be called when creating a Boss
}
// just calls the superclass constructor, could do more if you want
public Boss(String firstName, String lastName) {
super(firstName, lastName);
}
// just calls the superclass constructor, could do more if you want
public Boss(String firstName, String lastName, String password) {
super(firstName, lastName, password);
}
#Override
public void getMenu() {
// put the print statment for Boss's menu here
}
// don't need to re-implement other methods, we can use them since
// they are part of the superclass
}
Once you have the Employee, Worker, and Boss classes, you're ready to try and re-write your program to Objects in place of simple variables as you were doing before. Here is an example of how that would get started:
import java.util.Scanner;
public class EmployeeTester {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// can make workers and bosses able to be processed polymorphically
// by assinging their references to Employee variables, since
// and Employee is the supertype of each, a Worker "is an" Employee
// and a Boss "is an" Employee.
Employee worker1 = new Worker("Bob", "Worker");
Employee worker2 = new Worker("Sue", "Bush", "Password1");
Employee worker3 = new Worker();
Employee boss1 = new Boss("Jenny", "Boss");
Employee boss2 = new Boss("Bill", "OtherBoss", "Password2");
Employee boss3 = new Boss();
// if you're going to have a lot of workers and bosses, and you don't
// need named variables for each because their info will be included
// in their constructors, you could do this
Employee[] employees = {new Worker("Bob", "Bailey", "myPassword"),
new Worker("Sue", "Sarandon", "123Seven"),
new Boss("Jenny", "Strayhorn", "hardPassword"),
new Boss("Billy", "MeanGuy", "pifiaoanaei")};
// then, you could iterate through this list to check if a password
// entered matches a firstName, lastName, and password combination
// for ANY type of employee in the array, then call the getMenu()
// method on that employee, like so: (This could all be in a loop
// if you wanted to process multiple Employees...)
System.out.println("Enter firstName:");
// you figure out which Scanner method to use!
String firstName = input._____();
System.out.println("Enter lastName:");
String lastName = input._____();
System.out.println("Enter password:");
String password = input._____();
// figure out what get____() method of the Employee class
// needs to be called in each case, and what it should be
// compared to with the .equals() method.
for (int i = 0; i < employees.length; i++) {
if (employees[i].get______().equals(______) &&
employees[i].get______().equals(______) &&
employees[i].get______().equals(______)) {
// if all of those conditions are true, print the menu
// for this employee
employees[i].get_____();
// you could do more stuff here....
// breaks out of the loop, no need to check for anymore employees
break;
}
}
}
}
I have this method addPerson (on the main) which is used to set the name of a person.
private static Person[] addPerson(Person _person[], int _minAge, int _id){
int personAge;
String personName;
Scanner scan = new Scanner(System.in);
System.out.println("What's his age?");
personAge = scan.nextInt();
if(personAge >= _minAge){
if(!_person[_id].getPerson().equals("")){
System.out.println("Person " + _person[_id].getPerson() + " already exists.");
}else{
System.out.println("Enter the name of the person");
Scanner addPerson = new Scanner(System.in);
personName = addPerson.next();
_person[_id].setPerson(personName);
}
}else{
System.out.println("Person is not old enough");
}
return _person;
}
And here is the method setPerson in my custom class which is used to set the name of the person.
public void setPerson(String name){
System.out.println("Person added");
personName = name;
}
I know I should be doing the checking on whether that person already exists inside my setPerson method, but I am sort of confused with this. As you see I am expecting the user to input an integer, so I guess that I should check that right away to not get an error in case he inputs a string.
So my question is which should be checked within the same method and which on the method on my custom class?
Your code (and your question) is a bit confusing, but from what I can understand you want to know if you should check whether a person exists in the array in setPerson() or not?
Well, from what I can gather from your code, you should not do it in setPerson(), because that's a method in the Person class. The Person class shouldn't need to know anything about your array of Person objects.
So the way you're doing it now is probably your best bet.
Some general hints about the code:
There's no need to create a new Scanner, you can just use the one you have. So this
Scanner addPerson = new Scanner(System.in);
personName = addPerson.next();
becomes this
personName = scan.next();
I would also suggest you use the name setName()instead of setPerson()for your method name, it doesn't make sense to have it named one way when what it's actually doing is something else.
I would do it this way. However I don't have java currently so I didn't test this snippet.
class Person {
private String name;
public void setName(String name) {
this.name = name;
}
}
class Main {
private static final int minAge = 22;
private static Map<Person> addPerson(Map<Person> people, int id) {
if(people.containsKey(id)) {
// print that person with this id exists
return people;
}
Scanner scanner = new Scanner(System.in);
int age = scanner.nextInt();
if(age < minAge) {
// print that given age is invalid
return people;
}
String name = scanner.next();
people.get(id).setName(name);
return people;
}
}
I'm creating a banking app and I need to generate a customer number starting from number 1, keeping track of the number so that it won't repeat itself each time I enter the loop and store it into an int variable that I can use to collect the value and pass it to the customerNumber variable outside the loop. I've tried a few things like arraylists and arrays, but I was getting troubles in passing the values to the variable I wanted. Thanks in advance and sorry for my terrible noobishness...I'm new in programming... Here's what I've got so far:
import java.util.ArrayList;
public class Bank{
public void addCustomer(String name, int telephone, String email, String profession) {
ArrayList customerList = new ArrayList();
Customer customer = new Customer();
customerList.add(customer);
}
}
public class Customer{
private String name;
private int telephone;
private String email;
private String profession;
private int customerNumber;
public Customer() {
}
}
public class Menu {
Scanner sc = new Scanner(System.in);
Bank bank = new Bank();
private void createCustomer() {
String name, email, profession;
int telephone, customerNumber;
System.out.println("Enter the customer's number: ");
name = sc.nextLine();
System.out.println("Enter the customer's telephone: ");
telephone = sc.nextInt();
System.out.println("Enter the customer's email: ");
email = sc.nextLine();
System.out.println("Enter the customer's profession: ");
profession = sc.nextLine();
bank.addCustomer(name, telephone, email, profession);
}
}
One thing you can do is create a singleton class, and request a number each time you need one. The singleton class keeps a list of the numbers that have been used already, and thus can return a number that has not been used before.
If you need also to generate new numbers after your application is restarted, then you can store all numbers in a file, and read that file whenever needed.
A singleton class, is a class that can have max 1 instance. You can achieve this by making the constructor private, and creating a public static method (usually called something like getInstance() ) to get an instance of this class. This getInstance() returns the ref to the only instance, and if no instance was created yet, it first creates one.
Then, this only instance knows all account numbers in use (inyour case), regardless how often an instance of this class is requested.
The responsibility of this class is to maintain the account nrs: create a nr, print them, save them, read them, ...
Example:
private AccoutnNr singleInstance;
private AccountNr(){
}
public AccountNr getInstance(){
if (singleInstance == null) {
singleInstance = new AccountNr();
}
return singleInstance;
}
public int getAccountNr{
// do whatever is needed to create an account nr
}
more methods if you need to do more than creating account numbers
I am writing this program that will take in the names, ages and salaries for 5 different people from the user and will put them in an array.
I then want to write a method that will ask the user for another name, age and salary and add that into the array. Also a method that will as for the name of someone who's already in the array and will delete the information of the person with that age from the array.
The first method will increase the array size by 1 and the second will decrease the array size by 1. so far this is what I have:
ArrayList<details> details = new ArrayList<details>();
for(int x = 0; x < 4; x++) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name: ");
String firstName = scan.nextLine();
System.out.println("Enter the last name: ");
String lastName = scan.nextLine();
System.out.println("Enter the age: ");
int age = scan.nextInt();
System.out.println("Enter the salary: ");
double salary = scan.nextDouble();
details.add (new details(firstName, lastName, age, salary));
}
I don't know how to go about doing this. I need some help!
thanks!
You can have a class Person with the class variables you require (name,age,salary)
class Person {
private int age;
private dobule salary;
private String firstname;
private String lastname;
}
Define the getter and setter methods for each of the class variables. For e.g
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
In your main class read the input from STDIN as you are doing it. Instantiate the Person object for each of the 5 person.
Person employee = new Person();
employee.setAge(x);
employee.setFirstName(x);
employee.setLastName(y);
employee.setSalary(y);
Now, you can add each Person to your list and remove them too.
For removing any Person you would have to search for the Person through the ArrayList by name. That would be iterating over the length of ArrayList and comparing the name of each.
The final class would look like,
public class Solution{
private ArrayList<Person> details = new ArrayList()<Person>;
public static void main(){
// Here you loop for reading from STDIN as you are already doing.
// addPerson() would be used to add to ArrayList and removePerson() for the other
}
public addPerson(String firstName, String lastName, int age, int salary){
//Create the Person object
details.add(<person object>);
}
public removePerson(name){
details.remove(index);
// to get index it would require iterating over the ArrayList.
// It would be better if you use a Map instead (as other suggest)
// with name as the key
}
}
Hope this helps.
dud first of all, i can see that u have used arrayList name & Class name both same so please update that.
secondary use Map in place of Class like in if condition
if(){
Map userDetails = new HashMap();
map.put("firstname",firstname);
..
..
map.put("salary",scan.nextDouble());
details.add(map)
}
and on time of delete iterate ArrayList
for(int i=0;i<details.size();i++){
Map tempMap = details.get(i);
if(temp.get("firstname").toString() == "Given Name"){
}else{
// your logic
}
}
Hope will help you please let me know if any doubts.
use this code for removing employee
void removeEmployee(String name){
for(Employee emp :details){
if(name.equals(emp.getName())){
details.remove(emp);
break;
}
}
}
and do include exception handling