Java - Adding to an Array using copyOf - java

I'm doing an assignment for class which requires me to create an array and add to it as the user wishes. Here's what I have so far:
public void add(Scanner stdIn)
{
entries = new String[1];
Contact add = new Contact(); // Instantiate new Contact instance
String name;
System.out.print("Enter the contact's name: ");
name = stdIn.next();
add.setName(name); // set name in Contact class
String address;
System.out.print("Enter the contact's address: ");
address = stdIn.next();
add.setAddress(address); // set address in Contact class
String phone;
System.out.print("Enter the contact's phone number: ");
phone = stdIn.next();
add.setPhone(phone); // set phone number in Contact class
String email;
System.out.print("Enter the contact's email address: ");
email = stdIn.next();
add.setEmail(email); // set email address in Contact class
final int N = entries.length;
entries = Arrays.copyOf(entries, N + 1);
entries[0] = add.toString();
System.out.print(Arrays.toString(entries));
} // end add
I am not too familiar with using arrays, so trying to copy the old array and create a new array with the old information, as well as add new information is alluding me. The toString method looks like this:
#Override // Overrides method from java.lang.Object
public String toString() // Displays the info for a contact in order
{
return getName() + "\t" + getAddress() + "\t" + getPhone() +
"\t" + getEmail();
}
If you need any more clarification, let me know! Thanks for the help!

As I mentioned in your comment, you need to define the array (could use an ArrayList instead) outside of the method or it will go out of scope and the data will be lost between calls to the add method.
Here is sample code showing how to make multiple calls to add(), each time expanding the array by 1 and printing the result:
import java.util.Arrays;
import java.util.Scanner;
public class ArrayCopy {
String[] entries = new String[0];
public void add(Scanner stdIn)
{
entries = Arrays.copyOf(entries, entries.length + 1);
Contact add = new Contact(); // Instantiate new Contact instance
String name;
System.out.print("Enter the contact's name: ");
name = stdIn.next();
add.setName(name); // set name in Contact class
String address;
System.out.print("Enter the contact's address: ");
address = stdIn.next();
add.setAddress(address); // set address in Contact class
String phone;
System.out.print("Enter the contact's phone number: ");
phone = stdIn.next();
add.setPhone(phone); // set phone number in Contact class
String email;
System.out.print("Enter the contact's email address: ");
email = stdIn.next();
add.setEmail(email); // set email address in Contact class
entries[entries.length-1] = add.toString();
System.out.println(Arrays.toString(entries));
} // end add
public static void main(String[] args) {
ArrayCopy program = new ArrayCopy();
Scanner scan = new Scanner(System.in);
String op = "";
System.out.println("Press A to add a user or E to exit.");
while(!(op = scan.nextLine()).equalsIgnoreCase("E")){
switch(op){
case "A":
program.add(scan);
break;
case "E":
System.out.println("Good Bye.");
System.exit(0);
}
}
}
}

Related

User input to update variables when multiple objects involved

I'm currently learning java and starting on methods, classes and objects. I'm attempting to code a simple program to have set values for 2 separate employee's at a company that would then allow for user input to alter certain variables of a specific object. The variables needing to be updated via user input will be the MonthlySalary and FirstName of the object employee2. I'm not really sure how to structure the user input part and I'm at a loss trying to find a solution.
import java.util.Scanner;
public class EmployeeTest
{
public static void main( String[] args ){
Scanner input = new Scanner(System.in);
// Create 2 Employee objects
Employee employee1 = new Employee( "Jane", "Doe", 5000 );
Employee employee2 = new Employee( "John", "Bloggs", 4500 );
// Do other steps (not requiring input)
// Ask for user input of Employee 2's new first name
System.out.println( "Please enter new first name for Employee 2: \n");
String input = employee2.newFirstName();
// repeat above to set Employee 2's new salary then display new information
}
}
With the Class file Employee.java
public class Employee
{
private String firstName; // Employee's First Name
private String lastName; // Employee's Last Name
private double monthlySalary; // Employee's Monthly Salary
// Employee constructor
public Employee( String initFirstName, String initLastName, double initMonthlySalary )
{
firstName = initFirstName;
lastName = initLastName;
if (initMonthlySalary > 0)
monthlySalary = initMonthlySalary;
else
monthlySalary = 0;
}
public Employee( )
{
firstName = "";
lastName = "";
monthlySalary = 0;
}
// Method to assign the employee's First Name
public void setFirstName( String newFirstName )
{
firstName = newFirstName;
}
// Method to assign the employee's Monthly Salary
public void setMonthlySalary( double newMonthlySalary )
{
if (newMonthlySalary > 0) monthlySalary = newMonthlySalary;
}
// Other required methods
}
You are struggling to take input from the console.
System.out.println("Please enter new first name for Employee 2: ");
String firstName = input.next();
employee2.setFirstName(firstName);
System.out.println("Please enter new Salary for Employee 2: ");
double salary = input.nextDouble();
employee2.setMonthlySalary(salary);
This will work for you. And please go through the basic syntaxes first. Because otherwise you are wasting your own time banging your head for this kind of syntactical doubts.

