New to vectors passing parameters
I am implementing a searching method for my first program using Vectors
But it does not work not sure why??
The program runs but the search is unsuccessful.
Thank you for time and interest.
Code :
import java.util.*;
public class test {
public static void main(String[] args) {
Customer dan = new Customer("dan rogers","13 apple road",8787);
Customer carl = new Customer("carl","17 peach road",89);
Customer michael = new Customer("michael ford","345 apple road");
Vector<Customer> cu = new Vector<Customer>();
cu.add(dan);
cu.add(carl);
cu.add(michael);
Scanner sc = new Scanner(System.in);
String c = sc.nextLine();
searchVector(cu,c);
}//end main
// Search Method
public static void searchVector(Vector<Customer> v, String c ){
int i = v.indexOf(c);
if(i >=0){
System.out.println("Found "+ i);
System.out.println();
Customer temp = v.get(i);
System.out.printf("%s\t %s\t %s\t",temp.getName(),temp.getTelephone(),temp.getAddress());
System.out.println();
}
else {
System.out.println( c +" Does not exist");
}
} Search Method
}// end class
Re: New to vectors passing parameters
indexOf uses the equals method of an object...Customer and String are different objects, and if you do not define the equals method for Customer (no code to show either way) you will not find the object in question. What value of Customer is the String supposed to search anyway? A better method would be to loop through the vector, comparing the search string and the value you wish to search. An even better method would be to use a Map to key each customer based upon the values you wish to search with.
Re: New to vectors passing parameters
Quote:
Originally Posted by
osmaavenro
I am implementing a searching method for my first program using Vectors
But it does not work not sure why??
The program runs but the search is unsuccessful.
Thank you for time and interest.
Code :
import java.util.*;
public class test {
public static void main(String[] args) {
Customer dan = new Customer("dan rogers","13 apple road",8787);
Customer carl = new Customer("carl","17 peach road",89);
Customer michael = new Customer("michael ford","345 apple road");
Vector<Customer> cu = new Vector<Customer>();
cu.add(dan);
cu.add(carl);
cu.add(michael);
Scanner sc = new Scanner(System.in);
String c = sc.nextLine();
searchVector(cu,c);
}//end main
// Search Method
public static void searchVector(Vector<Customer> v, String c ){
int i = v.indexOf(c);
if(i >=0){
System.out.println("Found "+ i);
System.out.println();
Customer temp = v.get(i);
System.out.printf("%s\t %s\t %s\t",temp.getName(),temp.getTelephone(),temp.getAddress());
System.out.println();
}
else {
System.out.println( c +" Does not exist");
}
} Search Method
}// end class
Your parameters for searchVector are supposed to be v and c.
You have cu and c.
int i = v.indexOf(c);
if c isn't in there, what value will i be?
Also, maybe Scanner should be static, I'm not positive on that one.
Re: New to vectors passing parameters