some problems on declaring and calling of fields in java - java

I'm trying to access some fields from some class, but i face trouble when i want to call them.
This is the class which i have declared the fields :
public class InfoOfFriends {
public static final String Friends_List = "friends_list";
public static final String userName = "username";
public static final String STATUS = "status";
public static final String PORT = "port";
public static final String Ip = "Ip";
public static final String UserKey = "userKey";
public static final String Message = "message";
}
And this is where i want to use them :
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException
{
if (localName == "friend")
{
InfoOfFriends friend = new InfoOfFriends();
friend.username = attributes.getValue(InfoOfFriends.userName);
String status = attributes.getValue(InfoOfFriends.STATUS);
friend.port = attributes.getValue(InfoOfFriends.PORT);
if (status != null && status.equals("online")) {
friend.status = InfoStatus.ONLINE;
mOnlineFriends.add(friend);
} else if (status.equals("unApproved")) {
friend.status = InfoStatus.UNAPPROVED;
mUnApprovedFriends.add(friend);
} else {
friend.status = InfoStatus.OFFLINE;
mOnlineFriends.add(friend);
}
}
else if (localName == "user")
{
this.userKey = attributes.getValue(InfoOfFriends.UserKey);
}
super.startElement(uri ,localName, name, (org.xml.sax.Attributes) attributes);
}
These parts have errors :
friend.username = attributes.getValue(InfoOfFriends.userName);
friend.port = attributes.getValue(InfoOfFriends.PORT);
friend.status = InfoStatus.ONLINE;
friend.status = InfoStatus.UNAPPROVED;
friend.status = InfoStatus.OFFLINE;
Thanks for your time friends...

first of all are you sure that attributes has the correct values?
and remember to use as string comparator the equals() method
if (localName.equals("friend"))
instead of
if (localName == "friend")

You can't assign new values to final fields. Remove the final keyword to resolve the error.
Also you made all of the fields static and use them as keys to retrieve stuff from Attributes, but at the same time you want to assign new values to them - probably a bad idea. Try doing a separate class with final static keys to use for the Attributes retrieving, and a separate Friend class to assign the retrieved values to.

Related

How to use variable of method from 1 class in 2 class via Java?

public static class One {
#Override
public String interact(String... values) {
String actualTextOne = "test";
return actualTextOne;
}
}
public static class Two {
#Override
public String interact(String... values) {
String actualTextTwo = "test";
/* Here I need to compare actualTextOne and actualTextTwo, but the problem is that I can't find solluction how to use actualTextOne in Two class*/
return actualTextTwo;
}
}
You cannot do that.
Please check variable scope in java.
https://www.codecademy.com/articles/variable-scope-in-java
A possible solution here is to call the method interact from the class One. Something like this
public static class Two {
#Override
public String interact(String... values) {
String actualTextTwo = "test";
One one = new One();
String actualTextOne = one.interact(values);
// compare values here
return actualTextTwo;
}
}
Why in your classes functions have parameters if you dont use it?
You can mark your class with static only if he is nested, else you need do like this:
class Two {
static public String interact(String... values) {
String actualTextTwo = "test";
return actualTextTwo;
}
}
String textOne = One.interact("");
String textTwo = Two.interact("");
System.out.println(textOne==textTwo);

Any way to get a specific entry by key in a Java hashmap(having inserted multiple values)?

I have a Java hashmap, to which multiple variables were added(ex.):
class client {
public static int clientIdentifier;
public static String clientName;
public static String clientFamilyname;
public static String clientBirthdate;
}
Inside the main method:
client newclient = new client();
HashMap<Integer, String> clients = new HashMap<>();
clients.put(newclient.clientIdentifier,
newclient.clientName +
newclient.clientFamilyname +
newclient.clientBirthdate
Where new client.clientIdentifier is the key and newClient.clientName/Familyname/Birthdate are already defined. They belong to an object newclient, it belonging to the class client
Is there any way to get only the value clientName from that hashmap, to compare later?
Looking for something like:
String requiredName = clients.get(scannedID, newclient.clientName);
(I know that it is totally wrong, but just to have an idea)
Thank you very much!
You need to make all the fields in Client non-static first! You'd want each instance of Client to have a different ID, name, and birthday, right?
Instead of using a HashMap<Integer, String>, use a HashMap<Integer, Client>:
Client newclient = new Client();
HashMap<Integer, Client> clients = new HashMap<>();
clients.put(newclient.clientIdentifier, newclient);
Now you can just do:
String requiredName = clients.get(scannedID).clientName;
But really though, the fields in the class Client should all be private and should be accessed via getters and setters. You also should not be able to reset the client's clientIdentifier as that is the map's key.
Client should look like this:
class Client {
private int clientIdentifier;
private String clientName;
private String clientFamilyname;
private String clientBirthdate;
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
this.clientName = clientName;
}
public String getClientFamilyname() {
return clientFamilyname;
}
public void setClientFamilyname(String clientFamilyname) {
this.clientFamilyname = clientFamilyname;
}
public String getClientBirthdate() {
return clientBirthdate;
}
public void setClientBirthdate(String clientBirthdate) {
this.clientBirthdate = clientBirthdate;
}
public int getClientIdentifier() {
return clientIdentifier;
}
public Client(int clientIdentifier, String clientName, String clientFamilyname, String clientBirthdate) {
this.clientIdentifier = clientIdentifier;
this.clientName = clientName;
this.clientFamilyname = clientFamilyname;
this.clientBirthdate = clientBirthdate;
}
}
Your hash map code will now look like:
Client newclient = new Client();
HashMap<Integer, Client> clients = new HashMap<>();
clients.put(newclient.getClientIdentifier(), newclient);
String requiredName = clients.get(scannedID).getClientName();
I would put the value in the hashmap something like this:
map.put(clientID,name+"+"+familyname+"+"+bithdate);
This way when I get the value from Map using the key, I would get a string like John+Wood+1994.
Now I can easily get the name by using substring.
Does this help ?