How do I store new client information in array and be able to view it again in java?

This is my assignment.
I have to create an application that show a menu and perform the corresponding action based on the user's choice. Here is what my menu should include
1. add a new client - keep it as the current client
2. find a client with a given name - keep it as the current client
3. add a service for the current client
4. print the current client's balance
5. print the current client's history of services
6. print all the clients' balances
7. exit [save all the data to a file option and retrieve it back when the program starts]
System.out.println("Welcome to Tracy'S Auto Mechanic Shop!");
do{
System.out.println("\nTracy's Auto Mechanic Shop Main Menu");
System.out.println("------------------------------------");
for(int i = 0; i < choices.length; i++){
System.out.println((i < choices.length-1? ? i+1 : 0) + ". " + choices[i]);
}
System.it.print("Make your choice: ");
choice = input.nextInt();
switch(choice){
case 1:
main_addNewClient();
break;
case 2:
main_SearchClient();
break;
case 3:
main_AddService();
break;
case 4:
main_ViewBalance();
break;
case 5:
main_ViewHistory();
break;
case 6:
main_ViewAll();
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice. Try again.");
}
}while(choice != 0);
input.close();
}
So far I have created the menu but I am stuck at adding a new client. How do I store all information into an array and save it? I created a class as shown at the bottom:
class Client{
public String name;
public String email;
public String make;
public int year;
public String vin;
public static void Client(String name, String email, String make, int year, String vin){
this.name = name;
this.email = email;
this.make = make;
this.year = year;
this.vin = vin;
}
}
For the option of adding a new client, I created a method in main
public static void main_addNewClient() {
String name, email, vin, make;
int year;
input.nextLine();
System.out.print("Enter your first name: ");
name = input.nextLine();
System.out.print("Enter your email: ");
email = input.nextLine();
System.out.print("Enter vin: ");
vin = input.nextLine();
System.out.print("Enter make: ");
make = input.nextLine();
System.out.print("Enter year: ");
year = input.nextLine();
but how do I take all the user input and store it into an array? I'm not sure where to begin.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Exercise {
// list to store your clients
static List<Client> clients = new ArrayList<>();
static class Client{
public String name;
public String email;
public String make;
public int year;
public String vin;
Client(String name, String email, String make, int year, String vin){
this.name = name;
this.email = email;
this.make = make;
this.year = year;
this.vin = vin;
}
}
public static void main_addNewClient() {
String name, email, vin, make;
int year;
Scanner input = new Scanner(System.in);
input.nextLine();
System.out.print("Enter your first name: ");
name = input.nextLine();
System.out.print("Enter your email: ");
email = input.nextLine();
System.out.print("Enter vin: ");
vin = input.nextLine();
System.out.print("Enter make: ");
make = input.nextLine();
System.out.print("Enter year: ");
year = input.nextInt();
// create new client object with input you got
Client c = new Client(name, email, make, year, vin);
// add client to the list
clients.add(c);
}
}
Is that what you wanted to know? There is lots into this exercise. I think you first need to build a menu which will ask a user what he wants to do: add new client, find a client, etc.
First, declare an ArrayList in your main which will contain all the clients
ArrayList clients = new ArrayList<Client>();
Second, create a new client object within your method and fill with the data you get from the input then add this client data to the ArrayList you have created
Client client = new Client(name,email,vin,year,make);
clients.add(client);

display an entire arraylist in java

