java : Make it the best "Searching method" - java

I have design the search method. According to my requirement, If a user wants to search a customer’s record, he/she can input the customer’s family name or given name into the name text field and then click the search button. The following two screen shots show an example of the events before and after button click (with input the name to be searched is Lee)
And below is the code for searching. It is working fine but I want to make it better?
private void search()
{
String studentName=CNameTextField.getText();
String record="";
int count=0;
for(int i=0; i<myList.size();i++)
{
String name=myList.get(i).getName();
String [] splitName= name.split(" ");
if(studentName.equals(splitName[0]) || studentName.equals(splitName[1]))
{
count++;
record=record+"\n"+myList.get(i).toString();
}
display.setText("");
display.append(count + " result(s) found for "+ studentName);
display.append("\n "+ record);
}
}

So you've basically got a list of String items, and you're searching through all of them for the value?
My recommendation would be to create Objects for each line in your DisplayArea, rather than Strings. For example, when you read in the input file for your DisplayArea, do the split() for each line and create objects of type Customer that have fields called ID, name, room, etc. This would be better OO programming anyway - Strings don't really have any meaning, whereas a Customer has meaning.
If you do this, in the search you can simply loop over all the Customers in the list, asking whether the name.equals(customer.getName()); This would remove the need to split the line every time you search.

Related

Comparing an inputted string to multiple strings efficiently