Updating a static final field from an instance initializer

Java prohibits access of a final static field from an initializer. For example:
public enum Example {
ValueA("valueAA", "valueAB"),
ValueB("valueBA", "valueBB");
final static Map<String, Example> exampleByPropertyA = new HashMap<>();
final String propertyA;
final String propertyB;
Example(String propertyA, String propertyB) {
this.propertyA = propertyA;
this.propertyB = propertyB;
Example.exampleByPropertyA.put(propertyA, this); // <- Not permitted
}
}
However, if the update to the static Map is performed in a separate method that is called by the initializer, this is fine. For example:
public enum Example {
ValueA("valueAA", "valueAB"),
ValueB("valueBA", "valueBB");
final static Map<String, Example> exampleByPropertyA = new HashMap<>();
final String propertyA;
final String propertyB;
Example(String propertyA, String propertyB) {
this.propertyA = propertyA;
this.propertyB = propertyB;
addExample(this);
}
private addExample(Example example) {
Example.exampleByPropertyA.put(example.propertyA, example); // <- Permitted
}
}
Given this context, my question is: Does a call to a member method constitute a "freeze action" or is it indicative to the JVM that the object is, for all intents and purposes, "initialized"? Curious why this makes a difference.
I've done some searching, but haven't found anything that articulates this well.
Thank you in advance!
Does a call to a member method constitute a "freeze action" or is it indicative to the JVM that the object is, for all intents and purposes, "initialized"? Curious why this makes a difference.
The problem is that your class is initialised top to bottom. This means your static fields have not been initialised yet i.e. your Map is null.
Another approach is to add a static initialisation block to be called after everything has been initialised.
static {
for (Example e: values()) {
addExample(e);
}
}
private static addExample(Example example) {
Example prev = exampleByPropertyA.put(example.propertyA, example);
assert prev == null;
}
NOTE: You can see a final variable before it is initialised. This means final can have a before and after value even without using reflection.
public class A {
final String text = getText();
private String getText() {
System.out.println("text= " + text);
return "is set";
}
public static void main(String... args) {
new A().getText();
}
}
prints
text= null
text= is set
Using reflection you can alter final fields even after initialisation though you should avoid doing this unless there is no other option.
The correct way to do what you're trying to do, is to write a static initializer, which runs after all the enums have been created.
Defensive programming: You should also add a simple check to guard against programming errors.
public enum Example {
ValueA("valueAA", "valueAB"),
ValueB("valueBA", "valueBB");
final static Map<String, Example> exampleByPropertyA = new HashMap<>();
static {
for (Example ex : values())
if (exampleByPropertyA.put(ex.propertyA, ex) != null)
throw new IllegalStateException("Duplicate propertyA: " + ex.propertyA);
}
final String propertyA;
final String propertyB;
Example(String propertyA, String propertyB) {
this.propertyA = propertyA;
this.propertyB = propertyB;
}
}

How would I use the result of a variable as a variable rather than plain text

