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.
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 have two questions, first of all I have software that takes names and I want to not allow the reception of a variable that is not String How do I do it? And second thing I did a code section whose goal is to sort songs according to their singer (he gets an array of songs containing the name of the singer and I want him to make a list of songs that each singer has) but something that does not work.
Thank you:)
this is the code:
public void miunBySinger(Song[] song3){
int place =0;
int numChecking = 0;
System.out.println("this is your songs list sorts by name of singer");
for (int i = 0; i < song3.length; i++) {
System.out.println("song of"+song3[i].getSinger()+ ":");
for (int i1 = 0; i1 < song3.length; i1++) {
if (song3[place].getSinger().equals( song3[place+numChecking].getSinger())){
System.out.println(song3[place+numChecking].getName());
}
if (numChecking + place < song3.length) {
numChecking++;
}else {
numChecking =1;
place++;
}
}
}
}
You have the code:
if (numChecking + place < song3.length) {
numChecking++;
The problem is that if numChecking + place is exactly 1 less than song3.length, then when you increment numChecking, numChecking + place will then be equal to song3.length. So when you try to access the array at that index, it will be off the end of the array.
"first of all I have software that takes names and I want to not allow
the reception of a variable that is not String. How do I do it?"
To you.... what would not be considered a String? If you set your input mechanism to only accept a String then golly gee, that's what you'll get. In reality it's all a matter of what characters you would allow to be within a String so you can use the String.matches() method to carry out a mild form of validation on the String contents which is input from User (or whatever the input source might be).
Let's pretend that we have a String variable named artist and we are going to accept User input to fill that variable with a valid name from the Console window. If the name String isn't found to be valid (according to our rules) then we inform the User and let him/her try again.
To begin with you need to decide what the 'name validity rules' are and for the sake of this simple example we are just going to have these:
Allow any alpha letters from a to z or A to Z;
Allow commas (,);
Allow periods (.);
Allow hyphens (-);
Allow apostrophes (');
Allow white-spaces;
Don't allow any other keyboard character other than rules 1 to 6.
The above rules can be easily applied to the String.Matches() method using a Regular Expression (RegEx) since the method accepts them. To institute the above rules we will use the following RegEx:
"[a-zA-Z.,'\\- ]+"
and here is an explanation of what the RegEx does:
To implement what is mentioned above you might have code that looks like this:
Scanner userInput = new Scanner(System.in);
String artist = "";
while (artist.equals("")) {
System.out.print("Please enter a Singer Name (or quit): -> ");
artist = userInput.nextLine();
if (artist.equalsIgnoreCase("quit")) {
System.err.println("Bye-Bye");
System.exit(0);
}
// Regular Expression used to validate input.
// Notice the NOT operator (!).
if (!artist.matches("[a-zA-Z.,'\\- ]+")) {
System.err.println("Invalid Name! Try again...\n");
artist = "";
}
}
// Any Continuing Method Code Here:
System.out.println("Processing songs for the singer: " + artist
+ "\nPlease wait...\n");
Again, you need to be the one that determines the rules for what would be considered "a valid String". This isn't too difficult for names of people. Letter case is not really an issue either in this particular situation since the String class does have the String.equalsIgnoreCase() method as well. Just add the characters you want allowed for validation within the Regular expression but do keep in mind that some characters (like the hyphen) are considered special RegEx characters and need to be Escaped with the Escape character (\).
"second thing I did a code section whose goal is to sort songs
according to their singer (he gets an array of songs containing the
name of the singer and I want him to make a list of songs that each
singer has) but something that does not work."
I had to read this a few times to get a grasp of what I think you're really asking here and to be honest, I'm still not sure. Are you talking about sorting or do you actually mean "display song titles according to their respective Artists in a list type fashion"? Perhaps it's both.
In any case sorting is the way to go and there are a lot ways to do it in Java. At this time it's also important to note that it would of been helpful if you had also provided the code for the Song Class so for the sake of the examples shown below I created a Songs Class:
The Songs Class:
public class Songs {
private String songTitle;
private String artistName;
public Songs(String songName, String singerName) {
this.songTitle = songName;
this.artistName = singerName;
}
public Songs() {
songTitle = null;
artistName = null;
}
public String getTitle() {
return songTitle;
}
public void setTitle(String songName) {
this.songTitle = songName;
}
public String getArtist() {
return artistName;
}
public void setArtist(String singerName) {
this.artistName = singerName;
}
public void sort(Songs[] songs) {
List<String> list = new ArrayList<>();
// Place the songs array into a List collection as a single
// string placing the Artist first and using the Pipe (|)
// character as a delimiter between Artist and Title. This
// ensures that the sorting will be done based on the Artist's
// name will be sorted and because Titles with the same artist
// the titles appear to be sorted as well. This can also be
// done with a Comparator but this allows you to clearly see
// what's going on and allows you to make the sort the way you
// want.
for (Songs song : songs) {
list.add(song.getArtist() + "|" + song.getTitle());
}
// Sort the collection (ascending order)
Collections.sort(list);
// Convert the List back into our original songs Array
for (int i = 0; i < list.size(); i++) {
String[] tmp = list.get(i).split("\\|");
songs[i] = new Songs(tmp[1], tmp[0]);
}
}
#Override
public String toString() {
return songTitle + " By " + artistName;
}
}
You will notice that in this Songs class there are what you would expect to be typical Fields along with Getter and Setter methods but there is also a custom toString() method and a sort() method which only excepts a single dimensional Songs[] Array as an argument. This way you can keep the sorting business in one house so to speak.
Let's create a Songs Array:
Songs[] songs = new Songs[10];
songs[0] = new Songs("Up On The Roof", "The Drifters");
songs[1] = new Songs("On Broadway", "The Drifters");
songs[2] = new Songs("It's All Over Now", "The Rolling Stones");
songs[3] = new Songs("Time Is On My Side", "The Rolling Stones");
songs[4] = new Songs("Dance, Dance, Dance", "The Beach Boys");
songs[5] = new Songs("Do You Wanna Dance", "The Beach Boys");
songs[6] = new Songs("I Don't Believe In You", "Talk Talk");
songs[7] = new Songs("I Believe In You", "Talk Talk");
songs[8] = new Songs("Hold On", "Wilson Phillips");
songs[9] = new Songs("Release Me", "Wilson Phillips");
This array contains 10 song Titles and the 5 Artists that sang them. As you can see there is no real sorting to the elements of the array but we'll take care of that now with our Songs.sort() method and then we'll list the Artists to the Console Window with their related Song Titles beneath them:
// Sort the songs Array..,
new Songs().sort(songs);
// Display the Array by artist and their related titles.
String currentArtist = "";
// Iterate through the songs Array
for (int i = 0; i < songs.length; i++) {
String artistName = songs[i].getArtist(); // artist from current song index
String songTitle = songs[i].getTitle(); // Titlet from current song index
// Make sure we only display the Artist once.
if (!currentArtist.equals(artistName)) {
System.out.println("\nSongs By: " + songs[i].getArtist());
}
// Display the Title(s) relate to the current Artist
System.out.println("\t " + songs[i].getTitle());
currentArtist = artistName; // Update who is the current Artist
}
When the above code is run the Console Window will display:
Songs By: Talk Talk
I Believe In You
I Don't Believe In You
Songs By: The Beach Boys
Dance, Dance, Dance
Do You Wanna Dance
Songs By: The Drifters
On Broadway
Up On The Roof
Songs By: The Rolling Stones
It's All Over Now
Time Is On My Side
Songs By: Wilson Phillips
Hold On
Release Me
Notice how the Artists are listed in alphabetical order as are the song Titles beneath them.
Tying it all together...
Now it's time to put it all together whereas we're going to create a console display application where the User is asked to enter the name of a particular Artist and the app will seek through the songs Array and create yet another array named artistSongs based on that artist name supplied if it exists. If the artist name doesn't exist then the User is notified and given the opportunity to enter another Artist name (or quit the application by entering quit).
To completely pull this off we'll need yet another method named getSongsByArtist() which will take our songs array and the User supplied artist name as arguments so as to build our artistSongs Array. Here is the whole runnable code (you will need the Songs class posted above):
The Console Application (requires Songs Class above):
package songsexample;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class SongsExample {
public static void main(String[] args) {
new SongsExample().startApp();
}
private void startApp() {
// Declare and initialize the songs array for 10 songs.
Songs[] songs = new Songs[10];
// Fill the Array...
songs[0] = new Songs("Up On The Roof", "The Drifters");
songs[1] = new Songs("On Broadway", "The Drifters");
songs[2] = new Songs("It's All Over Now", "The Rolling Stones");
songs[3] = new Songs("Time Is On My Side", "The Rolling Stones");
songs[4] = new Songs("Dance, Dance, Dance", "The Beach Boys");
songs[5] = new Songs("Do You Wanna Dance", "The Beach Boys");
songs[6] = new Songs("I Don't Believe In You", "Talk Talk");
songs[7] = new Songs("I Believe In You", "Talk Talk");
songs[8] = new Songs("Hold On", "Wilson Phillips");
songs[9] = new Songs("Release Me", "Wilson Phillips");
// displayAllSongs(songs);
Scanner userInput = new Scanner(System.in);
String artist = "";
while (artist.equals("")) {
// Prompt for Artist name from User
System.out.print("\nPlease enter a Artist Name (or quit): -> ");
artist = userInput.nextLine();
if (artist.equalsIgnoreCase("quit")) {
System.out.println("Bye-Bye");
System.exit(0);
}
// Is the supplied name from User valid (meets our rules)?
if (!artist.matches("[a-zA-Z.,'\\- ]+")) {
// No it's not. Inform & allow User to try again
System.err.println("Invalid Artist Name! Try again...\n");
artist = "";
continue; // Go to top of loop.
}
// Name is valid...
System.out.println("Processing songs for the Artist: " + artist
+ "\nPlease wait...");
// Get song titles by the Artist supplied from User
Songs[] artistSongs = getSongsByArtist(songs, artist);
// Are there songs by Artist?
if (artistSongs.length > 0) {
// Yes there is...
new Songs().sort(artistSongs); // Sort the artistSongs Array.
//sortSongs(artistSongs); // Sort the artistSongs Array.
// Display the Artist's name.
System.out.println("\nSongs By: " + artistSongs[0].getArtist());
//Display the Artist's song titles...
for (int i = 0; i < artistSongs.length; i++) {
System.out.println("\t " + artistSongs[i].getTitle());
}
}
else {
// No such artist found.
System.out.println("There are no found Titles by: " + artist);
}
artist = "";
}
}
private void displayAllSongs(Songs[] songs) {
// Sort the songs Array..,
new Songs().sort(songs);
// Display the Array by artist and their related titles.
String currentArtist = "";
// Iterate through the songs Array
for (int i = 0; i < songs.length; i++) {
String artistName = songs[i].getArtist(); // artist from current song index
String songTitle = songs[i].getTitle(); // Titlet from current song index
// Make sure we only display the Artist once.
if (!currentArtist.equals(artistName)) {
System.out.println("\nSongs By: " + songs[i].getArtist());
}
// Display the Title(s) relate to the current Artist
System.out.println("\t " + songs[i].getTitle());
currentArtist = artistName; // Update who is the current Artist
}
}
public Songs[] getSongsByArtist(Songs[] songs, String artistName) {
List<Songs> list = new ArrayList<>();
for (Songs song : songs) {
// See if the artist name in Array contains the
// supplied artist name. Everything is brought to
// lowercase so that there is no case sensitivity
// and the String.contains() method is used to reduce
// some need for name accuracy.
if (song.getArtist().toLowerCase().contains(artistName.toLowerCase())) {
list.add(song);
}
}
return list.toArray(new Songs[0]);
}
}
I am writing a program for a project for school. The project requires me to create a record of pets for a pet hospital. I am supposed to create a list of pet owners (maximum of 30 owners) with their first name, last name, e-mail, and phone, and an array pets for each owner (maximum of pets per owner is 5). However, the user can create a list of less than 30 owners. The issue I have is I want to make code where the user can press the escape key to stop the outside while loop that asks them for the owner info when they don't need to add anymore owners. Also, where it says, "System.out.println("Press enter to add another owner or Esc to finish list.");" it is in another loop, so if the user hits an incorrect key it will loop asking them if they want to stop adding tot he list or not (until they hit esc or enter). (Note: the code below is not my whole program, I just needed help with one specific part. I left the if statements blank, because that is where my keypress code will be.).
public class Runner
{
public static void main(String[]args)
{
while(i <= 30)
{
System.out.println(i + ". " + "Enter the owner's first name.");
String first = scan.nextLine();
System.out.println(i + ". " + "Enter the owner's last name.");
String last = scan.nextLine();
System.out.println(i + ". " + "Enter the owner's email address.");
String emailAdd = scan.nextLine();
System.out.println(i + ". " + "Enter the owner's phone number.");
String phone = scan.nextLine();
Owner owner = new Owner(first, last, emailAdd, phone);
int j = 1;
while(j > 0)
{
System.out.println("Press enter to add another owner or Esc to
finish list.");
if ()
{
}
if ()
{
}
j++;
}
list.add(owner.toString());
i+=1;
}
System.out.println(list);
}
}
Since Java is merely using the console, there's no native way to detect a single keypress... any input must end with an "enter" to actually be taken by the program.
As such, to emulate detecting an enter keypress you could do something like:
if (scan.nextLine().isEmpty())
// do stuff
Since we know that a line always means that the enter key was pressed, if the String is empty, it means that only the enter key remains.
For the ESC key, you should use a 3rd party library if is imperative to have it work like that, otherwise, you could have the user actually write "ESC" or some other key word defined by you as input.
So I have a file which has all presidents in it - their first name, middle initial (if any), and last name.
The file needs to be read in, and a user can enter a president's name to search for it, and that president should be displayed.
I have it displaying the president if a user searches by first name or by last name, but not by both.
For example, the external file contains:
George,Washington,(1789-1797)
Franklin,D.,Roosevelt,(1933-1945)
... and so on with all the presidents
I need the user to be able to either type in the first name, the last name, or both first and last name and get the desired result (the date is irrelevant for the most part).
Tried lots of different things, but not getting there as far as displaying the president if user searches by first and last name.
Here is what I got so far:
public class NameSearch {
public static void main(String[] args) throws IOException {
try {
// read from presidents file
Scanner presidentsFile = new Scanner(new File("Presidents.txt"));
// scanner for user input
Scanner keyboard = new Scanner(System.in);
// create array list of each line in presidents file
ArrayList<String> presidentsArrayList = new ArrayList<String>();
// prompt user to enter a string to see if it matches with a president's name
System.out.println("Enter a search string of letters to find a president match: ");
// store user input
String userInput = keyboard.nextLine();
// add president file info to array list linesInPresidentFile
while (presidentsFile.hasNextLine()) {
presidentsArrayList.add(presidentsFile.nextLine());
} // end while loop
String presidentNamesArray[] = presidentsArrayList.toArray(new String[presidentsArrayList.size()]);
String results = searchArray(presidentNamesArray, userInput);
//System.out.println("\nThe presidents who have \"" + userInput + "\" as part of their name are: ");
} catch (FileNotFoundException ex) {
// print out error (if any) to screen
System.out.println(ex.toString());
} // end catch block
} // end main
// method to search for a specific value in an array
public static String searchArray(String array[], String value) {
for (int i = 0; i < array.length; i++) {
if (array[i].toLowerCase().contains(value.toLowerCase())) {
String splitter[] = array[i].split(" ,");
System.out.println(Arrays.toString(splitter));
}
}
return Arrays.toString(array);
}
}
There is another way in which I might have implemented this.Read the file inputs and stored them as objects (class with lname, fname and year perhaps). In this way you can search for lname from user input, match it up with its corresponding fname (as same objects). The creation can be done once and searching can be done in a while loop implementing users consent of continuing the search.
//define your class like this:
static int i; //to keep a track of number of objects
public class dummy{
string fname;
string lname;
string year;
};
while the file content exists:
read the line
dummy dobj[i++] = new dummy();//allocate memory for the object
split the different parameters (fname, lname, year) from the read line
put these read parameters into the object
dobj[i].fname = first;
dobj[i].lname = second;
dobj[i].year = y;
//ask your user to enter the query in a specified format
//if he enters lname, compare your input to all the object's lname, and so on
//in case of lname && fname, compare your input to the lname first and then check for the corresponding objects fname, if they match.. display
Actually, there are many ways in which you can achieve what you wish to program. You can ask use the array list indices to solve it. If you take in the input from the user in a particular format, you can map it to the index in that list. Further, if you want to use first name and last name together, you may use these index representing the first and last name to come from same list.
The reason you may have problems searching by both first and last names is because you have to match your input exactly (ignoring case of course). What I mean is if you use George Washington as input, your program will not find a match for the George,Washington,(1789-1797) line. This is because your program treats George Washington as one string. Note: the input is missing the comma, so it will not be considered a substring of George,Washington,(1789-1797). If you used George,Washington as your input string, then your program would print the George Washington line. Your program just searches if the input string is a substring of any of the lines in your file. It does not search for a first name or last name specifically. If you used in as your input string, then you would get a match for both George Washington and Franklin D. Roosevelt.What you could do is take your input data and split it and search for each of the terms. You can either accept lines that match all of the terms provided, or at least one of the terms provided.
public static String searchArray(String array[], String value) {
// Uses both blank spaces and commas as delimiters
String[] terms = value.toLowerCase().Split("[ ,]");
for (int i = 0; i < array.length; i++) {
String line = array[i].toLowerCase();
boolean printIfAllMatch = true;
boolean printIfAtLeastOneMatches = false;
for(int j = 0 ; j < terms.length; j++) {
// Check that all terms are contained in the line
printIfAllMatch &= line.Contains(terms[j]);
// Check that at least one term is in the line
printIfAtLeastOneMatches |= line.Contains(terms[j]);
}
String splitter[] = array[i].split(" ,");
if (printIfAllMatch) {
System.out.println(Arrays.toString(splitter));
}
if(printIfAtLeastOneMatches) {
System.out.println(Arrays.toString(splitter));
}
}
//I'm not sure why you're returning the original array as a string
//I would think it would make more sense to return an Array of filtered data.
return Arrays.toString(array);
}
This does not take name ordering into account. If that's what you're going for, then I would suggest making a class and parsing each line in the file as an new object and trying to match the first term provided with the first name and second term provided with the last name, or something to that effect.
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();