Java use String value as Variable - java

I have a method with a Parameter Country. This Parameter only Contains an abbreviation of the Country. In the method i want to print the full name of the Country without switch case or something, but with predefined Strings
final String VA="Vatikan";
String country="VA";
system.out.println(country);
//Is it possible that it Prints Vatikan now?
//I know not with that code but is there a possibillity to do that.

No, but you could use a map to acheve the result you want. Specifically, to return the full name of the abbreviated country name:
String va="Vatikan";
String country="VA";
Map<String, String> abbreviationMap = new HashMap<String, String>();
abbreviationMap.put(country, va);
System.out.println(abbreviationMap.get(country)); //prints "Vatikan"

This will assign it properly:
final String VA="Vatikan";
String country=VA;
System.out.println(country);
The String variable country will be pointed to whatever the variable VA is pointed to; because VA cannot change (it's final), country will point to "Vatikan".

What you are doing is that assigning a string "VA" to country, but you want to treat it as a variable, so remove the quotes("").
final String VA="Vatikan";
String country=VA;
System.out.println(country);

Related

Using an array to store multiple variables from user input

I am relatively new to Java and would like to know how to store variables separately from a single line of user input.
At the minute the user is prompted to enter football results in the following format
home_name : away_name : home_score : away_score
and I am using a while loop to continue to ask user for input until they enter "stop"
(while (input != "stop))
Once the loop is broken I would like my program to output a variety of data such as total games played, but I'm struggling to store the home_name, away_name etc.. especially if the user wishes to enter multiple lines of results.
Two mainstream ways to store a "record" are:
Maps
Data objects
A map is more generic:
Map<String,String> match = new HashMap<>();
match.put("home_name", "Alvechurch Villa");
match.put("away_name", "Leamington");
match.put("home_score", "0");
match.put("away_score", "6");
You can add a map to a list:
List<Map<String,String>> matches = new ArrayList<>();
matches.add(list);
... and retrieve them:
Map<String,String> match = matches.get(0);
System.out.println(match.get("away_score"));
A data object is more tuned to your data format, but you have to write the class yourself.
public class Match {
public String homeName;
public String awayName;
public int homeScore;
public int awayScore;
}
Now you can use this class:
Match match = new Match();
match.homeName = "Studley";
// etc.
You can add and retrieve these from lists too:
List<Match> matches = new ArrayList<>();
matches.add(match);
Match aMatch = matches.get(0);
This is simple, but it's considered bad practice to have public fields like this - it's better to get at them via methods. For brevity, here's a data class with only one field:
public class Player {
private String name;
public Player(String name) {
this.name = name;
}
public String name() {
return name;
}
}
Player neilStacey = new Player("Neil Stacey");
You can use the same technique with all the fields in Match.
(A common style is to name a method like this getName(), and also to have a setName(). I have used a different style and made the object immutable, in an effort to set a good example!)
One advantage of the data object is that it has different types for different fields: homeName is a String, homeScore is an integer. All the fields in the Map are Strings. You can get around this by using Map<String,Object> but then as a consumer you have to cast to the right type when you read.
String homeName = (String) match.get("home_name");
Data objects allow the compiler to do a lot of compile-time checking that helps you know your code is correct. If you use a map, you won't find out until runtime.
Prompt the user separately for each input.
System.out.println("home_name: ");
String hN = scan.next();
System.out.println("away_name: ");
String aN = scan.next();
System.out.println("home_score: ");
String hS = scan.next();
System.out.println("away_score: ");
String aS = scan.next();

replace String with value of properties file in java

I have a code to replace stream of string. I need to search a specific string that is defined in the key of properties file
String result="";
int i=0;
while (i<listToken.size()){
result = listToken.get(i);
while (enuKey.hasMoreElements()) {
String key = (String)enuKey.nextElement();
// String value = propertiesSlang.getProperty(key);
if (listToken.get(i).equals(key)){
String value = propertiesSlang.getProperty(key);
listToken.get(i).replace(listToken.get(i), value);
System.out.print("detected");
}
}
i++;
}
But it doesn't replace word. How I can replace words using properties.
It's because you forgot to assign the result, using the method set():
listToken.set(i, propertiesSlang.getProperty(key)));
assuming listToken implements AbstractList
Why complicate things with replace(). As far as I understand your code you can simply do -
String value = propertiesSlang.getProperty(key);
listToken.set(i, value);
I see you have modified your code again to
listToken.get(i).replace(listToken.get(i), value);
Just so that you know String class is immutable. So operations like replace() or substring() will give you a new String and not modify the original one. Get the new String and set it in your list listToken.

variable is not being intitialised

String firstname , middlename , lastname ;
firstname = fn.getText().substring(0,1);
middlename = mn.getText().substring(0,1);
lastname = ln.getText();
String shortname = shortname.concat(lastname); // error is in this line, shortname.concat
shortname = shortname.concat(" ");
shortname = shortname.concat(firstname);
shortname = shortname.concat(".");
shortname = shortname.concat("middlename");
shortname = shortname.concat(".");
shrt.setText(shortname);
No other lines have any error. just shortname variable not initialised.
Note: EASY SOLUTIONS PLEASE. I AM IN CLASS 11. DOING THIS JAVA OUT OF TEXT BOOK.
The right-hand expression in
String shortname = shortname.concat(lastname);
will be evaluated before the assignment, so when you try to do
shortname.concat(lastname)
shortname at that moment is not initialized. To fix this you must initialize it with an empty string ("") before you use it:
String shortname = "";
shortname = shortname.concat(...);
Edit:
As #BrianRoach commented, is not necessary to concatenate it, since you are just concatenating a empty string ("") with another String. Just do:
String shortname = lastname;
You are trying to use shortname even before declaring it. You need to declare it and initialize a variable before using it. The use of shortname on the RHS means that you're trying to use it even before it has been declared on the LHS. Declare and initialize it first, and then use it.
String shortname = ""; // blank string, for initializing it
shortname = shortname.concat(lastname);
As #Brian has commented, if its going to be a concat with a blank string, you might as well just directly assign the value to it. And that way you need not have 2 statements.
String shortname = lastname; // Declaration and initialization, done!
Use:
String shortname = "";
shortname = shortname.concat(lastname);
Initilize shortname first
Actulally shortname doesnt contain anything to concat with.
So provide some value for it,
String shortname="";
shortname = shortname.concat(lastname);
Edit:
as #BrianRoach commented in #Christians answer,we should initilize shortname as
String shortname=lastname;
to value the purpose of concatenation.

Howto convert the value of a hashmap to String i Java

I have a HashMap. I am trying to retrieve the value and print it using the key from the user-code.
The code is:
lib.addbook(book2.getISBN(), book2);
Book ret = lib.getbook("978-81-291-1979-7");
System.out.println(ret);
Current Output:
O/P: LibraryPackage.Book#527c6768
I want the output to be a string and to display the actual value not the address of the book.
You have to implement (and override) the toString() method in your Book class, and specify what you want the output to be. E.g.:
#Override
String toString()
{
return this.author+": " + this.title;
}
commons-lang has a great utility for this if you don't want to override the .toString() method, or need to represent it differently in different situations:
Here's a call to build a string based on reflection:
String str = ToStringBuilder.reflectionToString(object);
In fact, this is a great way to implement the .toString() method itself. Another alternative use of this class would be a field by field creation of the string:
String str = new ToStringBuilder(object)
.append("field1", field1)
.append("field2", field2)
.toString();

Dynamic variable names Java

How will I be able to retrieve the value of a variable which has a dynamic name
For Example I have list of constants
public class Constant{
public static final String S_R = "Standard(240)";
public static final String S_W = "Standard(180)";
public static final String L_R = "Large(360)";
public static final String L_W = "Large(280)";
}
Based on database I build a variable name
String varName = "S" + "_" +"R"; // This can be S_R , S_W , L_R or L_W
String varVal = // How do i get value of S_R
Use a normal HashMap with variable names as strings against their values. Or use a EnumMap with enums as key and your value as values. AFAIK, that's the closest you can get when using Java. Sure, you can mess around with reflection but IMO the map approach is much more logical.
You can use a Map<String, String> and locate the value by its key.
Even better, you can have an enum:
public enum Foo {
S_R("Standard", 240),
S_W("Standard", 180),...;
private String type;
private String duration;
// constructor and getters
}
And then call Foo.valueOf(name)
(You can also do this via reflection - Constants.class.getField(fieldName) and then call field.get(null) (null for static). But that's not really a good approach.)
If you really must do this (and it's unlikely), you would have to use the Java "reflection" APIs.

Categories

Resources