How to search for ID number in java? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
My problem is I need to make a program where you can search for an employee based on their ID number. Which needs to be something like "E1" or "E2". I am struggling to find a way to search for numbers and letters in the same object. It only works when I use just a number like 1 or 2 by using Int.
How can I store both a letter and integer in an object? Is there something similar to String that stores letters or Int that stores numbers but for both letters and numbers?
Ex. I can search for my employe already but their ID is currently just "1" or "2" or "3". I need to change it to "E1" or "E2" etc. But it wont work with String or Int.
I am searching an array. In an employee class

You can check, if two Strings are equal, by using the equals method: String1.equals(String2);
Also, you could implement a new class implementing the interface Comparable. In this class you could split the ID into a String and an Integer part:
public class EmployeeID implements Comparable {
String s = null;
Integer i = null;
public EmployeeID(String s, Integer i) {
this.s = s;
this.i = i;
}
#Override
public void equals(EmployeeID id) {
return new String(s + i).equals(new String(id.s + id.i));
}
#Override
public void compareTo(EmployeeID id) {
return new String(s + i).compareTo(new String(id.s + id.i));
}
}
Of course, if you do not need to compare elements (which can be useful for sorting), you can just implement this wrapper class without the comparable interface.
The equals method compares two ids and is not implemented in the Comparable interface, but the Object class, which is the superclass of every class.

No code provided so I'm guessing as to what you actually are trying to do.
public class SomeIds {
private String[] ids;
public boolean isPresent(String id) {
for (String element : ids) {
if (element.equals(id)) {
return true;
}
}
return false;
}
/**
* returns the index of the first element matching the id
* provided or -1 if it is not found
*/
public int indexOf(String id) {
for (int index = 0 ; index < ids.length ; ++index) {
if (ids[index].equals(id)) {
return index;
}
}
return -1;
}
}

Unfortunately, you won't be able to mix types (i.e. numbers and letters). You'll have to use a String for storage of the ID, in which case, you can use equals to search:
String searchTerm = "E1";
for (Employee employe : employeeArr) {
if (employe.getId() == searchTerm) {
System.out.println("Employe_ID: E" + employe.getEmployeId() +
"\narbetstitel: " + employe.getArbetsTitel());
}
}
Better yet, use a HashMap so you don't have to loop to find an employee:
HashMap<String, Employee> employees = new HashMap<>(); // String to store IDs
Employee e = new Employee();
employees.put("E1", e);
// To fetch an employee
Employee e1 = employees.get("E1");
if (e1 != null) {
System.out.println("Employe_ID: E" + e1.getEmployeId() +
"\narbetstitel: " + e1.getArbetsTitel());
}

Related