I'm still pretty new to java. Am trying to make a program that basically adds contacts to an array list. I have figured everything out as far as creating a new object and setting the name/number. As far as I can tell it's adding it to the array, however I'm not sure how I can display the array? I want to add a snippet of code that would display the array list after you add each contact.
Here is my contact class, not sure if I need the PhoneBook method or not for the array....
public class Contact {
String first; //first name
String last; //last name
String phone; //phone number
String PhoneBook; //array list???
public void PhoneBook(String f, String l, String p) {
first = f;
last = l;
phone = p;
}
public void setFirst(String first) {
this.first = first;
}
public void setLast(String last) {
this.last = last;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Contact makeCopy() {
Contact Contact = new Contact();
Contact.first = this.first;
Contact.last = this.last;
Contact.phone = this.phone;
return Contact;
} //end makeCopy
} //end class Computer
Here is my driver class...
import java.util.Scanner;
import java.util.ArrayList;
public class contactDriver {
public static void main(String[] args) {
Contact Contact = new Contact(); //make default Contact
Contact newContact;
String first; //first name
String last; //last name
String phone; //phone number
String input; //answer to create a new contact
boolean add = true; //boolean to add new contact
Scanner scan = new Scanner(System.in);
Contact.setFirst("Default");
Contact.setLast("Default");
Contact.setPhone("Default");
while (add) {
System.out.println("Would you like to create a new contact? (Y/N)");
input = scan.nextLine();
if (input.equals("Y") || input.equals("y")) {
newContact = Contact.makeCopy();
System.out.println("Enter the contact's first name: ");
first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
last = scan.nextLine();
System.out.println("Enter the contact's phone number: ");
phone = scan.nextLine();
ArrayList < Contact > PhoneBook = new ArrayList();
newContact.setFirst(first);
newContact.setLast(last);
newContact.setPhone(phone);
PhoneBook.add(newContact);
} else {
add = false;
System.out.println("Goodbye!");
break;
}
}
} //end main
} //end Class ComputerDriver
If just for printing, override the toString method of your Contact class, which will be like:
#Override
public String toString() {
return first + " " + last + "; phone number: " + phone;
}
Then, in your main method, print all the contacts by doing:
for (Contact c : phoneBook) {
System.out.println(c);
}
Also, you should create the phoneBook, which is an ArrayList outside of your loop.
Your Contact class should be defined as:
public class Contact {
private String first; // first name
private String last; // last name
private String phone; // phone number
public Contact(String f, String l, String p) {
first = f;
last = l;
phone = p;
}
public String getFirst() {
return first;
}
public String getLast() {
return last;
}
public String getPhone() {
return phone;
}
public Contact makeCopy() {
return new Contact(first, last, phone);
}
#Override
public String toString() {
return first + " " + last + "; phone number: " + phone;
}
}
And your main method should be:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<Contact> phoneBook = new ArrayList<>();
while (true) {
System.out.println("Would you like to create a new contact? (Y/N)");
String input = scan.nextLine();
if (input.equalsIgnoreCase("Y")) {
System.out.println("Enter the contact's first name: ");
String first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
String last = scan.nextLine();
System.out.println("Enter the contact's phone number: ");
String phone = scan.nextLine();
Contact contact = new Contact(first, last, phone);
phoneBook.add(contact);
for (Contact c : phoneBook) {
System.out.println(c);
}
} else {
System.out.println("Goodbye!");
break;
}
}
scan.close();
}
The compiler will give warning, most likely because of this:
String PhoneBook;
when you know that you also have
public void PhoneBook(String f, String l, String p)
and even more another PhoneBook
ArrayList < Contact > PhoneBook = new ArrayList();
try to use another variable name and function name to be safe and make sure they are different especially for
String PhoneBook;
public void PhoneBook(String f, String l, String p)
since they are under same class.
In terms of data structure, you have a wrong concept here. first is, this:
ArrayList < Contact > PhoneBook = new ArrayList();
should be outside the while loop so for whole your application, you will not replace your phone book after looping. to print them, later just use
for(int i = 0; i < phoneBook.size(); i++)
your printing
You just override toString() method of your Contact class, and in main() method, directly call your ArrayList's toString().
Here is my example:
package somepackage;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<Inner> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Inner in = new Inner("name" + i, "address" + i);
list.add(in);
}
System.out.println(list.toString());
}
private static class Inner {
private String name;
private String address;
Inner(String name, String address) {
this.name = name;
this.address = address;
}
#Override
public String toString() {
return "name:" + name + ", " + "address: " + address + "\n";
}
}
}
Screen outputs:
[name:name0, address: address0
, name:name1, address: address1
, name:name2, address: address2
, name:name3, address: address3
, name:name4, address: address4
, name:name5, address: address5
, name:name6, address: address6
, name:name7, address: address7
, name:name8, address: address8
, name:name9, address: address9
]
Ok, figured it out thanks to your guys help! I changed the if statement so you can now add a new contact, display the phone book, or quit. I also added phone number validation! Here is the updated code if anyone cares!
import java.util.Scanner;
import java.util.ArrayList;
public class contactDriver {
public static void main(String[] args) {
String first; //first name
String last; //last name
String phone = ""; //phone number
String input; //answer to create a new contact
boolean add = true; //boolean to add new contact
boolean phoneValid; //boolean to validate phone number
Scanner scan = new Scanner(System.in);
ArrayList < Contact > PhoneBook = new ArrayList < > ();
while (add) {
phoneValid = false;
System.out.println("Type (N) to add a new contact, (D) to display your phonebook, or (Q) to quit!");
input = scan.nextLine();
if (input.equalsIgnoreCase("N")) {
System.out.println("Enter the contact's first name: ");
first = scan.nextLine();
System.out.println("Enter the contact's last name: ");
last = scan.nextLine();
while (!phoneValid) {
System.out.println("Enter the contact's phone number: XXX-XXX-XXXX");
phone = scan.nextLine();
if (phone.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) {
phoneValid = true;
break;
} else {
System.out.println("Sorry, I didn't catch that!");
}
}
Contact contact = new Contact(first, last, phone);
PhoneBook.add(contact);
} else if (input.equalsIgnoreCase("Q")) {
add = false;
System.out.println("Goodbye!");
break;
} else if (input.equalsIgnoreCase("D")) {
for (Contact c: PhoneBook) {
System.out.println(c);
}
} else {
System.out.println("Sorry, I didn't catch that!");
}
}
} //end main
} //end Class ComputerDriver
It sounds like you need to create some Getters. Most IDE's will do this for you.
For example, in your contact class add this:
public String getFirst(){ return first; }
Then do that for all of the items you want. When you want to print them out, set up a for each loop in your driver class like this:
for(Contact contact : PhoneBook){
System.out.println("Contact details: " + contact.getFirst() + " " + contact.getLast() + ", Phone #: " + contact.getPhoneNumber());
}
Alternatively, you could also create a method in you contacts class that takes the println contents from above and spits it out. For example:
public void printContactDetails(){ System.out.println("...");}
then in your for each loop call: contact.printContactDetails();