The problem I have is "slowRotor" returns the value "Rotor_I".
I would like to use the result of slowRotor (Rotor_I) as the variable Rotor_I and not the "plain text" so to speak.
I'm wondering if that is possible in Java and if so, how it would be done (As i'm trying to avoid lots of if statements)
String slowRotor = GUI.getRotorInPosition("slow");
int position = (alphabet.indexOf(result));
String resultAfterRotor = "";
if (Rotor == "Slow") {
resultAfterRotor = Character.toString((slowRotor.charAt(position)));
}
And
static String alphabet ="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static String Rotor_I = "EKMFLGDQVZNTOWYHXUSPAIBRCJ";
I don't exactly know what you want and we could use a little more explanation, but I'm guessing your code would be something like:
if (rotor.equals("Slow")) {
resultAfterRotor = Character.toString((slowRotor.charAt(position)));
} else if (rotor.equals("Medium")) {
resultAfterRotor = // ... something else
} else if (rotor.equals("Fast")) {
resultAfterRotor = // ... something else
}
// ...
Instead you could use a switch statement which avoids doing a comparison for each case as you would with if-else-if-else-if. (for few cases though (~3 maybe), switch will compile to if-else bytecode since I guess that's fastest):
private final static String slowRotor = "EKMFLGDQVZNTOWYHXUSPAIBRCJ";
private final static String mediumRotor = "...";
private final static String fastRotor = "...";
public static void main(String[] args){
String rotor = GUI.getRotorInPosition("slow");
int position = (alphabet.indexOf(result));
String resultAfterRotor = getResultAfterRotor(rotor);
// ...
}
private String getResultAfterRotor(String rotor) {
switch(rotor){
case "Slow": {
return Character.toString(slowRotor.charAt(position));
}
case "Medium": {
return Character.toString(mediumRotor.charAt(position));
}
case "Fast": {
return Character.toString(fastRotor.charAt(position));
}
}
}
Or you could use a Map
private static final Map<String, String> rotorMap = new HashMap<>();
static {
rotorMap.put("Slow", "EKMFLGDQVZNTOWYHXUSPAIBRCJ");
rotorMap.put("Slow2", "...");
rotorMap.put("Slow3", "...");
}
public static void main(String[] args){
String slowRotor = GUI.getRotorInPosition("slow");
int position = (alphabet.indexOf(result));
String resultAfterRotor = Character.toString(rotorMap.get(slowRotor).charAt(position));
// ...
}

Lookup within the enum constants by constant specific data [duplicate]

This question already has answers here:
How to retrieve Enum name using the id?
(11 answers)
Closed 9 years ago.
I need to do look up in an enum by an int . The enum is as folows :
public enum ErrorCode{
MissingReturn(1,"Some long String here"),
InvalidArgument(2,"Another long String here");
private final int shortCode ;
private final String detailMessage;
ErrorCode(shortCode ,detailMessage){
this.shortCode = shortCode ;
this.detailMessage= detailMessage;
}
public String getDetailedMessage(){
return this.detailMessage;
}
public int getShortCode(){
return this.shortCode ;
}
}
Now Is need to have a lookup method that would take an int code and should return me the String message pertaining to that code that is stored in the Enum.Passing a "1" should return me the String "Some long String here". What is the best way to implement this functionality?
public static String lookUpMessageFromCode(int code){
}
P.S: Is the class EnumMap useful for this kind of use case? If yes,please let me know why?
Depending on the int values that you associated with your enum, I would add a static array of ErrorCodes, or a static Map<Integer,ErrorCode> to your enum class, and use it to do a lookup in the message from code method. In your case, an array is more appropriate, because you have values 1 and 2 which are small. I would also change the signature to return ErrorCode.
private static final ErrorCode[] allErrorCodes = new ErrorCode[] {
null, MissingReturn, InvalidArgument
};
public static ErrorCode lookUpByCode(int code) {
// Add range checking to see if the code is valid
return allErrorCodes[code];
}
The callers who need the message would obtain it like this:
String message = ErrorCode.lookUpByCode(myErrorCode).getDetailedMessage();
I would simply iterate through your Enum values and check the code. This solution lets you utilize the existing Enum with out creating another object to manage.
public enum ErrorCode {
MissingReturn(1, "Some long String here"),
InvalidArgument(2, "Another long String here");
private final int shortCode;
private final String detailMessage;
ErrorCode(int shortCode, String detailMessage) {
this.shortCode = shortCode;
this.detailMessage = detailMessage;
}
public String getDetailedMessage() {
return this.detailMessage;
}
public int getShortCode() {
return this.shortCode;
}
public static String lookUpMessageFromCode(int code) {
String message = null;
for (ErrorCode errorCode : ErrorCode.values()) {
if (errorCode.getShortCode() == code) {
message = errorCode.getDetailedMessage();
break;
}
}
return message;
}
public static void main(String[] args) {
System.out.println(ErrorCode.lookUpMessageFromCode(1));
System.out.println(ErrorCode.lookUpMessageFromCode(2));
}
}
One thing to note
The Enum constructor is missing the type information regarding its parameters.
ErrorCode(int shortCode, String detailMessage) {
this.shortCode = shortCode;
this.detailMessage = detailMessage;
}
Here is another option:
public static String lookUpMessageFromCode(int code){
for(ErrorCode ec:ErrorCode.values()){
if(ec.shortCode==code)
return ec.detailMessage;
}
return null;
}

Categories

Resources