I am trying to create a find method, that will check every entry in my PhoneDirectory, and return the position of the name that matches the name given in the parameter. This is what currently have:
private String find(String name) {
for (DirectoryEntry x : theDirectory) {
if (x.getName().equals(name)) {
return x.getName();
}
}
return null;
}
However I will be calling my find function from within other methods that don't necessarily want the name returned, but instead the number attached to the name, (each DirectoryEntry has a name and a telno).
Any help regarding how to return the position of the array instead of just the matching name, would be much appreciated.
you can take a couter to count the postion
private int find(String name) {
int i = 0;
for (DirectoryEntry x : theDirectory) {
if (x.getName().equals(name)) {
return i;
}
i++;
}
return -1; // returning -1 if not found
}
or you can use normal for loop instead of foreach
private String find(String name) {
int k=0;
for (DirectoryEntry x : theDirectory) {
if (x.getName().equals(name)) {
k++;
return x.getName();
}
}
//k will give you pos
return null;
}
If you want the position in the array, use a regular loop instead of a foreach loop.
for (int i=0;i<theDirectory.length;i++) {
DirectoryEntry x = theDirectory[i];
if (x.getName().equals(name)) {
return i;
}
}
Depending on the type of your theDirectory-field you could use an own counter up to its length:
private int find(String name) {
for (int i = 0; i < theDirectory.length(); i++) {
DirectoryEntry x = theDirectory[i]; //If it is an Array; for Lists use get etc...
if (x.getName().equals(name)) {
return i;
}
}
return -1;
}
Why not to avoid reinventing the wheel and use Guava instead:
private int find(String name) {
return Iterables.indexOf(theDirectory, new Predicate<DirectoryEntry>() {
public boolean apply(DirectoryEntry de) {
return de.getName().equals(name);
}
});
}
Related
I have two Arraylist.
ArrayList workerlist and Arraylist workernamelist
public class Workers {
private String worker_id;
private String worker_name;
public String getWorker_id() {
return worker_id;
}
public void setWorker_id(String worker_id) {
this.worker_id = worker_id;
}
public String getWorker_name() {
return worker_name;
}
public void setWorker_name(String worker_name) {
this.worker_name = worker_name;
}
}
The Arraylist workernamelist list contains all the worker name in strings.
I want to search through the ArrayList workerlist weather it contains the wokrername in workerlist if it matches with the worker name then it will return corresponding worker id .
I think we only need to traversal the whole workers list, and for each worker, compare it's name with the given worker_name, if they're equal, return the worker's id. If such worker does not exist or the worker_name is null you can return null.
public String findWorkerId(ArrayList<Workers> workerList, String workerName) {
if (workerList == null || workerName == null) {
return null;
}
for (Workers worker : workerList) {
if (workerName.equals(worker.getWorker_name())) {
return worker.getWorker_id();
}
}
return null;
}
public Workers searchWorkers(ArrayList workers,String worker_name){
int len = workers.size();
for(int i = 0; i<len; i++){
your logic
enter code here
}
}
you need a for loop to look through the array list then if any match do display the match or whatever you want to do.
for(int i =0: i< workernamelist.size(); i++){
if(workernamelist.worker_ID = worker_ID){
system.out.println(workerlist.worker_ID);
}
}
Try this,
public String searchs(ArrayList list_workers,String worker_name){
for(int i = 0; i<list_workers.size(); i++){
if(list_workers.get(i).getWorker_name.equals(worker_name)
{
String worker_id=list_workers.get(i).getWorker_id();
Log.d("TAG","worker_id:"+worker_id);
return worker_id;
}
}
return null;
}
You can do something like this:
ArrayList<String> workernamelist=new ArrayList<>();
ArrayList<Workers> workersArrayList=new ArrayList<>();
for(int i=0;i<workernamelist.size();i++)
{
for(int j=0;j<workersArrayList.size();j++) {
if (workernamelist.get(i).equalsIgnoreCase(workersArrayList.get(j).getWorker_name()))
{
String id=workersArrayList.get(j).getWorker_id();
}
}
}
I'm working on a program to manipulate chemical formulae, and I'm writing a method which needs to loop through an ArrayList called "terms" and return the first one alphabetically.
e.g. terms = {Term('H',4),Term('C',2),Term('H',4),Term('C',1)} would return Term('C',2)
I've written this code so far but it's not working. I'm a real beginner to the Java language.
public Term nextElement()
{
int i = 0;
for (i = 0; i < terms.size()-1; i++)
{
int j = 1;
while (i + j <= terms.size())
if (terms.get(i).getElement() > terms.get(i+j).getElement())
{
terms.remove(i+j++);
return terms.get(i);
}
}
return null;
}
I'd appreciate any ideas or suggestions to solve this problem. Thanks!
You have two options here:
Let your Term class implement Comparable interface and override its compareTo() method. Then you can use Collections.sort(listOfTerms) to sort them and loop through.
Add class TermComparator which implements Comparator interface, use Collections.sort(listOfTerms, new TermComparator()) and loops through the sorted list.
1- you can implement Comparable and override compareTo()
int compareTo(Object obj){
Term term = (Term)obj;
if(term.getElement < this.getElement())
return 1;
else if (term.getElement == this.getElement())
return 0;
else
return -1;
}
then use
Collection.sort(terms);
2-
public Term nextElement()
{
char minElement = 'Z';
int index = 0;
for (int i = 0; i < terms.size(); i++)
{
if (terms.get(i).getElement() < minElement)
{
minElement = terms.get(i).getElement();
index = i;
}
}
Term temp = terms.get(index);
terms.remove(index)
return temp;
}
use Collections.sort(terms);it will arrange the list alphabetically.
This is what you need to do:
List<Term> terms = //your list
Collections.sort(terms, new Comparator<Term>() {
#Override
public int compare(Term t1, Term t2) {
return t1.getElement().compareTo(t2.getElement());
}
});
CODE:
public class CodeSample {
public static void main(String[] args) {
List<Term> terms=new ArrayList<Term>();
terms.add(new Term('H',4));
terms.add(new Term('C',2));
terms.add(new Term('H',4));
terms.add(new Term('C',1));
System.out.println("Before Sorting");
for(Term term:terms){
System.out.print(term.toString().concat(" "));
}
Collections.sort(terms,new Comparator<Term>() {
#Override
public int compare(Term object1, Term object2) {
if (object1.getElement() != object2.getElement()) {
return object1.getElement() - object2.getElement();
} else {
return object2.getCount() - object1.getCount();
}
}
});
//Sorted terms
System.out.println("After Sorting");
for(Term term:terms){
System.out.print(term.toString().concat(" "));
}
}
public static class Term{
private char element;
private int count;
public Term(char element, int count) {
super();
this.element = element;
this.count = count;
}
public char getElement() {
return element;
}
public int getCount() {
return count;
}
#Override
public String toString() {
return "Term [element=" + element + ", count=" + count + "]";
}
}
}
OUTPUT:
Before Sorting
Term [element=H, count=4] Term [element=C, count=2] Term [element=H, count=4] Term [element=C, count=1]
After Sorting
Term [element=C, count=2] Term [element=C, count=1] Term [element=H, count=4] Term [element=H, count=4]
One of my methods is not working in my Java implementation of the Set class. Why does equals always return false?
public boolean equals(Set<E> s) {
if(this.size() == s.size()){
for(int i = 0; i < size(); i++){
if(theData[i] == s.get(i)){
return true;
}
}
}
return false;
}
My set is Set<Integer> and I've compared a set of (1,2,3,4) and (1,2,3,4) together and it outputs false.
EDIT: All of my sets are ordered from least to greatest.
EDIT2: Here is my code dealing with equals in the main driver
else if(spaceSplit[0].equals("equal")){
if(spaceSplit.length == 3){
String fSet = spaceSplit[1];
String sSet = spaceSplit[2];
int fSetIndex = 0;
int sSetIndex = 0;
for(int i = 0; i < sets.size(); i++){
if(((Set<Integer>) sets.get(i)).getName().equals(fSet)){
fSetIndex = i;
}
}
for(int i = 0; i < sets.size(); i++){
if(((Set<Integer>) sets.get(i)).getName().equals(sSet)){
sSetIndex = i;
}
}
System.out.println(sets.get(fSetIndex).equals(sets.get(sSetIndex)));
} else {
System.out.println("Parameters entered wrong, please try again.");
}
EDIT3: In my program I've been messing with it, and it outputs false everytime I put a real set in. If I just made up 2 sets that don't exist and call the equals method, it outputs true. I'm so confused.
EDIT4: Here's more of the set code:
import java.util.*;
public class Set<E extends Comparable> {
private String name;
private int size = 0;
private E[] theData;
private static final int INITIAL_CAPACITY = 100;
private int capacity = 0;
public Set() {
capacity = INITIAL_CAPACITY;
theData = (E[]) new Integer[capacity];
}
public Set(String name) {
this.name = name;
capacity = INITIAL_CAPACITY;
theData = (E[]) new Integer[capacity];
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private void reallocate() {
capacity = 2 * capacity;
}
Your problem is you aren't overriding equals()
The signature is not
public boolean equals(Set<E>)
It is
public boolean equals(Object)
That is why when you add the #Override annotation you get a compiler error. You must use Object as the parameter, then check for instanceof and cast.
The compare should be .equals instead of ==.
try like this:
public boolean equals(Set<E> s) {
if(this.size() == s.size()){
for(int i = 0; i < size(); i++){
if(!this.get(i).equals(s.get(i))){
return false;
}
}
return true;
}
return false;
}
Intro
My code to do a custom sort by using Comparable is not work the way I want it to. I'm basically taking an Array of directories and sorting them by:
First number of directories, the fewer comes first.
If it's a tie alphabetically.
The problem
An example of an input you be:
["/", "/usr/", "/usr/local/", "/usr/local/bin/", "/games/",
"/games/snake/", "/homework/", "/temp/downloads/" ]
Which should return this:
["/", "/games/", "/homework/", "/usr/", "/games/snake/",
"/temp/downloads/", "/usr/local/", "/usr/local/bin/" ]
But for some reason my code is return this:
["/", "/usr/", "/games/", "/homework/", "/usr/local/",
"/games/snake/", "/usr/local/bin/", "/temp/downloads/" ]
My code [edited with comments]
import java.util.*;
public class Dirsort { public String[] sort(String[] dirs) {
//Creates Array list containing Sort object
ArrayList<Sort> mySort = new ArrayList<Sort>();
//Loop that gets the 3 needed values for sorting
for (String d: dirs){
String [] l = d.split("/");//String array for alphabetical comparison
int di = d.length();//Length of array for sorting by number of directories
mySort.add(new Sort(di,l,d));//adds Sort object to arraylist (note d (the entire directory) is needed for the toString)
}
Collections.sort(mySort);//sorts according to compareTo
String [] ans = new String [mySort.size()];//Creates a new string array that will be returned
int count = 0;//to keep track of where we are in the loop for appending
for (Sort s: mySort){
ans[count] = s.toString();
count++;
}
return ans;
}
class Sort implements Comparable<Sort>{
private int d;//number of directories
private String [] arr;//array of strings of names of directories
private String dir;//full directory as string for toString
//Constructor
public Sort(int myD, String [] myArr, String myDir){
d = myD;
arr = myArr;
dir = myDir;
}
//toString
public String toString(){
return dir;
}
#Override
public int compareTo(Sort arg0) {
// TODO Auto-generated method stub
//If they are the same return 0
if (this.equals(arg0)){
return 0;
}
//if the directories are empty
if("/".equals(arg0.dir)){
return 1;
}
if ("/".equals(this.dir)){
return -1;
}
//If they are not the same length the shorter one comes first
if (this.d != arg0.d){
return this.d - arg0.d;
}
//If they are the same length, compare them alphabetically
else{
for (int i = 0; i < arg0.d; i++){
if (!this.arr[i].equals(arg0.arr[i])){
return this.arr[i].compareTo(arg0.arr[i]);
}
}
}
return 0;
}
}
}
The bug is here:
for (String d: dirs){
String [] l = d.split("/");
int di = d.length(); // <- here
mySort.add(new Sort(di,l,d));
}
Because there you are comparing the length of the entire directory String, not the number of 'folders' in the directory. That's why "/usr/" comes before "/homework/", for example, because:
"/usr/".length() == 5
"/homework/".length() == 10
I believe what you wanted was this, using the length of the split:
int di = l.length;
Then the output is:
/
/games/
/homework/
/usr/
/games/snake/
/temp/downloads/
/usr/local/
/usr/local/bin/
There's another small bug though (possibly), which is that calling split on a String that starts with the delimiter will result in an empty String at the beginning.
IE:
"/usr/".split("/") == { "", "usr" }
So you might want to do something about that. Though here it means that all of them start with the empty String so it doesn't end up with an effect on the way you're doing the comparison.
And as a side note, it's also true what #JBNizet is suggesting that giving your variables more meaningful names helps a lot here. fullDir.length() and splitDir.length would have made this much easier to spot (and it may have never happened in the first place).
Here's a fixed version of your code, which handles the case where both directories are "/", which removes the unnecessary, and incorrectly passed length of the parts array, and which uses more meaningful variable names:
public class Dirsort {
public static void main(String[] args) {
String[] input = new String[] {
"/",
"/usr/",
"/usr/local/",
"/usr/local/bin/",
"/games/",
"/games/snake/",
"/homework/",
"/temp/downloads/"
};
String[] result = new Dirsort().sort(input);
System.out.println("result = " + Arrays.toString(result));
}
public String[] sort(String[] dirs) {
ArrayList<Sort> sorts = new ArrayList<Sort>();
for (String dir : dirs) {
String[] parts = dir.split("/");
sorts.add(new Sort(parts, dir));
}
Collections.sort(sorts);
String[] result = new String[sorts.size()];
int count = 0;
for (Sort sort: sorts) {
result[count] = sort.toString();
count++;
}
return result;
}
class Sort implements Comparable<Sort> {
private String[] parts;
private String dir;
public Sort(String[] parts, String dir) {
this.parts = parts;
this.dir = dir;
}
public String toString(){
return dir;
}
#Override
public int compareTo(Sort other) {
if (this.equals(other)){
return 0;
}
if("/".equals(other.dir) && "/".equals(dir)) {
return 0;
}
if("/".equals(other.dir)){
return 1;
}
if ("/".equals(this.dir)){
return -1;
}
if (this.parts.length != other.parts.length){
return this.parts.length - other.parts.length;
}
else {
for (int i = 0; i < other.parts.length; i++){
if (!this.parts[i].equals(other.parts[i])){
return this.parts[i].compareTo(other.parts[i]);
}
}
}
return 0;
}
}
}
I spotted the problem by simply using my debugger and make it display the value of all the variables.
public class Disort
{
public static String[] sort(String[] dirs)
{
ArrayList<Path> mySort = new ArrayList<Path>();
Path pathDir;
for(String dir : dirs){
pathDir = Paths.get(dir);
// check if directory exists
if(Files.isDirectory(pathDir)){
mySort.add(pathDir);
}
}
// sort the ArrayList according a personalized comparator
Collections.sort(mySort, new Comparator<Path>(){
#Override
public int compare(Path o1, Path o2)
{
if(o1.getNameCount() < o2.getNameCount()){
return -1;
}
else if(o1.getNameCount() > o2.getNameCount()){
return 1;
}
else{
return o1.compareTo(o2);
}
}
});
// to return a String[] but it will better to return a ArrayList<Path>
String[] result = new String[mySort.size()];
for(int i = 0; i < result.length; i++){
result[i] = mySort.get(i).toString();
}
return result;
}
}
I have an assignment that requires me to make ordered string list objects.
i currently have 2 ordered string lists, each with 7 string values in them.
im trying to create a method that merges list myList and yourList into a combined list combinedList.
here is what i have so far.
public boolean merge(OrderedStringList myList, OrderedStringList yourList){
int index;
String value;
for (index = 0;index < numUsed; index++){
value = myList.storage[index];
combinedList.insert(value);
}
for (index = 0;index < numUsed; index++){
value = yourList.storage[index];
combinedList.insert(value);
}
}
i declare the object combinedList in my main, and it doesnt recognize it in my orderedStringList.class
the insert function will insert strings into alphabetical order.
If you declared the combinedList inside your main function, it is accessible only inside the main function.
What you should do is create the combinedList inside the above function and return the result to the calling function i.e. your main function.
Where exactly is combinedList declared? Perhaps you should declare it outside outside your method so that all the methods can access it.
public class Merger {
private OrderedStringList combinedList; // This is a field
private int numUsed;
public static void main(){
new Merger().merge(new OrderedStringList(),new OrderedStringList());
}
public boolean merge(OrderedStringList myList, OrderedStringList yourList){
int index;
String value;
for (index = 0;index < numUsed; index++){
value = myList.storage[index];
combinedList.insert(value);
}
for (index = 0;index < numUsed; index++){
value = yourList.storage[index];
combinedList.insert(value);
}
return false;
}
}
class OrderedStringList {
public String[] storage;
public void insert(String value) {
// TODO Auto-generated method stub
}
}
Found out how to fix my problem. I just called the insert function based on the amount of strings that were in each list, and added them to the new combined list.
public boolean merge(OrderedStringList myList, OrderedStringList yourList) {
boolean result = false;
int index;
for (index = 0; index < myList.numUsed; index++) {
Insert(myList.storage[index]);
result = true;
}
for (index = 0; index < yourList.numUsed; index++) {
Insert(yourList.storage[index]);
result = true;
}
return result;
}