Change an array to a string without creating a string - java

I wish to accomplish:
String []beef = new String[3];
beef[0] = "Water";
beef[1] = "Chicken";
beef[2] = "Paper";
String empo = Arrays.toString(beef);
if (empo.isEmpty()){
empo = "Nothing";
System.out.println(empo);
}else{
System.out.println(empo);
}
without having to create the string.
Something like:
String []beef = new String[3];
beef[0] = "Water";
beef[1] = "Chicken";
beef[2] = "Paper";
Arrays.toString(beef); //change beef to just a plain string
if(beef.isEmpty()||beef==""){
no = "Nothing";
System.out.println(beef);
How would one go about doing this?

You can't.
Java is a strongly and statically typed language. That means you have to tell it what type a thing will be when you declare it (strong typing), and you can't ever change it's type after that (static typing).
You will just have to create a new String.

You can create substrings with the same backing memory as the original string, but you can't create a string with the same backing memory as an array of strings. They're not stored in the same order so it's impossible to view the same memory both ways.

Related

How can I use name of string instead of content of string?

Normally, I use
String[] arrayName = getResources().getStringArray(R.array.name_array);
So are there any ways to use
String[] arrayName = getResources().getStringArray(R.array.NAME);
with NAME is string (String NAME = "name_array";)?
Android replace string name to integer id after compile, but you place id to varialbe
int NAME = R.array.name_array;
String[] arrayName = getResources().getStringArray(NAME);
Going by what is in the official documentation, this is an acceptable way of referencing your array. However, I need to point out an error in your flow:
NAME must be an int. Therefore, the value should be R.id.name_array (this would return an int). Also, remove the double quotes around name_array.
You can do the referencing this way:
int NAME = R.array.name_array; // use a variable to store the int reference
String[] arrayName = getResources().getStringArray(NAME); //fetch

Huge constructor for messages/names definition

I want to allow name and message customisation in both my lexer and parsers. The parser/lexer must be able to select a specific message or name, e.g.:
messageManager.tokenName.eofToken
Here, eofToken would be a String. tokenName would be a set of names for lexer tokens and messageManager would be a structure like { parserMessage, lexerMessage, contextName, tokenName }
However, I want the message customisation very directly constructed. I don't want something like:
TokenName tokenName = new TokenName();
tokenName.eofToken = "end of file";
tokenName.identifier = "identifier";
tokenName.keyword = "keyword";
tokenName.regExpLiteral = "regexp' literal";
// much more...
I want something like:
new TokenName(
"end of file",
"identifier",
"keyword",
...
)
I know we just need to define parameters and assign them to the corresponding variables, but I don't want a huge constructor like the one I had in my previous parser:
public TokenNames(
String booleanLiteral,
String eofToken,
String identifier,
String punctuator,
String keyword,
String numericLiteral,
String nullLiteral,
String regExpLiteral,
String stringLiteral,
String xmlName,
String xmlMarkup,
String xmlPunctuator,
String xmlTagCharacters,
String xmlText
)
{
this.booleanLiteral = booleanLiteral;
this.eofToken = eofToken;
this.identifier = identifier;
this.punctuator = punctuator;
this.keyword = keyword;
this.numericLiteral = numericLiteral;
this.nullLiteral = nullLiteral;
this.regExpLiteral = regExpLiteral;
this.stringLiteral = stringLiteral;
this.xmlName = xmlName;
this.xmlMarkup = xmlMarkup;
this.xmlPunctuator = xmlPunctuator;
this.xmlTagCharacters = xmlTagCharacters;
this.xmlText = xmlText;
}
I believe it's possible with arrays or varargs (more readable). How to?
Define class like this:
public class Token {
private String booleanLiteral;
private String eofToken;
...
public Token withBooleanLiteral(String booleanLiteral) {
this.booleanLiteral = booleanLiteral;
return this;
}
public Token withEofToken(String eofToken) {
this.eofToken = eofToken;
return this;
}
...
}
You'll get
Token token = new Token()
.withBooleanLiteral("something");
Check out Lombok library and #Wither annotation. It does everything for you.
Of course, the builder pattern is the most obvious solution in here (and the correct one).
But I would like to draw your attention to the fact there is a lot of fields that can be encapsulated by their own classes.
The following fields can be collected into an XMLDescription class:
String xmlName;
String xmlMarkup;
String xmlPunctuator;
String xmlTagCharacters;
String xmlText;
The next ones can be grouped by a LiteralDescription class:
String numericLiteral;
String nullLiteral;
String regExpLiteral;
String stringLiteral;
Think the problem over once more: if there is a chance to shorten a number of the fields to 3 (an extreme bound according to good practices), the constructor can be used instead of the builder.
I believe it's possible with arrays or varargs (more readable).
Please, don't do that - it's an error-prone approach. You are coupling an index of the array with a corresponding field. Such code, hard to maintain and document, causes an API user
to read a documentation if any provided,
to poke around in the sources if no provided,
to follow to any API change believing that nothing is changed.

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();

String.replace() isn't working like I expect

I am not understanding how to use the String.replace() method. Here is the code:
CharSequence oldNumber = "0";
CharSequence newNumber = "1";
String example = "folderName_0";
System.out.println("example = " + example);
example.replace(oldNumber, newNumber);
System.out.println("example.replace(oldNumber, newNumber);");
System.out.println("example = " + example);
And it's outputting:
example = folderName_0
example.replace(oldNumber, newNumber);
example = folderName_0 // <=== How do I make this folderName_1???
The replace method isn't changing the contents of your string; Strings are immutable. It's returning a new string that contains the changed contents, but you've ignored the returned value. Change
example.replace(oldNumber, newNumber);
with
example = example.replace(oldNumber, newNumber);
Strings are immutable. You need to re-assign the returned value of replace to the variable:
example = example.replace(oldNumber, newNumber);
String is a immutable object, when you are trying to change your string with the help of this code - example.replace(oldNumber,newNumber); it changed your string but it will be a new string and you are not holding that new string into any variable. Either you can hold this new string into a new variable, if you want to use your old string value later in your code like -
String changedValue = example.replace(oldNumber,newNumber);
or you can store in the existing string if you are not going to use your old string value later like -
example = example.replace(oldNumber,newNumber);

How do I convert a string to an new object's name?

I'd like to write a program which creates a set of objects in a loop....
(i.e.)
String newFirm = "empty";
for(int i=0; i<30; i++)
{
newFirm = "firm" + i;
firm newFirm = new firm();
}
and then of course I would need something like
stringToObject = "firm" + x;
stringToObject.type = "service";
stringToObject.size = 10000;
Obviously this code is fictional, but It expresses how I'd ideally create and call for objects. The nature of this program is such that the final number of firms (or other objects) are not known at the time of compiling.
Is there a method by which I can convert a given string into the name of an object (either to call or to create) as well as creating objects "on the fly"?
Sounds like a job for an ArrayList.
ArrayList<Firm> myList = new ArrayList<Firm>();
And in your loop,
Firm firm = new Firm();
firm.type = "service";
myList.add(firm);
And to get it,
Firm f = myList.get(index);
convert a given string into the name of an object
Your need is to refer an object with the string in your hand. I'll suggest Hashmap<String,Object>
Eg:- you have a String,
String name="object_name";
And your class is Firm. Now,
Hashmap<String,Firm> objs=new Hashmap<String,Firm>();// note:your for loop comes after this line
Firm new_firm=new Firm();
new_firm.type = "service";
new_firm.size = 10000;
objs.put(name,new_firm);
Now you can refer your object with the string in your hand as
objs.get("object_name");

Categories

Resources