Searching a class array with multiple values per record - java

I need to search an object array for a Name and then print out all info corresponding to that name.
I have
public class AccessFriendlyFile {
private Friendlies[] fr = new Friendlies[100];
private int size = 0;
public AccessFriendlyFile (){
try {
Scanner scFile = new Scanner(new File("Friends.txt"));
String line, name, surname, cell, mail, landline;
while (scFile.hasNext()){
line = scFile.nextLine();
Scanner sc = new Scanner(line).useDelimiter("#");
name = sc.next();
surname = sc.next();
cell = sc.next();
if (sc.hasNext()){
mail = sc.next();
landline= sc.next();
fr[size] = new ExtendFriendlies(name, surname, cell, mail, landline);
}
else {
fr[size]= new Friendlies(name, surname, cell);
}
size++;
sc.close();
}
}catch (FileNotFoundException ex){
System.out.println("File not found");
}
How do I code a method that will search "fr" for a name and print out all corresponding info?
Many Thanks
Jesse
Edit:
Here is my Search method, that is currently not working.
public int Search(String name) {
int loop = 0;
int pos = -1;
boolean found = false;
while (found == false) {
if (fr[loop] == name) {
found = true;
pos = loop;
} else {
loop++;
}
}
return pos;
}
Incomparable types error on the if statement.

In your Friendlies class, have a method called getName() that will return the name of that Friendly. Iterate through the fr until you find the matching name. Once you've found that name, use similar get methods to print out all the information you want for the matching Friendly you just found.

I would suggest that you rename your variables here. The Friendlies class stores, I think, a single contact, a Friend. The list of Friend objects is an array that you might beter name friendList or even friendlies. I would also encourage you to not use size as a counter variable. Size is how many friends you have, and you can iterate through them using i, or friendCounter, or use a for each loop as I demonstrate below,
public Friendlies find(String name) {
for(Friendlies friend : fr) {
if(friend.getName().equalsIgnoreCase(name))
return fiend;
}
return null;
}
//now to print the info you can do this:
Friendlies findJoe = find("Joe");
if(findJoe==null)
System.out.println("You have no friends namd Joe.");
else
System.out.println(findJoe);
My code assumes that you implement toString() in Friendlies. If you use netbeans, you can auto-generate this code and then tweak it to get the format you want. (Just right-click where you want to write the method and choose insert code)

This should work:
public List<Friendlies> search(String name) {
List<Friendlies> list = new ArrayList<Friendlies>();
for(Friendlies friendlies : fr) {
if(friendlies.getName().equals(name)) {
list.add(friendlies);
}
}
return list;
}
Then, with the returned list, implement a nice display of the data :)

Assuming the AccessFriendlyFile loads the data into your array, you can use a for each loop, if you want to retieve all the matching names :
List<Friendlies> getByName(String searched){
List<Friendlies> result = new Arraylist<Friendlies>();
for (Friendlies currentFriendly : fr){
if (searched.equalsIgnoreCase(currentFriendly.getName()){
result.add(currentFriendly);
}
}
return result;
}
for only the first one :
Friendlies getByName(String searched){
for (Friendlies currentFriendly : fr){
if (searched.equalsIgnoreCase(currentFriendly.getName()){
return currentFriendly;
}
}
return null;
}
You should use lists instead of fixed arrays. If the files contains more than 100 records you'll get an indexoutofbounds exception.

Related

Java ArrayList add class object to list if object name is not already in the list?

I have looked through other questions but cant seem to find the answer I am looking for.
I am having trouble figuring out how to create a loop that adds a class object to an ArrayList only if it its name is not used in the list already.
This is the class I have.
package myPackage;
public class Cube {
private int length;
private String name;
public Cube(int initLength, String initName) {
this.length = initLength;
this.name = initName;
}
I would like to create new cubes and add them to a list. Here is the code I am trying to do this with.
In the while loop I can't figure out how to determine if the name has been used or not
package myPackage;
import java.util.ArrayList;
import java.util.Scanner;
public class PartFive {
public static void main(String[] args) {
ArrayList<Cube> cubelist = new ArrayList<>();
Cube oshea = new Cube (13, "oshea");
Cube mike = new Cube (7, "tony");
cubelist.add(oshea);
cubelist.add(mike);
Scanner reader = new Scanner(System.in);
while (true) {
System.out.println("enter cube name (blank quits): ");
String name = reader.nextLine();
if (name.equals("")){
break;
}
System.out.println("enter side length: ");
int length = Integer.valueOf(reader.nextLine());
Cube newcube = new Cube(length, name);
if(cubelist.contains(newcube.name)) {
// dont add to list
}
else {
cubelist.add(newcube);
}
}
reader.close();
System.out.println(cubelist);
}
}
Any constructive criticisms and suggestions are welcomed.
Replace
if(cubelist.contains(newcube.name)) {
dont add to list
}
else {
cubelist.add(newcube);
}
with
boolean found = false;
for(Cube cube: cubelist){
if(cube.getName().equals(name)) {
found = true;
break;
}
}
if(!found) {
cubelist.add(newcube);
}
The idea is to use a boolean variable to track if a cube with the same name as that of the input name already exists in the list. For this, iterate cubelist and if a cube with the same name as that of the input name is found, change the state of the boolean variable and break the loop. If the state of the boolean variable does not change throughout the loop, add the cube to the list.
From the code in your question:
if(cubelist.contains(newcube.name)) {
// don't add to list
}
else {
cubelist.add(newcube);
}
Method contains in class java.utilArrayList is the way to go but you need to be aware that method contains [eventually] calls method equals of its element type. In your case, the element type is Cube. Therefore you need to add a equals method to class Cube. I don't know what determines whether two Cube objects are equal, but I'll guess, according to your question, that they are equal if they have the same name, even when they have different lengths. I will further assume that name cannot be null. Based on those assumptions, here is a equals method. You should add this method to class Cube.
public boolean equals(Object obj) {
boolean areEqual = false;
if (this == obj) {
areEqual = true;
}
else {
if (obj instanceof Cube) {
Cube other = (Cube) obj;
areEqual = name.equals(other.name);
}
}
return areEqual;
}
Now, in method main of class PartFive you can use the following if to add a Cube to the list.
if (!cubelist.contains(newcube)) {
cubelist.add(newcube);
}
You can check for duplicate names in the cubelist array using lambda expressions (for better readability):
boolean isNameAlreadyExisting = cubelist.stream()
.anyMatch(cube -> cube.getName().equals(newcube.getName())); // this is returning true if any of the cubelist element's name is equal with the newcube's name, meaning that the name is already existing in the cubelist
if (!isNameAlreadyExisting) {
cubelist.add(newcube);
}
One thing that you should do is to remove the while(true) instruction which causes an infinite loop.
Another suggestion is to display the name of objects contained by cubelist, to see that indeed the names are not duplicated:
cubelist.stream()
.map(Cube::getName)
.forEach(System.out::println);

How can I compare all the values of an enum with a given array in java?

I have an enum class with values:
enum carBrand{BMW,HONDA,MERC,AUDI};
And there's an array called Sales with Array values:
sales[] = {CHEVVY, BMW , MERC, AUDI};
So how could I check that the sales[] has all the values of enum carBrand?
I'm trying to put it in a for loop as:
for(int i = 0; i<sales.length;i++){
if(carBrand.sales == sales[i]){
return true;
}
return false;
}
Add carBrand values to list
loop sales, remove the carBrand from the list
check if list is empty, if so they have all the values
Note: Class names should be names in PascalCase (CarBrand, Sales)
I would, personally, suggest using a list object rather than an Array where you are using such, however, this should work.
public static boolean checkArray(carBrand[] array) {
for (carBrand c : carBrand.values()) {
boolean found = false;
for (carBrand a : array) {
if (a == c) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
where the "array" parameter would be invoked as the sales object in your code.
This code will return false if not every enum value exists within your array.
Off-topic:
Things like this are actually all over the internet - here, google, even Bing (as garbo as Bing is), so searching before requesting help, probably a viable choice
public class Enumeration {
enum carBrand{BMW,HONDA,MERC,AUDI};
public static void main(String[] args) {
String sales[] = {"CHEVVY", "BMW" , "MERC", "AUDI"};
for(carBrand brand:carBrand.values()) {
boolean bran=false;
for(int i=0;i<sales.length;i++) {
if(brand.toString()==sales[i]) {
bran=true;
break;
}
}
if(!bran==true) {
System.out.println("Sales doesn't have " +brand);
}
}
}
}

Calling method Java

Im having difficulty understanding what exactly I should pass my third method in the main class with. Im really just sort of lost at this point. Any help would be awesome. Here is my code that I have written:
Also, here are the directions for boolean method called "getOrder":
Write a method called getOrder that takes an ArrayList of Strings as a parameter (the products ArrayList) and returns a boolean.
In the method body, prompt the user to enter a product name (a String), then check whether the product name exists in the ArrayList of strings.
If it exists, return true, otherwise return false.
public static void main(String[] args) {
// Call your methods here
bannerPrinter();
productBuilder();
getOrder(??); -----------------------------Confused as to what to pass this method with
}
// Write your methods below here
public static boolean getOrder(ArrayList<String> products) {
#SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.println("Please enter a product name: ");
String productName = in.nextLine();
if (products.contains(productName)) {
return true;
}
else {
return false;
}
}
public static ArrayList<String> productBuilder() {
ArrayList<String> products = new ArrayList<String>();
products.add("Desktop");
products.add("Phone");
products.add("TV");
products.add("Speaker");
products.add("Laptop");
return products;
}
public static void bannerPrinter() {
System.out.println();
System.out.println("******************************************");
System.out.println("****** Welcome to my eCommerce app! ******");
System.out.println("******************************************");
System.out.println();
}
}
You need to pass an ArrayList<String>. Looking at your code, you build one with productBuilder() which is otherwise unused. So:
ArrayList<String> products = productBuilder();
getOrder(products);
or
getOrder(productBuilder());
BTW, the following code:
if (products.contains(productName)) {
return true;
}
else {
return false;
}
is more easily written as
return products.contains(productName);
You would just pass an ArrayList. Like this:
ArrayList<String> lst = new ArrayList<String>();
lst.add("Phone");
lst.add("Laptop");
getOrder(lst);
You would fill your ArrayList first of course and then pass it.

Separate a comma separated value in an array list then put it back together

What I am trying to do exactly is creating a sorting program that sorts PatientRecords by whatever the user specifies in the command-line.
The program is operated on command-line and the user will input a text file containing the records as the first argument (args[0]), and how he wants it sorted as the second argument(args[1]).
The text file is formatted as: Lastname, Firstname, Age, Roomnumber for each line.
The amount of Lines is not specified and can vary, therefore I am using an Array list.
I can read in the lines and I got to where I could sort it by last name, but it looks like to me that the only way to do it is by separating the line at the commas and apprehending them individually in separate methods.
If there is a better way please let me know, I am open to anything. My main problem is getting the program to sort by the different categories, such as Age or RoomNumber.
Here is my code:
import java.io.*;
import java.util.*;
public class PatientRecord
{
public static void main(String args[]) {
System.out.println("Servando Hernandez");
System.out.println("Patient sorting Program.");
Scanner scan = null;
try
{
scan = new Scanner(new File(args[0]));
}
catch (FileNotFoundException e)
{
System.err.println("File path \"" + args[0] + "\" not found.");
System.exit(0);
}
ArrayList<String> lines=new ArrayList<String>();
while(scan.hasNextLine())
lines.add(scan.nextLine());
if(!(args.length == 0))
{
if(args[1] == lastname)
{
sortByLastName();
}
else if(args[1] == firstname)
{
sortByLastName();
}
else if(args[1] == age)
{
sortByAge();
}
else if(args[1] == roomnumber)
{
sortByRoomNumber();
}
}
}
static String sortByLastName()
{
Collections.sort(lines);
for(String x : lines)
System.out.println(x);
}
static String sortByFirstName()
{
}
static int sortByAge()
{
}
static int sortByRoomNumber()
{
}
}
Create a model class named Patient which has firstName, lastName etc.
class Patient{
String firstName;
String lastName;
// Constructor, getter, setter
}
I guess, text file line are comma separated. So, split the line into array and populate the List
List<Parent> patients= new ArrayList<>();
while(sc.hanNextLine()){
String[] values= sc.nextLine().split(",");
patients.add(new Patient(...))
}
Now, read the customer preferences from command line and sort the patients List.
String sortType= sc.next()
switch(sortType)){//Use java 7 or greater for string switch
case "firsname":
//Now sort the list by firstname using Comparator sort method.
break;
case "lastname":
....
}

Declaring an object array in java (code included)?

public class Pig {
private int pigss;
private Pig[] pigs;
public Pig[] pigNumber (int pigss)
{
pigs = new Pig [pigss];
return pigs;
}
Code that includes main method:
public class animals{
public static void main(String[] args){
Pig cool = new Pig();
Scanner keyboard = new Scanner (System.in);
System.out.println("How many pigs are there?");
int pigss = Integer.parseInt( keyboard.nextLine() );
cool.pigNumber(pigss);
//This is where I have trouble. I want to use the array pigs here in the main method, this is what i tried:
Pig[] pigs = cool.pigNumber(pigss);
I then tried to use a for loop and assign values (String) to the index of arrays (pigs[]). But the error that gives me is: cannot convert from String to Pig. Any tips are appreciated. THank you.
for(int j = 0; j < pigs.length; j++)
{
System.out.println("What is the pig " + (j+1) + "'s name");
pigs[j] = keyboard.nextLine();
}
Your pigs will need an attribute to contain the string values you are trying to pass:
public class Pig {
private String name;
public void setName(String n) {
name = n;
}
public String getName() {
return name;
}
Then when you want to assign this string value to your pig:
int indexOfPig = 0; // Or whatever it is supposed to be
pigs[indexOfPig].setName("I am a string");
In java you can only use ints as the indexes of arrays
It is saying 'cannot convert from String to Pig' because you can't do that!
If you want somehow convert a String to a Pig, you are going to need to write some code to do the conversion. For example, you might write a constructor that creates a new Pig from some kind of description. Or you might write a method that looks up a Pig by name or number or something.
It is hard to offer any more concrete advice because you don't tell us what is in the string values ... or how you expect the strings to become pigs. (The only suggestion I have is to try Macrame :-) )
Pig doesn't have a name member or even method that accepts a string. Also you are trying to assign a String(keyboard.nextline() to a Pig(pigs[j].
Add an attribute name to your pig.
class Pig{
public String name:
public void Pig(String name){
this.name = name;
}
}
Then assign a new instance of Pig in the loop.
pigs[j] = new Pig(keyboard.nextLine());
Also get rid of the useless class pigNumber. All you need is an ArrayList of Pigs. The array list can be dynanically sized.
List<Pig> pigs = new ArrayList<Pig>
so your loop could be something like
String name = ""
while(true){
name = keyboard.readline();
if(name== "stop"){
break;
}
pigs.add(new Pig(names);
}
Then getting the number of pigs is a simple
System.out.println(pigs.length());

Categories

Resources