I am trying to reference a string stored in a .xml file, and every time i reference it I just get a string of numbers.
if (Medals.medal_counter1 == 0) {
Medals.medal_counter1++;
victory.setMessage("you won " + R.string.medal01);
}
victory.show();
Here is the stored string.
<string name="medal01">"A medal"</string>
The dialog I actually get is something more like this,
"you won 21310334567"
Any solutions?
That's because you are getting the string resource's ID. If you want to retrieve the actual string content you need to use Context.getString(int resourceId) method.
For instance, from inside an Activity:
victory.setMessage("you won " + getString(R.string.medal01));
Otherwise:
victory.setMessage("you won " + victory.getContext().getString(R.string.medal01));
Try this
getResources().getString(R.string.medal01);
- What you are referring to using R.string.medal01 is an public static final integer value in R.java file.
- Use below instead:
victory.setMessage("you won " + getString(R.string.medal01));
Related
This question already has answers here:
How can I print this 2 Variables in the same println "System.out.println"
(7 answers)
Closed 3 years ago.
So basically I'm trying to complete a school problem in which I have to declare two variables:
I want to print them in a single statement, but I don't know how.
I have tried using commas, and even a plus sign to separate the different variables but I'm always getting an error.
I did look online, but I guess you can only combine strings and ints?
Boolean isTrue = false;
Double money = 99999.99;
System.out.println(money + isTrue);
I expected it to print:
99999.99 false
Try this.
Inside of a System.out.println() method each variable calls its string representation to print. But if its a primitive datatype--> then we need to call its to string method to print its exact value.
You can concatenate with .toString() method
public static void main(String[] args) {
Boolean isTrue = false;
Double money = 99999.99;
System.out.println(money + isTrue.toString());
}
This is because println will automatically convert its input to a string for printing. Any logic inside of the "()" will be performed first, before this type conversion. Since you have 2 different value types that can't normally be added together, this logic fails. You will need to convert all of your values to a string to be able to use the "+" as a concatenation.
Alternatively, consider looking at using StringBuilder or StringFormat
Try this way:
System.out.println(money + " " + (isTrue ? "True" : "False"));
or simply:
System.out.println(money + " " + isTrue);
Concatenate them with string:
Boolean isTrue = false;
Double money = 99999.99;
System.out.println(money + " " + isTrue);
I've been asked to create a program that stores series of suitable nouns, adjectives and verbs in arrays. These must be set up at the start of program run. Rather than ask the user, each time it generates letter it just chooses words at random from the appropriate array. The arrays are passed to methods that represent the templates.
I'm new to java, and this is what I have managed to get done below, however shows errors saying void cannot be converted to string for each print message part. I would be glad if someone can help me approach this simple question which i'm struggling on, I don't know if I am doing it correctly.
Any help would be much appreciated.
public static void arrays()
{
String []noun = {"face", "eyes", "tender", "lips", "ears", "roses"};
Random random = new Random();
int rand1 = random.nextInt(noun.length);
String []verb = {"enchant", "dazzle", "cuddle" , "lure", "desire", "dream" };
Random random2 = new Random();
int rand2 = random2.nextInt(verb.length);
String []adjective = { "Alluring", "Angelic", "Adoring", "Appealing", "Attractive", "beautiful"};
Random random3 = new Random();
int rand3 = random3.nextInt(adjective.length);
printmessage (noun[rand1], verb[rand2], adjective[rand3]);
}
// END arrays
public static void printmessage(String noun, String verb, String adjective)
{
System.out.println("I would love to " + verb + " " + adjective + " " + noun + "\n");
System.out.println("Your are my " + noun + " " + adjective + " " + verb + "\n");
System.out.println("you always look great in that " + noun + " ,as you always do, since your so " + adjective + "\n");
System.out.println("I get butterflies when I see you in" + noun + " , you make me " + verb + " , in your " + adjective + " world" + "\n");
}
} // END class loveletter
You've got some issues here, so let's walk through them.
First, the conceptual issue. You shouldn't need to return anything from your printmessage method, as all you're doing is showing a message dialog.
Next, you don't do anything with those four result variables, and they would only last within the scope of that method. That's to say, not very long. I don't think you need them.
Next, the technical issues:
One return is all it takes for the code execution to halt. If it were valid code, you would only get back result1. Since we discussed earlier that you don't need to return anything from this method, remove the superfluous returns.
JOptionPane#showMessageDialog returns void; that is to say, it returns nothing. You can't assign a value of its return type to a variable, so the variables do you absolutely no good. Remove the assignment and declarations.
Don't forget to change the return type of your method to void instead of String.
Clean up the call in arrays() so that it only calls printmessage at the end, and doesn't do anything else after that.
I leave the logical errors (I did notice some funky string concatenation and grammatical errors in there) as an exercise to the reader.
I have a blank text field which I'm trying to use settext on after a button click, so I can change the blank text field to the text in the stored variables.
The variables are two ints which I've converted to string and I'm trying to do the following:
blankText.setText("" + var1);
currently works but when I try to add the other variable in the same field I'm not sure how to go about it?
For example I tried to do: blankText.setText("" + var1, var2) which throws an error. I want them listed side by side in the same text field. is this possible?
To combine Strings, use +:
blankText.setText(var1 + var2);
blankText.setText(var1 + " " + var2);
blankText.setText("" + var1 + " " + var2);
if you want to space your variables
If you are trying to add or append the text in already written textview then use
blankText.append(""+var2);
if you want to write two variables in textview at the same time then use the concatination symbol
blankText.setText(" " + var1 + " " + var2); // also will remove the previous written text
Hi so I'm relatively new at Java, I have about 2 months of experience, so please try to answer my question using terms and code relevant to my learning level.
So, I have to make a program for school that makes a letter, fitting the following format:
Dear recipient name:
blank line
first line of the body
second line of the body
. . .
last line of the body
blank line
Sincerely,
blank line
sender name
my code looks like this:
private String body;
private String letter;
public Letter(String from, String to)
{
letter = ("Dear " + to + ":" + "\n" + "\n" + body + "\n" + "Sincerely," + "\n" + "\n" + from);
body = "";
}
public void addLine(String line)
{
body = body + line + "\n";
}
public String getText()
{
return letter;
}
Ive tried several different ways to get this program done, and the one that yields the best results is this one.. The thing is, we're only supposed to use two instance fields max. It seems that it's null because body isn't given a value in my constructor. There's also a program tester class that looks like this:
public class LetterTester
{
public static void main(String [] args)
{
Letter tyler = new Letter("Mary", "John");
tyler.addLine("I am sorry we must part.");
tyler.addLine("I wish you all the best.");
System.out.println(tyler.getText());
}
}
i skipped all the default stuff and some braces and theres no syntax errors, but when i run the tester class, I get:
Dear John:
null
Sincerely,
Mary
What am I doing wrong, and can someone please give a solution as to how to get rid of null? Keep in mind I can only use two instance fields, thanks.
body is null because that is the default value for reference fields. You could initialize it to empty string body = "" instead. That would work with your addLine() code. You should also move constructing the content from the constructor to getText(). In the constructor the required data is not yet available.
Also consider using a StringBuilder. That's usually better choise than + when you need to make several concatenations.
Edit: (after a clarifying comment by the OP, and myself reading the question better)
In the constructor you can start the letter like:
body = "Dear " + to + ":" + "\n\n";
sender = from;
Here I made sender a field. You don't need the letter field, so you can still stay at the max 2 fields limit.
You will have to initialize the body variable with an empty string. Otherwise its initialized as null, and thereby you cannot append anything to the string as you are doing in function addLine()
This question is rather difficult to confer, for simplistic sake:
I am loading some Strings via XML (XStream).
for example, Your total count is +variable+ .
The outcome would be
"Your total count is +variable+ ."
when it ideally should be
"Your total count is" + variable + "." aka "Your total count is 1."
The issue: (if you can't see it) it reads the variable as if it were a String.
I know I would need to split that String from where the plus sign starts and ends and then connect it to the String, for it to read as a variable, like the above. But how? I need this to be done so that the String before the variable and after it is split.
so:
"Your total count is 50, would you like a cookie?"
aka
"Your total count is " + variable + " , would you like a cookie?"
Thank you alot!
Okay, I agree it's very confusing. I've edited this post (read below).
Well I am loading some Strings via XML this could be the same case if I were loading them via a .txt or a config file.
On the XML file, I lay it out like so:
<list>
<dialogue>
<line>
<string> Your total count is + Somewhere.totalCount +, Would you like a cookie?</string>
</line>
</dialogue>
</list>
As you can see, the XML file can't locate where the variable (in a class is), nor can it recognise if it is a variable or a string.
I know that I would need to alter the way it reads it, so if there is a plus sign (+) anywhere on the String, it would simply "split" it away from the original String so I can reconnect it.
E.g. Your phone number is + PhoneBook.phoneNumber + should I call you? as it would be read from a XML file.
I want to "split" the String from front to back like so:
"Your phone number is " + PhoneBook.phoneNumber + " should I call you?"
At the same time, I'm not assigning a variable because It's already declared in the XML file, I want it to recognise it as a int.
First, Java can not know that the +variable+ part of your string should be replaced with the value of the corresponding variable and also does not provide some "eval" like functionality like PHP or other scripting languages do, which might help you with that.
If you want to exactly replace this specific '+variable+' part of the string, it can be done like this:
int variable = 1;
String text = "Your total count is +variable+.";
String textWithVariableValue = text.replaceAll("\\+variable\\+", Integer.toString(variable));
But if you want to replace variables with arbitrary names, you will have to put them into a Map first, and then find all occurences of +somename+ in the string and replace it with the corresponding value stored in the map. Something like this:
Map<String, Object> variables = new HashMap<String, Object>();
variables.put("var1", 1);
variables.put("foo", 5);
String text = "var1 = +var1+, foo = +foo+";
String textWithVariableValues = text;
for (String variableName : variables.keySet()) {
Object variableValue = variables.get(variableName);
textWithVariableValues = textWithVariableValues.replaceAll("\\+" + variableName + "\\+", variableValue.toString());
}
Sounds like what you need is the
String.format() method:
int total = calculateTotal();
String s = String.format("Your total is %1d.", total);
Not split, but find and replace.
Simplistically,
int variable = 1;
String src = "Your total count is +variable+.";
String result = src.replaceAll("\\+variable\\+.", Integer.toString(variable));
System.out.println(result);
Should print "Your total count is 1."
EDIT: (after your comment) If you need to replace a multiple variables in one go then the following works for me:
// Replace the ff. with the actual map of variables & values
Map<String, String> vars = Collections.singletonMap(
"variable", Integer.toString(123));
String src = "Your total count is +variable+.";
Pattern p = Pattern.compile("\\+(\\w+)\\+");
StringBuffer sb = new StringBuffer();
Matcher m = p.matcher(src);
while (m.find()) {
String varName = m.group(1);
if (vars.containsKey(varName)) {
m.appendReplacement(sb, vars.get(varName));
}
}
m.appendTail(sb);
System.out.println(sb.toString());
Prints "Your total count is 123."