How to create a custom order to sort Java String phone number? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a list of Java String phone number & I need to sort out them based on their operator like - "013..." and "017..." they are both same operator number.
List<String> phoneNumberList = new ArrayList<String>();
phoneNumberList.add("01313445566");
phoneNumberList.add("01414556677");
phoneNumberList.add("01515667788");
phoneNumberList.add("01616778899");
phoneNumberList.add("01717889900");
phoneNumberList.add("01818990011");
phoneNumberList.add("01919001122");
When I print them, they look like -
01313445566
01414556677
01515667788
01616778899
01717889900
01818990011
01919001122
But I want to print them like this using custom order -
01313445566,
01717889900,
01414556677,
01919001122,
01515667788,
01616778899,
01818990011
How may I create a custom order to sort them as per my requirement?
Define your preferred order in a map
Map<String,Integer> order = new HashMap<>();
order.put("013", 1);
order.put("017", 2);
order.put("014", 3);
order.put("019", 4);
order.put("015", 5);
order.put("016", 6);
order.put("018", 7);
Then sort using map order value
list.sort(Comparator.comparing( e -> order.get(e.substring(0,3))))
Update: For java 6
Collections.sort(list, new Comparator<String>() {
#Override
public int compare(String e1, String e2) {
return order.get(e1.substring(0,3)).compareTo(order.get(e2.substring(0,3)));
}
});
Note: It will work if prefix exists in map.
A possible solution can be using object for phone numbers.
Consider the following code:
public class PhoneNumber implements Comparable{
private int operatorId;
private String phoneNumber;
private static final int GRAMEENPHONE = 1;
private static final int VERIZON = 2;
public PhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
char thirdDigit = phoneNumber.charAt(2);
if(thirdDigit == '7' || thirdDigit == '3') {
operatorId = GRAMEENPHONE;
} else if(thirdDigit == '4' || thirdDigit == '9') {
operatorId = VERIZON;
} else {
operatorId = 10; // a default value
}
}
public String getPhoneNumber() {
return phoneNumber;
}
#Override
public int compareTo(Object o) {
PhoneNumber pNumber = (PhoneNumber) o;
if(this.operatorId == pNumber.operatorId) {
return this.phoneNumber.compareTo(pNumber.getPhoneNumber());
}
return this.operatorId - pNumber.operatorId;
}
}
The main trick in this code is the operatorId. It is a number that represents different mobile operators/carrier company. This value is used in compareTo() method. And its value is used to determine which operator/carrier company's number should be on top.
And so the code for phone number list should look something like this:
List<PhoneNumber> phoneNumberList = new ArrayList<PhoneNumber>();
phoneNumberList.add(new PhoneNumber("01313445566"));
phoneNumberList.add(new PhoneNumber("01414556677"));
phoneNumberList.add(new PhoneNumber("01515667788"));
phoneNumberList.add(new PhoneNumber("01616778899"));
phoneNumberList.add(new PhoneNumber("01717889900"));
phoneNumberList.add(new PhoneNumber("01818990011"));
phoneNumberList.add(new PhoneNumber("01919001122"));
Collections.sort(phoneNumberList);
You may try sorting using a custom comparator:
Collections.sort(phoneNumberList, new Comparator<String>() {
#Override
public int compare(String s1, String s2) {
boolean s1Match = s1.matches("01[3479].*");
boolean s2Match = s2.matches("01[3479].*");
if (s1Match && !s2Match) {
return -1;
}
else if (!s1Match && s2Match) {
return 1;
}
else {
return s1.compareTo(s2);
}
}
});
System.out.println(phoneNumberList);
Using the sample list of 7 numbers you gave above, this prints:
[01313445566, 01414556677, 01717889900, 01919001122, 01515667788, 01616778899,
01818990011]
The expression String#matches("01[3479].*") will return true for those numbers beginning with 013, 014, 017, and 019. Thus, the custom comparator will place those numbers first, followed by all others. In the case of a tie, the natural string order will be used (which should be fine here, since the numbers all have the same width).
Well, you can use RuleBasedCollator to define your own Rules.
String customRules = "<013<017<014<019<015<016<018";
The above rule is decoded as that 013 and 017 are to appear before both 014 when comparing strings.
And then use the rule as below:
RuleBasedCollator myRuleBasedCollator = new RuleBasedCollator(customRules);
Collections.sort(phoneNumberList,myRuleBasedCollator);
phoneNumberList.forEach(System.out::println);
Output:
01313445566
01717889900
01414556677
01919001122
01515667788
01616778899
01818990011

Trouble converting strings of letters to integers