I'm new to Java, and I can't seem to find exactly what I'm looking for on this website. Apologies if it has already been answered in the past!
Essentially, I'm trying to compare a user inputted string to multiple strings pre-established in the program as a "database".
As an example
System.out.println("Enter a name to check the database");
Scanner names= new Scanner(System.in);
String nameinput= names.next();
if(!nameinput.equals( *[ database]?* )
System.out.println("There is no such name, you cannot continue");
How do I check if the inputted string is not equal to the entire database individually?
I have the database set up simply as
class database
{String name, name, name, name... etc.}
I'm trying to stick to keeping things simple and using the database, if at all possible.
I understood that you have a class that contains individual names as fields. It seems like you are looking for a simple collection instead:
List<String> database = Arrays.asList("item1", "item2", "item3");
System.out.println("Enter a name to check the database");
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
if (database.contains(input)) {
System.err.println("There is no such name, you cannot continue");
}
Arrays.asList simply initializes the collection with the 3 items. You can later dynamically add or remove items with database.add or database.remove.
I suggest reading about Java collections and their usage
I suggest to make a list of all the names available in the database. So database class will have a method like
public List getData ()
It will return all the available names. To make the comparison easier, you can try to have the names in the list as uppercase or lowercase using .toUpperCase() or .toLowerCase()
So when you get the input string from user, convert that string to uppercase or lowercase based on your data.
Then simply you can check if this input string is part of list using contains method.
something like,
if(!availableNames.contains(inputName))
System.out.println("There is no such name, you cannot continue");

How to get corresponding data from different arrays

I have 2 arrays that have corresponding data, one has 20 names and another 20 grades, Im asking the user to enter a name and then taking the name and matching it up to the grades file and returning the grade, how would I go about doing that.
Ive tried doing something like this then returning g which refers to grade and getName refers to the name input from the user. Also getName is a string and g is an int array.
getName.length() = g.length;
Would I have to scan through the grades file to find that exact line with the corresponding grade? Im not really sure how to achieve this.
Since your question does not provide the relevant data, I'll try to answer your question with my own variable names, and you can cross check my code with yours.
Assuming the names are stored in the String array names[], and the marks are in the int array marks[], and getName contains the name to be found,
int FoundMarks = 0;
for(int i = 0; i < names.length; i++)
{
if(names[i].equalsIgnoreCase(getName))
{
FoundMarks = marks[i];
break;
}
}
System.out.println("Marks of "+getName+": "+FoundMarks);
This is a simple Linear Search which takes each individual name of names and checks if the user is searching for that particular one. If found, then the marks of that person is stored in FoundMarks, and the looping stops.
This type of searching algorithm will be incredibly useful in almost all array related operations.
I repeat, the variable names might be different than yours, but the core logic remains the same.

Java seeing if list contains string

I'm trying to iterate through a list line by line to check if a string the user inputs can be found and if so that line is printed. This is what i have so far
while(true) {
System.out.println("Please enter a hill name or quit to exit: ");
String HillName = input.next();
if (HillName.equals("quit")) {
break;
}
else {
for(int i=0; i < HillList.size(); i++) {
if (HillList.get(i).contains(HillName)) {
System.out.println(HillList.get(i));
}
}
}
}
I'm getting an error over contains saying cannot resolve symbol method contains java lang string, any help is appreciated.
The problem is that the reference type of the HillList.get(i) expression doesn't have a contains method. HillList has type List<Hill>, so HillList.get(i) has type Hill.
You could add a contains method to the Hill class; but I wouldn't expect a Hill to have a contains method - what do hills contain, other than rock, peat and the occasional hydroelectric power station? :) I certainly wouldn't expect a contains(String) method to return true if its name contains the parameter.
It looks like you're actually trying to print hills whose names contain some substring. For instance, if you entered Ben, you might print the Hill instances for Ben Nevis, Ben Lawers, etc. If this is the case, it looks like a much more logical check is to get the name of HillList.get(i), and call contains on that, e.g.
if (HillList.get(i).getName().contains(HillName)) {
// ...
}
You've not given a definition of the Hill class, so I'm assuming there's an accessor for the name like this. But it doesn't have to be like that: you could call HillList.get(i).toString().contains(HillName), or something else, provided that method returns strings which contain the thing you're looking for.
Note that a better way to write the loop is to use an enhanced for loop:
for (Hill hill : HillList) {
if (hill.getName().contains(HillName)) {
System.out.println(hill);
}
}
Repeatedly calling HillList.get(i) is more verbose, error-prone, and potentially less efficient if HillList is e.g. a LinkedList.
(Also note that HillList should be called hillList by convention, since variables start with lower-case letters).
This code will cover the case where you have your hill name in several rows of your list. Just setup $$getYourHillProperyName$$ with a getterMethod of the property you want to search.
while(true) {
System.out.println("Please enter a hill name or quit to exit: ");
String HillName = input.next();
if (HillName.equals("quit")) {
break;
}
else {
events
.stream()
.filter(e-> e.$$getYourHillProperyName$$.contains(HillName))
.forEach(xx->System.out.println(xx));
}
You don't need that "for" just use the contains as you have tried.

Ask user to choose from array

I'm practicing Java and wanted to let the user choose an option from the Array such as:
String Food[] = {"Beans","Rice","Spaghetti"};
So far I only know of Scanner, but this is my first program so I don't know much of the subject.
Also, is there a way to print it? besides doing:
System.out.println(Food[0]); //and so on
for every single one of them.
Edit: not a Array list.
You can print the Array not ArrayList by doing:
System.out.println(Arrays.toString(Food));
It will print out: [Beans, Rice, Spaghetti]
If you are talking about an ArrayList, you would have to do:
ArrayList<String> Food = new ArrayList<String>();
Food.add("Beans");
Food.add("Rice");
Food.add("Spaghetti");
Then, you can loop over the ArrayList and build your own String with a StringBuilder
After reading your comment, I think you have a problem structuring your program. I will help you with that. Basically you have to complete these steps:
Program starts
Program outputs the options available in the menu
Program asks the user to choose one of the listed options
User chooses an option
Program will repeat step 3, only if the user wants to keep adding stuff to his order.
If the user does not want anything else, the Program outputs the total cost of the order
Some ideas of how to achieve this the right way:
I would use a class to encapsulate the characteristics of an "order". For instance: description, name, and price are important stuff that you need to be able to track per item.
when you don't know how many times your program will run, you have two options: using a do while loop or a while loop. Try to think in a condition that could make your program run indefinitely a number of times until the user is done. Inside the loop, you could have a sum variable where you would keep track of the items that the user wants.
It is better to keep track of items by just using numbers than Strings. Computers are faster to find stuff this way. So, if you use a HashMap to mock a database system in your program, it would make it better and faster. Then, instead of using if else to control your flow, you could use a switch instead.
I hope this helps.
EDIT: For a more efficient way of printing out the contents of the array, use an enhanced for-loop:
for(String f : Food)
{
System.out.println(f);
}
This is effectively the same as:
for(int i = 0; i < Food.size(); i++)
{
System.out.println(Food[i])
}
If I'm understanding what you're trying to do correctly, I think this should suffice (disclaimer, it's been a while since I've worked with Scanner():
public static void main(String[] args)
{
String[] food = {"Beans","Rice","Spaghetti"}; // Java standards are lowercase for variables and objects, uppercase for class names.
Scanner in = new Scanner(System.in);
System.out.println("What would you like to eat? Options:");
for(String f : food)
{
System.out.println(f);
}
String response = in.next();
boolean validEntry = false;
for(String f: food)
{
if(response.equalsIgnoreCase(f))
{
validEntry = true;
}
}
if(validEntry)
{
System.out.println("You chose " + response);
}
else
{
System.out.println("Invalid entry. Please retry.")
}
}

How do I search through my JList?

I have a swing application am working on, my application lets the user enter a first name, last name, and phone number. the the user clicks the add button and it adds the entries into the jlist(so it like a phone book). I have a jTextfield above the JList in which I want to allow the user to search for a specific name or phone number on the Jlist, so its kind like a google search you type a character and it shows names with relevant characters in the JList and such. Am really stuck and lost at this point any help would be appricated??
This is my add button code to add names to my Jlist:
private void btnAddContactActionPerformed(java.awt.event.ActionEvent evt) {
String firstName = txtFirstName.getText();
String lastName = txtLastName.getText();
String phoneNum = (txtPhoneNum.getText());
NumberFormat number = NumberFormat.getNumberInstance();
//Phone Number formatted
StringBuilder sb = new StringBuilder(phoneNum).insert(0, "(")
.insert(4,")").insert(8,"-");
String phoneNumFormatted = sb.toString();
contactsArrayList.add(firstName + "\t " + lastName + "\t " + phoneNumFormatted);
DefaultListModel<String> model = new DefaultListModel<>();
for(int i = 0; i < contactsArrayList.size(); i++)
{
String myArraylst = contactsArrayList.get(i);
model.addElement(myArraylst + "\t");
}
listPhoneBookContacts.setModel(model);
txtFirstName.setText("");
txtLastName.setText("");
txtPhoneNum.setText("");
}
It is possible to implement this kind of stuff in Swing, but it is gnarly and you are unlikely to do a good job of it (because it's hard). You're probably better off leaving it to some other library, like SwingX. They have a bunch of components you can use that might do exactly what you want.
If you don't want to use that, a quick Google search reveals a good tutorial for filtering JLists.
my application lets the user enter a first name, last name, and phone number
I would use a JTable to display all this information.
so its kind like a google search you type a character and it shows names with relevant characters
JTable has built in filtering. See Sorting and Filtering for a working example

Categories