I play this game where you can collect HUNDREDS of power ups, and the only way to know what they do without memorizing them is to look them up. Because of this, I am trying to make myself a "assistant" program where I can type in the name of the power up and get the effect of it.
Below is the full code with useless parts taken out. Examples of outputs are below. The problem should be fairly obvious if you look at the outputs. What ways could I use to fix this problem, or what am I doing wrong?
import java.util.ArrayList;
import java.util.Scanner;
public class ProgMain {
// // *** ------------*** and any variations indicate a change of importance or use
public static ArrayList<String> itemlist; // ArrayList of items to cycle through to see if item exists in database.
static {
itemlist = new ArrayList<String>();
itemlist.add("genericitem"); // testing item
itemlist.add("exit"); // allows for internal program exit
itemlist.add("debuglist"); // allows to print every item in "itemlist" for debug
// ***-------------------------------------------------***
itemlist.add(0, "thisitem hasaspace");
}
static Scanner console = new Scanner (System.in);
public static void main(String[] args) {
String item = " " // variable to store name of item
System.out.println("Enter an item name to check the database.");
System.out.println("Enter 'exit' to quit the program.");
System.out.println();
while(true) {
System.out.print("Item Name: ");
item = console.next().toLowerCase().replaceAll("\\s", " ");
/**
* ONLY FINDS FIRST WORD, even after removal of spaces.
*/
//DEBUG
System.out.print("\n DEBUG: " + item + "\n");
if (itemlist.contains(item)) { // cycle through database
displayItemProperties(item); // find item and print properties
System.out.println();
} else { // declares if the item isn't found in database
System.out.println("That item does not exist.");
System.out.println();
}
}
}
static void displayItemProperties(String item) {
/**
* Item names must be in LOWERCASE and have NO SPACES.
*/
// GENERIC IF STATEMENT
// Easy copy/paste to add new items
/*
if (item.equals("")) {
System.out.println("");
}
*/
// **----------------------------------**
if (item.equals("genericitem")) {
System.out.println("A generic item.");
}
if (item.equals("debuglist")) {
for (int i = 0; i < itemlist.size(); i++) {
System.out.println(itemlist.get(i));
}
}
if (item.equals("exit")) {
System.out.println("Application Terminating...");
System.exit(0);
}
// ***------------------------------------------------------***
if (item.equals("thisitem hasaspace")) {
System.out.println("If a name has a space, it wont show up correctly...");
}
// introduce new item declarations here
}
}
This is an example output of something entered WITHOUT A SPACE:
Enter an item name to check the database.
Enter 'exit' to quit the program.
Item Name: genericitem
DEBUG: genericitem
A generic item.
Item Name: exit
DEBUG: exit
Application Terminating...
and this is what happens when a name WITH A SPACE is used:
Enter an item name to check the database.
Enter 'exit' to quit the program.
Item Name: thisitem hasaspace
DEBUG: thisitem
That item does not exist.
Item Name:
DEBUG: hasaspace
That item does not exist.
Item Name: exit
DEBUG: exit
Application Terminating...
The Scanner class by default uses any whitespace as a delimiter pattern. This includes a regular SPACE. So when you call Scanner.next(), it pulls the next token, and thisite hasaspace is 2 separate tokens because a space is a default delimiter.
Instead of calling Scanner.next(), try calling Scanner.nextLine():
item = console.nextLine().toLowerCase().replaceAll("\\s", " ");
Related
I'm new in Java programming and I'm trying to create a user input validation to make sure that the user only input one of the three possible strings: Mammals, Reptiles, Birds. But I'm stock on trying to validate and create a loop. So far I have this:
public void validName() {
Scanner typeInput = new Scanner(System.in);
String [] type = {"Mammals", "Reptiles", "Birds"};
System.out.println("Enter Animal Type: ");
String atype = typeInput.next();
try {
if
(!Arrays.asList(type).contains(atype)){
System.out.println("Not a correct animal");
}
}
catch(Exception e){
System.out.println(e+"Plase add the correct Animal Type: (Mammals, Reptile, or Bird");
atype= typeInput.nextLine();}
while (atype.equalsIgnoreCase("Mammals") || atype.equalsIgnoreCase("Reptile") || atype.equalsIgnoreCase("Birds"));
{ System.out.println("Continue to next step");}
}
}
When I run the previous code I get this output:
Please enter First Name
Cris
Please enter Last Name
Cruz
User logged In: Criz Cruz
Welcome to ZooOrganizer!
Enter Animal Type:
Cow
Not a correct animal
Continue to next step
------------------------------------------------------------------------
BUILD SUCCESS
-----------------------------------------------------------------------
I can't get to execute the Catch Exception neither the loop to make the user to input the animal type again.
public void validName() {
Scanner typeInput = new Scanner(System.in);
String [] type = {"Mammals", "Reptiles", "Birds"};
System.out.println("Enter Animal Type: ");
String atype = typeInput.next();
try {
if
(!Arrays.asList(type).contains(atype)){
System.out.println("Not a correct animal");
}
}
catch(Exception e){
System.out.println(e+"Plase add the correct Animal Type: (Mammals, Reptile, or Bird");
atype= typeInput.nextLine();}
while (atype.equalsIgnoreCase("Mammals") || atype.equalsIgnoreCase("Reptile") || atype.equalsIgnoreCase("Birds"));
{ System.out.println("Continue to next step");}
}
}
If you want to think about it, the prompt you have coded is actually rather cruel. It doesn't inform the User of what is expected as input. You may as well display a prompt like:
Hey, enter an Animal Type and if you guess it right
you get two free OH-Henry Bars (yum yum): -->
Be up-front with what is required from the User and if you can, make the entry as simple as possible. If you do then the errors that can be possibly produced by that User is almost completely eliminated, for example:
Enter an Animal Type (Mammals, Reptiles, Birds): -->
Now the User can see what input you're expecting. This however still has issues which your code would need to deal with and take care of such as spelling mistakes, improper letter case, no word entered, etc. In my opinion it's sort of actually a pain in the butt to have to write the word Reptile into something like a Console Application which is why I would avoid those applications, you know :
Enter the full path and file name to your Database located within
the Windows Documents folder: -->
Ya, I don't think so....next app.
When you have multiple items that can be entered then use a Menu System. This way the User can see the choices available and only needs to enter a single letter or number for the desired menu item, for example:
Select an Animal Type (1-3):
1) Mammal
2) Reptiles
3) Birds
4) Quit
Menu Choice: -->
Doing it this way also reduces the amount of code required to carry out validity. Is the entered menu choice an Integer Number, is the entry greater than or equal to 1 and is it less than or equal to 4. If not then tell the User of non-validity and loop again. Here is how you might do this with your current scheme:
String ls = System.lineSeparator();
Scanner typeInput = new Scanner(System.in);
String[] type = {"Mammals", "Reptiles", "Birds"};
String selectedAnimalType = "";
String atype = "";
// Start a prompt WHILE loop...
while (atype.equals("")) {
/* Display a Menu. Doing things this way doesn't leave
the User in the dark as to what is required for input. */
System.out.print("Select an Animal Type (1-3): " + ls
+ "1) Mammal" + ls + "2) Reptiles" + ls
+ "3) Birds" + ls + "4) Quit" + ls
+ "Menu Choice: --> ");
// Get User input...
atype = typeInput.nextLine();
// Is the Input a Valid menu choice?
if (!atype.matches("\\d") || Integer.valueOf(atype) < 1 || Integer.valueOf(atype) > 4) {
/* If it's not a string representation of a Integer numerical value OR
if it's a numerical value less than 1 OR if it's a numerical value
greater than 4 */
System.out.println("Invalid entry! Please try again..." + ls);
atype = ""; // Make atype equal null string ("") to continue WHILE loop
}
// Otherwise, was the menu choice the numerical value 4 to quit?
else if (Integer.valueOf(atype) == 4) {
// Yes, it was...
System.out.println("Quiting... Bye-Bye");
System.exit(0); // Quit (end) Application.
}
}
// Prompt loop successful...continue on with code.
/* Get the proper name for the Animal Type from the 'type' Array
based on the menu choice (numerical value minus 1) so as to get
the desired array index value. */
selectedAnimalType = type[Integer.valueOf(atype) - 1];
/* The condition for the below WHILE loop is redundant since we
would NEVER get this far unless a menu choice for either Mammal,
Reptiles, or Birds, was made, so don't bother using it. Do something
similar as to what was done in the first prompt loop above. */
while (atype.equalsIgnoreCase("Mammals") || atype.equalsIgnoreCase("Reptile") || atype.equalsIgnoreCase("Birds")) {
System.out.println("Continue to next step");
// ........................................
}
You should use a Do...While loop in this case:
public void validName() {
Scanner typeInput = new Scanner(System.in);
String [] type = {"Mammals", "Reptiles", "Birds"};
do {
System.out.println("Enter Animal Type: ");
String atype = typeInput.next();
try {
if
(!Arrays.asList(type).contains(atype)){
System.out.println("Not a correct animal");
System.out.println("Continue to next step");}
}
}
catch(Exception e){
System.out.println(e+"Plase add the correct Animal Type: (Mammals, Reptile, or Bird");
atype= typeInput.nextLine();}
} while (atype.equalsIgnoreCase("Mammals") || atype.equalsIgnoreCase("Reptile") || atype.equalsIgnoreCase("Birds"));
}
I am trying to create a program for an assignment in Java and are looking for a push in the right direction. I am currently taking the class online so asking a teacher for help is not an option for me.
I am trying to create a simple java program that allows a user to enter their first name and last name, and their requested seat number. If the seat is taken, the program is supposed to find the nearest available seat. So far I have succeeded at getting all the input from the user (albeit in a roundabout way) and creating and printing an array.
Question
Can I store boolean values in an array? I just want to store false if the seat is taken and then have and if else statement test for true or false, and store a false if the value returned is true(very confusing but thats my train of thought) is there an easier way to go about this? Also how would I also store the persons first and last name with that boolean value? Do I have to create a seperate array? I have attached my code so far that succeeds in getting the user info and printing out an array.
//Import scanner and arrays
package airlinereservations;
import java.util.Scanner;
import java.util.Arrays;
public class AirlineReservations {
public static void main(String[] args) {
//Print the header
System.out.println("___________________________________");
System.out.println("|WELCOME TO FLY BY NIGHT AIRLINES!|");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
// Promt user for first and last name
System.out.println("Please enter your first name:");
Scanner scan= new Scanner(System.in);
String first = scan.nextLine();
System.out.println("Please enter your last name:");
String last = scan.nextLine();
//Greet the user
System.out.println("Hello! " + first + " "+ last);
//Get the requested seat
System.out.println("Please enter your requested seat row number 1-9:");
int rowz = scan.nextInt();
System.out.println("Please enter your requested seat column number 1-4:");
int colz = scan.nextInt();
//Tell the user if the seat is already taken
if(int rowz == rowz, System.out.println("This seat is already taken!"));
else(return true);
//Print out the array
int[][] Seating= new int[9][4];
for(int row=0; row<Seating.length; ++row){
for(int col=0; col<Seating[row].length; ++col){
Seating[row][col] = (row + col) % 9 + 1;
for(int ro=0; ro<Seating.length; ++ro);
}
System.out.println();
for(int col=0; col<Seating [row].length; ++col)
System.out.print(Seating[row][col]);
}
System.out.println();
}
}
For a push in the right direction, as you said, I see two quick options to consider:
One would be to add a Map. This would allow you to store a bunch of key-value pairs which you could use to represent seats, and whether or not they are taken.
Another option is to create a Seat class, that has a field for seatName and whether or not it is taken, and you could create an Array of these seat objects.
If you don't know where to begin on implementing either of those, I will help you, but I challenge you to at least try implementing one or the other first.
EDIT
Or, even more simply, you could create a two-dimensional array holding strings, like this:
String[][] seats = new int[numberofseats][2];
seats[0][0] = "Seat Number 1";
seats[0][1] = "true";
And you can force that second dimension to only hold values true or false, and later check them like this:
if(seats[0][1].equals("true")) // Then seat number 1 is taken
This might not be the best solution as far as error handling, but it is a possibility.
EDIT 2 If you were to create a seat class, I would set it up like this:
public class Seat{
private String seatName;
private boolean isTaken;
public Seat(String s, boolean t){
this.seatName = s;
this.isTaken = t;
}
public boolean isSeatTaken(){
return this.isTaken;
}
}
Then, later you can do something like this:
ArrayList<Seat> myArrayList = new ArrayList<Seat>(); // Or a regular array if you prefer
// Add elements
// Below checks if first seat in list is taken
boolean firstSeatTaken = myArrayList.get(0).isSeatTaken();
I am trying to figure out how to take input from a user and store it into an array. I cannot use an arrayList (the easy way lol) but rather a standard array[5]. I have looked on here and on google and because of the sheer amount of questions and responses I have yet to find a good answer. Using scanner to get input is not a problem. Storing the input in an array is not the problem. What i am having trouble with is that I need to store one input at a time.
Currently I was using a for loop to gather information but it wants to gather the entire array at once.
for (int i=0;i<5;i++)
array[i] = input.nextInt();
for (int i=0;i<array.length;i++)
System.out.println(array[i]+" ");
I have been messing around with it, but if i remove the first for loop, im not sure what to put in the array[] brackets. BlueJ just says that "array[] is not a statement"
How can I accept just one value at a time and let the user determine if they want to do the next?
This is for a homework assignment, but the homework assignment is about creating a console with commands of strings and this is a concept that i need to understand to complete the rest of the project which is working fine.
boolean c = true;
Scanner sc=new Scanner(System.in);
int arr[] = new int[5];
int i =0;
int y = 1;
while(c){
System.out.println("Enter "+i+" index of array: ");
arr[i]=sc.nextInt();
i++;
System.out.println("Want to enter more if yes press 1 or press 2 ");
y = sc.nextInt();
if(y==1)c=true;
else c=false;
}
Use this as a reference implementation. General pointers on how a simple console program can be designed. I'm using JDK 6 at the moment. If you're on JDK 7 you can use switch case with strings instead of the if-else.
public class Stack {
int[] stack; // holds our list
int MAX_SIZE, size; /* size helps us print the current list avoiding to
print zer0es & the ints deleted from the list */
public Stack(int i) {
MAX_SIZE = i; // max size makes the length configurable
stack = new int[MAX_SIZE]; // intialize the list with zer0es
}
public static void main(String[] args) throws IOException {
new Stack(2).run(); // list of max length 2
}
private void run() {
Scanner scanner = new Scanner(System.in);
// enter an infinite loop
while (true) {
showMenu(); // show the menu/prompt after every operation
// scan user response; expect a 2nd parameter after a space " "
String[] resp = scanner.nextLine().split(" "); // like "add <n>"
// split the response so that resp[0] = add|list|delete|exit etc.
System.out.println(); // and resp[1] = <n> if provided
// process "add <n>"; check that "<n>" is provided
if ("add".equals(resp[0]) && resp.length == 2) {
if (size >= MAX_SIZE) { // if the list is full
System.out.print("Sorry, the list is full! ");
printList(); // print the list
continue; // skip the rest and show menu again
}
// throws exception if not an int; handle it
// if the list is NOT full; save resp[1] = <n>
// as int at "stack[size]" and do "size = size + 1"
stack[size++] = Integer.parseInt(resp[1]);
printList(); // print the list
// process "list"
} else if ("list".equals(resp[0])) {
printList(); // print the list
// process "delete"
} else if ("delete".equals(resp[0])) {
if (size == 0) { // if the list is empty
System.out.println("List is already empty!\n");
continue; // skip the rest and show menu again
}
// if the list is NOT empty just reduce the
size--; // size by 1 to delete the last element
printList(); // print the list
// process "exit"
} else if ("exit".equals(resp[0])) {
break; // from the loop; program ends
// if user types anything else
} else {
System.out.println("Invalid command!\n");
}
}
}
private void printList() {
System.out.print("List: {"); // print list prefix
// print only if any ints entered by user
if (size > 0) { // are available i.e. size > 0
int i = 0;
for (; i < size - 1; i++) {
System.out.print(stack[i] + ",");
}
System.out.print(stack[i]);
}
System.out.println("}\n"); // print list suffix
}
private void showMenu() {
System.out.println("Enter one of the following commands:");
// Check String#format() docs for how "%" format specifiers work
System.out.printf(" %-8s: %s\n", "add <n>", "to add n to the list");
System.out.printf(" %-8s: %s\n", "delete", "to delete the last number");
System.out.printf(" %-8s: %s\n", "list", "to list all the numbers");
System.out.printf(" %-8s: %s\n", "exit", "to terminate the program");
System.out.print("$ "); // acts as command prompt
}
}
Sample Run :
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ list
List: {}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ add 1
List: {1}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ add 2
List: {1,2}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ add 3
Sorry, the list is full! List: {1,2}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ delete
List: {1}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ delete
List: {}
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ delete
List is already empty!
Enter one of the following commands:
add <n> : to add n to the list
delete : to delete the last number
list : to list all the numbers
exit : to terminate the program
$ exit
(Truth be told: I was getting bored. So, I wrote it and thought might as well post it then.)
How about this way?
Scanner sc=new Scanner(System.in);
int[] arr=new int[5];
int i=0;
while (i<arr.length){
System.out.println("Enter "+i+" index of array: ");
arr[i]=sc.nextInt();
i++;
}
My title isn't exactly the best but I'm not sure how to name what I am trying to do. Either way, I have a case-switch...
switch (input) {
case "A":
Item item = new Item();
System.out.print("Enter a barcode: ");
barCode = scan.nextLine();
item.setBarCode(barCode);
if (store.addItem(barCode)) {
System.out.println(store.stockedItems.get(barCode).getProductName()
+ " has been added to the store's inventory");
}
else {
item.setQuantity(1);
System.out.print("Enter the item's name: ");
productName = scan.nextLine();
productName = productName.toLowerCase();
item.setProductName(productName);
store.stockedItems.put(barCode, item);
System.out.println(store.stockedItems.get(barCode).getProductName()
+ " has been added to the store's inventory");
}
break;
}
This is just one case. What this does is when the user picks A to add an object to my data structure, it finds out if the barcode mentioned is already in use.
If it is, it just increments the quantity of the object in my data structure.
If the barcode is not in use and after checking its validity. It will prompt the user for the name of the object and then proceed to add it to my data structure.
Now the problem is after I input the barcode string and call the setter function in its respective object class:
public void setBarCode(String code) {
if (!code.matches("[0-9]+") || code.length() != 12) {
System.out.println("The barcode entered is not in valid format. Entry ignored.");
} else {
barcode = code;
}
}
This function just makes sure it is numeric and 12 characters long. If it's not, I want to ignore the entry and start over from the menu. The problem I have is that the program moves on to asking for the items name even if the barcode is invalid and not set.
How do I skip all that and just print the menu out again?
Two strategies can work for this:
move the check for barcode validity outside the setBarCode method and do that test first (or modify setBarCode to return a boolean indicating whether the bar code was valid).
modify addItem to return something more informative than a boolean so that you can distinguish three cases: bad bar code; succeeded; failed because it needs more info.
The setter setBarCode() should either (a) succeed, or (b) indicate failure (probably using an IllegalArgumentException since we're in Java) rather than fail silently. If you were to use an IllegalArgumentException, this code would work nicely:
boolean acceptable;
try {
item.setBarCode(barCode);
acceptable = true;
}
catch(IllegalArgumentException e) {
acceptable = false;
}
if(acceptable) {
if(store.addItem(barCode)){
System.out.println(store.stockedItems.get(barCode).getProductName() + " has been added to the store's inventory");
}
else {
item.setQuantity(1);
System.out.print("Enter the item's name: ");
productName = scan.nextLine();
productName = productName.toLowerCase();
item.setProductName(productName);
store.stockedItems.put(barCode, item);
System.out.println(store.stockedItems.get(barCode).getProductName() + " has been added to the store's inventory");
}
}
break;
However, I'd recommend you not rely on the failure of a setter for correctness. Stylistically, it "smells funny." Rather, I'd put the test in another (probably static) method, test before you call the setter and react accordingly, and then put an assert in the setter. So, more like this:
// Somewhere up in your code -- Sorry, fixed up your regex
private static final Pattern BARCODE=Pattern.compile("^\\d{12}$");
public static boolean isValidBarcode(String candidate) {
return BARCODE.matcher(candidate).matches();
}
// Now your "real" code
case "A":
Item item = new Item();
System.out.print("Enter a barcode: ");
barCode = scan.nextLine();
if(isValidBarCode(barCode)) {
item.setBarCode(barCode);
if(store.addItem(barCode)) {
System.out.println(store.stockedItems.get(barCode).getProductName() + " has been added to the store's inventory");
}
else {
item.setQuantity(1);
System.out.print("Enter the item's name: ");
productName = scan.nextLine();
productName = productName.toLowerCase();
item.setProductName(productName);
store.stockedItems.put(barCode, item);
System.out.println(store.stockedItems.get(barCode).getProductName() + " has been added to the store's inventory");
}
}
else {
System.out.println("That's not a valid bar code.");
}
break;
// And, finally, your setBarCode() method
public void setBarCode(String code) {
assert isValidBarCode(code);
barcode = code;
}
I'm working on this database type program for school. so far I've been able to make this part of the code fully functional:
import jpb.*;
//jpb is a package that lets me use SimpleIO as you'll see below
public class PhoneDirectory {
public static void main(String[] args) {
PhoneRecord[] records = new PhoneRecord[100];
int numRecords = 0;
// Display list of commands
System.out.println("Phone directory commands:\n" +
" a - Add a new phone number\n" +
" f - Find a phone number\n" +
" q - Quit\n");
// Read and execute commands
while (true) {
// Prompt user to enter a command
SimpleIO.prompt("Enter command (a, f, or q): ");
String command = SimpleIO.readLine().trim();
// Determine whether command is "a", "f", "q", or
// illegal; execute command if legal.
if (command.equalsIgnoreCase("a")) {
// Command is "a". Prompt user for name and number,
// then create a phone record and store it in the
// database.
if (numRecords < records.length) {
SimpleIO.prompt("Enter new name: ");
String name = SimpleIO.readLine().trim();
SimpleIO.prompt("Enter new phone number: ");
String number = SimpleIO.readLine().trim();
records[numRecords] =
new PhoneRecord(name, number);
numRecords++;
} else
System.out.println("Database is full");
} else if (command.equalsIgnoreCase("f")) {
// Command is "f". Prompt user for search key.
// Search the database for records whose names begin
// with the search key. Print these names and the
// corresponding phone numbers.
SimpleIO.prompt("Enter name to look up: ");
String key = SimpleIO.readLine().trim().toLowerCase();
for (int i = 0; i < numRecords; i++) {
String name = records[i].getName().toLowerCase();
if (name.startsWith(key))
System.out.println(records[i].getName() + " " +
records[i].getNumber());
}
} else if (command.equalsIgnoreCase("q")) {
// Command is "q". Terminate program.
return;
} else {
// Command is illegal. Display error message.
System.out.println("Command was not recognized; " +
"please enter only a, f, or q.");
}
System.out.println();
}
}
}
// Represents a record containing a name and a phone number
class PhoneRecord {
private String name;
private String number;
// Constructor
public PhoneRecord(String personName, String phoneNumber) {
name = personName;
number = phoneNumber;
}
// Returns the name stored in the record
public String getName() {
return name;
}
// Returns the phone number stored in the record
public String getNumber() {
return number;
}
}
I'm trying to do a few things, and they're probably simple solutions I'm just looking over. I need to make a command "d" for delete that will prompt for a name and delete all records that match. I tried using the same approach as the "f" command where partial matches are allowed, but again I couldn't get it to work.
Next I need to modify the f command so that it lines up names and numbers in columns. I tried to force the string to be a certain length by making it = to the array length to no avail, it just returns looking blank. essentially it needs to look like this:
Smith, John 555-5556
Shmoe, Joe 565-5656
and I need to set records to 1 instead of 100 and have in double in size every time it gets full. I haven't messed with this yet, but I'm not sure where to start.
Because the requirement is to be able to remove records i would recommend using an ArrayList which grows dynamically and you are able to easily remove records.
It is declarer like this:
ArrayList<PhoneRecord> records = new ArrayList<PhoneRecord>();
and you add like this:
records.add(PhoneRecord(name, number)));
you can remove a record like this:
records.remove(i);
to remove the ith record of the list.
the current size of the list is given by records.size() function.
As for your second question you can use string formatting to tell it to format the name for a specified number of characters for example you could use this:
System.out.println(String.format("%s%15s", records[i].getName(), records[i].getNumber());
In this example will be added space characters before the telephone in order the total number of characters will be 15.
So if your number is 555-5556 then 7 space blank characters will be added before the number.