Simple output issue

So in my class we're making simple programs and we're introducing inheritance. I've gotten everything to work properly, but I can't get this one bit of output to work correctly. It's when I'm asking for an input, but it skips one of my inputs and goes to the request for the second one. When I comment all the other things before that aren't needed, it doesn't skip the first input. I don't understand why this is, and if someone could help me decipher why it would be much appreciated. Thanks in advance and here are my two classes followed by the tester:
Person class:
public class Person{
private String name, address, phoneNumber;
public Person(){
name="none";
address="none";
phoneNumber="none";
}
public Person(String inName, String inAddress, String inPhoneNumber){
name=inName;
address=inAddress;
phoneNumber=inPhoneNumber;
}
public String getName(){
return name;
}
public void setName(String newName){
name = newName;
}
public String getAddress(){
return address;
}
public void setAddress(String newAddress){
address = newAddress;
}
public String getPhoneNumber(){
return phoneNumber;
}
public void setPhoneNumber(String newPhoneNumber){
phoneNumber = newPhoneNumber;
}
public String toString(){
return String.format("Name: " + name + "\nAddress: " + address + "\nPhone Number: " + phoneNumber);
}
public void clearPerson(){
name="none";
address="none";
phoneNumber="none";
}
}
Customer class:
public class Customer extends Person{
private int customerNumber;
private boolean mailingList;
public Customer(){
customerNumber=0;
mailingList=false;
}
public Customer(int inCustomerNumber, boolean inMailingList){
customerNumber=inCustomerNumber;
mailingList=inMailingList;
}
public int getCustomerNumber(){
return customerNumber;
}
public void setCustomerNumber(int newCustomerNumber){
customerNumber=newCustomerNumber;
}
public boolean getMailingList(){
return mailingList;
}
public void setMailingList(boolean newMailingList){
mailingList=newMailingList;
}
public String toString(){
return "Customer Number: "+customerNumber+"\nMailing List: "+mailingList+"\n";
}
public void clearCustomer(){
customerNumber=0;
mailingList=false;
}
}
Tester class:
import java.util.*;
public class CustomerPersonTester{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
Person testP1 = new Person();
Customer testC1 = new Customer();
System.out.println("Empty paramaters constructed on Person and Customer. Results: ");
System.out.println(testP1.toString());
System.out.println(testC1.toString());
/*System.out.println(testP1.getName());
System.out.println(testP1.getAddress());
System.out.println(testP1.getPhoneNumber());
System.out.println(testC1.getCustomerNumber());
System.out.println(testC1.getMailingList());*/
System.out.println("Expected: none x3, 0, false.\n");
System.out.print("Enter a new name: ");
String newName = in.nextLine();
System.out.print("Enter a new address: ");
String newAddress = in.nextLine();
System.out.print("Enter a new phone number: ");
String newPhoneNumber = in.nextLine();
System.out.print("Enter a new customer number: ");
int newCustomerNumber = in.nextInt();
System.out.print("Enter a new true/false for mailing list: ");
boolean newMailingList = in.nextBoolean();
testP1.setName(newName);
testP1.setAddress(newAddress);
testP1.setPhoneNumber(newPhoneNumber);
testC1.setCustomerNumber(newCustomerNumber);
testC1.setMailingList(newMailingList);
System.out.println(testP1.toString());
System.out.println(testC1.toString());
/*System.out.println(testP1.getName());
System.out.println(testP1.getAddress());
System.out.println(testP1.getPhoneNumber());
System.out.println(testC1.getCustomerNumber());
System.out.println(testC1.getMailingList());*/
System.out.println("Expected: given name/address/phone number/customer number/boolean.\n");
testP1.clearPerson();
testC1.clearCustomer();
System.out.println("\nTest 1 Complete. Values are reset. Please continue.\n");
System.out.print("Enter a name: ");
String inName = in.nextLine();
System.out.print("Enter an address: ");
String inAddress = in.nextLine();
System.out.print("Enter a phone number: ");
String inPhoneNumber = in.nextLine();
System.out.print("Enter a customer number: ");
int inCustomerNumber = in.nextInt();
System.out.print("Enter true/false for mailing list: ");
boolean inMailingList = in.nextBoolean();
Person testP2 = new Person(inName, inAddress, inPhoneNumber);
Customer testC2 = new Customer(inCustomerNumber, inMailingList);
System.out.println(testP2.toString());
System.out.println(testC2.toString());
/*System.out.println(testP2.getName());
System.out.println(testP2.getAddress());
System.out.println(testP2.getPhoneNumber());
System.out.println(testC2.getCustomerNumber());
System.out.println(testC2.getMailingList());*/
System.out.println("Expected: given name/address/phone number/customer number/boolean.\n");
System.out.println("Program complete. Terminating...");
in.close();
}
}
My output keeps looking like this:
Empty paramaters constructed on Person and Customer. Results:
Name: none
Address: none
Phone Number: none
Customer Number: 0
Mailing List: false
Expected: none x3, 0, false.
Enter a new name: Bob
Enter a new address: 123 Happy Lane
Enter a new phone number: 123-456-7890
Enter a new customer number: 12
Enter a new true/false for mailing list: true
Name: Bob
Address: 123 Happy Lane
Phone Number: 123-456-7890
Customer Number: 12
Mailing List: true
Expected: given name/address/phone number/customer number/boolean.
Test 1 Complete. Values are reset. Please continue.
Enter a name: Enter an address: Problem starts here...
The call to nextBoolean() doesn't consume the newline character that follows either your true or false input. As a result, this newline character is still in the input buffer when you next call nextLine(), which immedately consumes the leftover newline character and then moves on.
To get the expected behaviour, simply add another call to nextLine() just after you call nextBoolean(). You should also note that this would have happened if nextInt() was the last call in the sequence too.
You might also want to think about putting parts of that code into some form of loop (a while loop perhaps?) so that you've not got a huge section of duplicated code.