My program asks a question multiple times by an array but I need to get the answer from that String turned into the integer 1. Know I know how to convert any old String into it's integer counterpart if the string is a bunch of number i.e numbers = 12345 using Integer.parseInt(numbers). What happens if I have a character in the string but I want it to take an integer value of 1? I've got it set out this like this so far
String[] elements = {"Vote A for Football", "Vote B for Basketball"};
String question
int football = 0; // not sure if these should be strings or integers
int basketball = 0;
int tally;
for (String element : elements)
{
System.out.println(element);
}
question = JOptionPane.showInputDialog("What is your favourite sport?");
tally = Integer.parseInt(question);
The last line is the part that gets me because I want them to vote by either entering A or B but I also need the console to print how many times they have voted for that sport (it's an array exercise so the question will appear multiple times).
Welcome to SO. I'm not sure what you're asking, but it would be best to keep the storage of values as integers, and keep strings more of an interface to the user. This way you can readily calculate values without any conversion. Only when you present it to the user should you need to convert.
Having said that, if you are parsing a string (like "A" or "B"), you can store their response as a string, and then compare it against a list of known values using if and equals:
if ("A".equals(question)){
football++;
} else if ("B".equals(question)) {
basketball++;
} else {
// do nothing, process error, ask question again.
}
Also remember to close your statement when initializing your variable:
String question;
or
String question = "";
But as #Jean-François Savard mentions, the variable should make sense as well, so this would be clearer:
String userResponse = "";
Another approach to use Enums
public enum Game {
A {
#Override
public String getGame() {
return "Football";
}
#Override
public int getNumber() {
// TODO Auto-generated method stub
return 1;
}
},
B {
#Override
public String getGame() {
return "Basketball";
}
#Override
public int getNumber() {
// TODO Auto-generated method stub
return 2;
}
};
public abstract String getGame();
public abstract int getNumber();
}

Arraylist of Objects - How do I remove an entry?

I am doing homework and it states that I have to be able to remove a entry from an arraylist of objects.
I try to check if it contains the user id I want to remove but objects cannot contain strings
public class EmployeeProgramView extends FrameView {
ArrayList <information> database = new ArrayList <information>();
private void exitButtonActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {
information a;
String ID, firstName, lastName, startDate, annualSalary, linedUp;
ID = idInput.getText();
firstName = firstNameInput.getText();
lastName = lastNameInput.getText();
startDate = startInput.getText();
annualSalary = salaryInput.getText();
linedUp = (firstName+" "+lastName+" "+annualSalary+" "+startDate);
a = new information (ID, firstName, lastName, startDate,annualSalary);
database.add(a);
System.out.println(linedUp);
}
private void listButtonActionPerformed(java.awt.event.ActionEvent evt) {
String temp="";
for (int x=0; x<=database.size()-1; x++) {
temp = temp + database.get(x).ID + " "
+ database.get(x).first + " "
+ database.get(x).last + " "
+ database.get(x).start + " "
+ database.get(x).salary + "\n";
}
finalOutput.setText(temp);
}
private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {
String removeID;
removeID = idInput.getText();
if (database.contains(removeID)){
database.remove(removeID);
} else {
finalOutput.setText("No such ID in database");
}
}
class information{
String ID, first, last, start, salary;
information(String _ID ,String _first, String _last, String _start, String _salary){
ID = _ID;
first = _first;
last = _last;
start = _start;
salary = _salary;
}
}
}
So my question is? How do I remove a object?
The remove method will remove an object from array as long as .equals returns true when comparing that object and the object we are asking to remove. This is true for identical strings; other objects by defaults are only equal to themselves (still, you can add an object to array and retain another variable referring to it).
You can also always remove just by array index.
You may just need to use the method: List < T > #remove, to remove the object in question
Got it!
Thanks everyone for their input. really got my brain thinking different ways haha.
private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {
String temp, removeID;
removeID = idInput.getText();
for (int x = 0; x<=database.size()-1; x++){
temp = database.get(x).ID;
if(removeID.equals(temp)){
database.remove(x);
}
}
}
You have to iterate through the Array and find the ID you are looking for. Just add this into your main class:
public void removeInformation(ArrayList<Information> database, String removeID) {
for(int i = 0; i < database.size(); i++) {
if(database.get(i).getID().equals(removeID)) {
database.remove(database.get(i));
}
}
}
This is unrelated to your question, but by convention classes are named with a capital letter, so your "information" class should be titled "Information".
Also, I just wanted to say that, in case you didn't know, before you type your class you can type import statements. For example:
import java.awt.event.ActionListener;
This way you don't have to type "java.awt.event.ActionListener actionListener" every time you want to use that class.
see basically,
you need to remove an object information from arraylist if the list contains information whose id is same as removeid.
so before removing , you need to do a check for the information id in the list
so go for iterating list and find information in each iteration and check its id equlas to removeid
if equals then do list.remove(information)
for (Information information: database) {
// check for ID is same as remove id
// if equals remove that entire object from list
if (information.ID.equals(removeID)) {
// remove object with ID same as removeid
database.remove(information);
}
}

JAVA. Searching a value and displays the data [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
'm currently making a purchase program. I'm almost halfway done on it, the only thing i need is. when i Press 1 for purchase it will give me an option to input the Item Code that i stored in my inventory. And then it respectively displays the datas or values corresponds on my inputted code based on my stored products on my inventory.
PS: im new in java and i know my codes are still basic cus im still learning java on my own. And my variables are not yet changed into Arraylist cus i just found out that Arraylist is much better than a plain Array in storing collection of data.
Any suggestions is highly appreciated and welcome. Would stick on using Arraylist or Array. not Hashset or etc.. Thank you Guys!
Hope you guys could help me. Thanks!
class Item {
public final int sku;
public final String desc;
public final type other_fields;
public Item(int s, String d, type fields...) {
// set fields
}
}
or if you really want to be clever
abstract class Item {
public final int sku
// ....
}
class PinkCurtains extends Item {
public PinkCurtains() {
sku = 129534;
desc = "Adorable Pink Indoor Curtains";
}
}
class FuzzyTowel extends Item {
public FuzzyTowel() {
sku = 874164;
desc = "Machine Washable Fuzzy Towel";
}
}
then populate your list and search away
ArrayList<Item> catalog = new ArrayList<Item>(0);
for (int i = 0; i < numItems; i++) {
catalog.add(new Item(arg, arg, arg...));
}
// or
catalog.add(new PinkCurtains());
catalog.add(new FuzzyTowel());
for (Item item : catalog) {
if (chosenItem == item.sku) {
// do all your stuff
}
}
They are called Iterables for a reason. You don't have to make classes if you don't want to. ArrayList also has searching methods, contains() and indexOf() for example:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
If you want to fill in the fields as you go you can make a class that lets you do that:
class Item {
public int id;
public float price;
}
ArrayList<Item> cart = new ArrayList<Item>(0);
do {
Item item = new Item();
item.id = userInput;
item.price = userInput;
cart.add(item);
} while (userInputting);
float total = 0;
for (Item i : cart) {
total += i.price;
}
// using a regular for loop instead of for-each
for (int i = 0; i < cart.size(); i++) {
Item item = cart.get(i);
// or search for something particular
if (item.id == searchID) {
System.out.println("found item " + item.id + " with price $" + item.price);
}
// equivalent to
if (ids[i] == searchID) {
System.out.println("found item " + ids[i] + " with price $" + prices[i]);
}
}
Each time the user wants to add an item, you just make a new one, fill in the fields and add it to the list.

Access the value from list in java [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is one of my class
class number11 {
String ab;
int i;
public number11(String ab,int i) {
this.ab=ab;
this.i=i;
}
}
And in main method, I used
List<number11> n1= new ArrayList<number11>();
How can I access the value of integers and String contained in List? I do wish just to print them but to use further.
{Closed ,Thank you all}
Just loop over the list:
for (number11 n : list) {
String ab = n.ab;
int i = n.i;
//print ab and i
}
Note that number11 should be in CamelCase to follow Java's conventions: Number11.
From your question it seems you want list of your objects,
Before continuing, please create getters and setters, I've used them
Also your class name should be camelCase. Number11 is valid but not number11
You can fill the list using
List<number11> list = new ArrayList<number11>();
list.add(new number11("a",1));
list.add(new number11("b",2));
To access the members,
for (number11 n : list) {
String ab = n.getAb();
int i = n.getI();
}
like this
List<number11> n1= new ArrayList<number11>();
for(number11 n:n1){
System.out.println("String value: "+n.ab);
System.out.println("int value: "+n.i);
}
According to better coding standards.Follow the below rules
1.Change you class so that It starts with a camel case.
2.Change variables to private.
3.Add setter and getter methods
Assuming you have added values to the ArrayList you can read values by using code such as n1.get(0).ab or n1.get(0).i.
List l = new ArrayList<number11>();
l.add(new number11("x",1));
l.add(new number11("y",2));
for (number11 element : l) {
System.out.println(element.ab + " "+ element.i);
}
You might first want to add getter methods to your class number11.
e.g
public class number11{
String ab;
int i;
public number11(String ab,int i)
{
this.ab=ab;
this.i=i;
}
public int getI(){
return i;
}
public String getAb(){
return ab;
}
}
You need to obtain a reference to the particular object held inside the ArrayList via the get(index) method where index is the element number starting with 0. Simply call the getter methods to retrieve the values.
e.g
List<number11> n1= new ArrayList<number11>();
//Adding the object
n1.add(new number11("Test", 4));
//Retrieving the object.
number11 inst = n1.get(0);
//Retrieve and print the values
System.out.println(inst.getAb());
System.out.println(inst.getI());
For better convention change your class structure to,
class Number11 {
private String ab;
private int i;
public Number11(String ab,int i) {
this.ab=ab;
this.i=i;
}
public String getAb() {
return ab;
}
public void setAb(String ab) {
this.ab = ab;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
Access in this way.
List<number11> n1= new ArrayList<number11>();
if(n1!=null && n1.size()>0){
for (Number11 n : n1) {
String ab = n.getAb();
int i = n.getI();
//print ab and i
}
}
List<number11> n1= new ArrayList<number11>();
after adding values to this list n1 it will contains number11 type objects from index 0 to n-1, where n is number of element you added to list.
Then you can call what ever object as follows
n1.get(1) // this will return 2nd object in the list
It will contain ab and i
You can call them as follows
n1.get(1).getab // 2nd element ab value in list n1
n1.get(1).i // 2nd element i value in list n1
List Interface allows to:
Positional access — manipulates elements based on their numerical position in the list
MyClass obj = myList.get(24); //--get 25th item of a List<MyClass>--
Iteration access — extends Iterator semantics to take advantage of the list's sequential nature
for(MyClass obj : myList){ //-- go through all items of a List<MyClass> one by one--
int i = obj.someField;
}
Once you have your object, you can access its fields.

Categories