incorrect input Scanner

hey i am trying to take inputs from user one by one but its appears to take wrong input... it actually skip the one input to be taken from user ..
e.g..in the code below i want to take name first then address and at last contact but when i do so it skip the name input...
import java.util.ArrayList;
import java.util.Scanner;
public class mainClass {
public static void main(String args[]){
int value = 0;
ArrayList<Data> Contacts = new ArrayList<Data>();
Scanner input = new Scanner(System.in);
while(true){
System.out.println("Enter 1 to add a Contact :: Enter 2 to View all Contact");
value = input.nextInt();
switch(value){
case 1:
System.out.println("Plz enter Name : ");
String name = input.nextLine();
System.out.println("Plz enter Address : ");
String address = input.nextLine();
System.out.println("Plz enter ContactNo : ");
String contact = input.nextLine();
Data objt1 = new Data(name, address, contact);
Contacts.add(objt1);
break;
case 2:
System.out.println("Name\t\tContact\t\tAddress");
for(int i=0; i<Contacts.size(); i++)
{
System.out.println(Contacts.get(i));
}
break;
default:
System.out.println("Sorry wrong input");
}
}
}
}
the data class is here
public class Data {
private String name = "";
private String address = "";
private String cell = "";
public Data(String n, String a, String c){
name = n;
address = a;
cell = c;
}
public String toString()
{
return String.format("%s\t\t%s\t\t%s", name, cell, address);
}
}
try adding input.nextLine(); after getting the value, this will consume the new line character
value = input.nextInt();
input.nextLine();
(or)
int value = Integer.parseInt(input.nextLine());

Categories