Generate by use of the operator + a string, that the values in the variable in the given ones on top
Order includes, in each case apart by ",". give the string with System out println (...).
Remove the quotes " and call toString()
str = hexValue.toString() + ", " + octValue.toString() + ", " + l.toString() + ", " + var1.toString() + ", " + var2.toString() + ", " + var3.toString() + ", " + var4.toString() + ", " + c.toString();
now notice that this will give you the decimal values.. if you want the hex, octal, etc, that's a different question.
Suppose we have the following variables:
int age = 5;
String name = "Mohammad";
double weight = 68.4;
If we want to print them out joined in a string with one statement we can say:
System.out.println("My name is " + name + ", I am " + age + " years old, " + " I once caught a fish that weighs " + weight +"kg");
In Java, using the + operator you can concatenate strings.
Note: age, name, and weight are all of different types, but when you put the + operator with a String, java automatically convert that variable to a string and then concatenates it with the rest of the string. Hence, if you wish to perform some kind of operation then concatenate, then you should make use of parentheses ():
System.out.println("Two Plus Five is = " + (2 + 5));
Related
I am trying to have a string that when i print it, has multiple lines and different left indents.
String test = "Zone 0:" +
"Gear{" + "gearType=" + gearType + ", weight=" + weight}" +
"Zone 1:" +
"Gear{" + "gearType=" + gearType + ", weight=" +weight}";
System.out.println(test);
Expected Output: (without the dashes but with a left indent)
Zone 0:
------Gear{gearType=RAIN_JACKET, weight=HIGH}
Zone 1:
------Gear{gearType=SHELTER, weight=HIGH}
You can make use of "\n" new line character and "\t" for tab. Like:
final String test = "Zone 0:\n" + "\tGear{" + "gearType=" + gearType + ", weight=" + weight +"}\n" + "Zone 1:\n"
+ "\tGear{" + "gearType=" + gearType + ", weight=" + weight + "}\n";
As well as after weight there should be + sign and a double quote ". (as in above String)
you can use the "\n" for new line and "\t" for tabulation space :
String test = "Zone 0:\n" + "\tGear{" + "gearType=" +
gearType + ", weight=" + "weight}\n" +
"Zone 1:\n" + "\tGear{" + "gearType=" +
gearType + ", weight=" + "weight}";
output :
Zone 0:
Gear{gearType=test, weight=weight}
Zone 1:
Gear{gearType=test, weight=weight}
You may also refer to the official Formatter documentation. There you'll get all the other options and details for formatting a String in Java.
Presumably you'd want the lines to use the appropriate line terminator for your platform, i.e. \r\n for Windows and \n for Linux.
There are two ways to do that:
Use System.lineSeparator():
String test = "Zone 0:" + System.lineSeparator() +
" Gear{gearType=" + gearType + ", weight=" + weight + "}" + System.lineSeparator() +
"Zone 1:" + System.lineSeparator() +
" Gear{gearType=" + gearType + ", weight=" + weight + "}" + System.lineSeparator();
Use String.format(String format, Object... args) and the %n format specifier:
String test = String.format("Zone 0:%n" +
" Gear{gearType=%s, weight=%s}%n" +
"Zone 1:%n" +
" Gear{gearType=%s, weight=%s}%n",
gearType, weight, gearType, weight);
I'd recommend the second approach, since it's more readable.
May be an idea to rather use a StringBuilder (though from what I understand the Java compiler uses StringBuilder under the hood for String concatenation), so it really becomes more of a readability issue.
StringBuilder output = new StringBuilder()
.append(System.lineSeparator()).append("Zone 0:")
.append(System.lineSeparator()).append("\tGear{gearType=").append(gearType).append(", weight=").append(weight).append("}")
.append(System.lineSeparator()).append("Zone 1:")
.append(System.lineSeparator()).append("\tGear{gearType=").append(gearType).append(", weight=").append(weight).append("}");
System.out.print(output.toString());
For newlines it's good practice to use System.lineSeparator()
in addition to returning the db2.get (i) .getEnumDesc () strings which are normal strings.
there are some strings like: 1 - Selected house in db2.get (i) .getEnumDesc ()
I have to cut -> 1 -
I have translated the selected part of the house and then reassembled it.
1 - select house
in practice, in output, not only normal strings have to be returned, but also strings with numbers, ie 1 - select house
in printed output:
es.
house
hello
1 - select
2 - bye
etc...
public void getTraduttoreIt_ENUM_NLS() throws Exception {
List<EnumNls> db2 = getListEnumNls();
List<DizioPt> sqlServer = getListDizioPt();
BufferedWriter scrivi = new BufferedWriter(
new FileWriter("C:/Users/francesco/Desktop/Table_THERA.ENUM_NLS_Sez4.txt"));
System.out.println("-------------------WRITE FILE N°4--------TRANSLATION------------------------");
for (int i = 0; i < db2.size(); i++) {
for (int j = 0; j < sqlServer.size(); j++) {
if (db2.get(i).getEnumDesc().equals(sqlServer.get(j).getKeyword())) {
System.out.println(
"INSERT INTO THERA.ENUM_NLS VALUES" + "(" + "'" + db2.get(i).getAttributeRef().trim() + "'"
+ "," + "'" + db2.get(i).getEnumValue().trim() + "'" + "," + "'" + "en" + "'" + ","
+ "'" + sqlServer.get(j).getTraduzione().trim() + "'" + ")" + ";");
scrivi.write("INSERT INTO THERA.ENUM_NLS VALUES" + "(" + "'" + db2.get(i).getAttributeRef().trim()
+ "'" + "," + "'" + db2.get(i).getEnumValue().trim() + "'" + "," + "'" + "en" + "'" + ","
+ "'" + sqlServer.get(j).getTraduzione().trim() + "'" + ")" + ";");
scrivi.newLine();
scrivi.flush();
}
}
}
scrivi.close();
}
}
in practice, in output, not only normal strings have to be returned, but also strings with numbers, ie 1 - select house
in printed output:
es.
house
hello
1 - select
2 - bye
etc...
What error(s) are you getting?
Could the string returned from db2.get(i).getEnumValue().trim() or sqlServer.get(j).getTraduzione().trim() have a single quote (') in it? In which case your SQL statement has a syntax error. If this is the case, after trim() you could insert a .replaceAll("'", "''") which should solve your the problem.
So db2.get(i).getEnumValue().trim().replaceAll("'", "''") - This is ("\u0027", "\u0027\u0027")
If you are getting a number back, what you have should work, even if the number is part of the string.
Unless your data has to do with "house", I think you are using the wrong English word in describing your situation.
In any case, explain the errors you are seeing and that might help people understand your problem.
I'm trying to get each variable to print out with two decimal places but I do not know what I'm doing wrong. Any help?
System.out.printf("%.2",custNum + "\t" + beginBal + " \t " + financeCharge + "\t\t" +
purchases + " \t " + payments + "\t\t" + endBal);
Your format String should be %.2f and one for each term. Something like,
System.out.printf("%.2f\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f%n", custNum, beginBal,
financeCharge, purchases, payments, endBal);
this is probably a very basic problem but as I am only a beginner, this is confusing me. I am trying to make capitalise the first letter of a string, which I have done with the following code:
public String capitalizeFirstLetter(String product){
String productCap = product.substring(0, 1).toUpperCase() + product.substring(1);
return productCap; }
And then this capitalised version of the product just be placed in a letter writer method:
public void writeALetterChallenge(String nameFirst, String nameLast, String city, String product, String company, double retail, int numItem){
UI.println("Dear " + nameFirst);
UI.println(" You have been especially selected from the people of " + city);
UI.println("to receive a special offer for "+ product);
UI.println(productCap + " from " + company + " is a premium brand prodcut and"); UI.printf("retails for $%1.2f" + ". But, " + nameFirst + ",if you order your " + product + "\n", (retail));
UI.println("today, you can purchase it for just $" + (retail - (retail * 0.60)) + ", a saving of 60%!");
UI.println("As a special bonus, just for the " + nameLast + "family, if you order"); UI.println(numItem + " " + product + " today, you will get an additional 10% off - "); UI.println("an amazing price for " + product + " of just $" + (retail - (retail * 0.70)) + "!");
UI.println(" ");
UI.println("Hurry today and send in your order for " + product + " from " + company); UI.println("and make these fantastic savings.");
UI.println(" "); }
However my problem is that when I compile, I get the error that productCap cannot be found. So I've obviously missed something. How do I go about getting the productCap variable from the first method to be included in the second?
Any explanation on this would be great, thanks!
You should call your method:
UI.println(capitalizeFirstLetter(product) + " from " + compan ...
I think instead of this
UI.println(productCap + " from " + company + " is a premium brand prodcut and");
you want to have this
UI.println(capitalizeFirstLetter(product) + " from " + company + " is a premium brand prodcut and");
YOu can call your method as follows
UI.println(capitalizeFirstLetter(product) + " from " + company + " is a premium brand prodcut and");
Your variable productCap is local to method CapitalizaFirstLetter() and hence not accessible in another method.
To access the value of productCap, simply call CapitalizeFirstLetter() method so that it returns the value of productCap.
Just starting learning java today and can't seem to figure this out. I am following the tutorial on learnjavaonline.org which teaches you a few things and then asks you to write a code to do a specific thing, it then checks the output to see if its correct. The thing is, if its not correct, it doesn't say why, or give you an example of the correct code.
It wants me to output a string saying "H3110 w0r1d 2.0 true" using all of the primitives
i came up with this
public class Main {
public static void main(String[] args) {
char h = 'H';
byte three = 3;
short one = 1;
boolean t = true;
double ten = 10;
float two = (float) 2.0;
long won = 1;
int zero = 0;
String output = h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
System.out.println(output);
}
}
but it outputs 86.0 w0r1d 2.0 true
how can i make it so it doesn't add all the integers, but displays them consecutively?
The problem with this line:
String output = h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
is that operations are performed left to right, so it first sums h + three (which evaluates to an int) and then one and then ten. Up to that point you have a numerical value (an int) that then will be "summed" to a String. Try something like this:
String output = "" + h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
In this second case your expression will start with a String object, evaluating the rest of the operations as Strings.
You of course could use "" at the beginning or any other value that evaluates to String, like String.valueOf(h). In this last case you wouldn't need to use String.valueOf() for the other operands, as the first one is already a String.
You can either convert your numbers into a string using the toString or valueOf methods of the wrapper classes (guess you are not there yet), or just stuff all your primitives into the printline without the String output.
system.out.println(h + three + one + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t);
All you need to look for is that there is a String in the printline statement. Meaning if you only want to print our number based datatype you can use system.out.println("" + youNumberVariable).
There would also be the option to add an empty string at the beginning of your declaration of output output = "" + theRest; to force all following values into the string like it does in the printline statement.
Most of it is not very pretty coding but will completly suffice for the learning process.
An easy and ugly way to do this would be to use String.valueOf for each numerical value.
As in:
String output = h + String.valueOf(three); // + etc...
Edit
morgano's approach is perfectly valid as well - +1 for that.
On a more general topic, you might want to use String.concat for String concatenation, or even better, a StringBuilder object.
This SO page contains a lot of info you can use on the matter.
I would use String.valueOf to explicitly cast each numeric value to String before being added. Like so:
String output = h + String.valueOf( three ) + String.valueOf( one ) + String.valueOf( ten ) + " " + "w" + String.valueOf( zero ) + "r" + String.valueOf( won ) + "d " + String.valueOf( two ) + " " + t;
The trick is to get the compiler to interpret + as string concatenation (which then silently convert the numbers to strings) instead of adding two numbers. This mean that one of the two arguments to + must be a string, and not - as your first three arguments - numbers (and yes, a char is a number).
It is not typical in code in the wild to want numbers to be directly adjacent to each other, but have a space between them, like:
String output = h + " " + three + " " + one + " " + ten + " " + "w" + zero + "r" + won + "d " + two + " " + t;
If you really want to have no spaces, then just let the first argument be the empty string:
String output = "" + h ....
You could also just change h from char to String.
The result you're getting is because, essentially, you're doing arithmetical operations on numeric variable before printing them when relying on implicit casting.
Even the Char is a numeral! H has the value 72 in the ascii table, so you are basically instructing the Java program to print the result of:
72 + 3 + 1 + 10.0 (which is equal to 86.0)
String concatenation with mixed inputs of numerals and symbols like this can be problematic since implicit casting is in play.
In order to make sure stuff is as you want, without using explicit casting, maybe use either strings between each numeric value, like this:
char h = 'H'; // This is a numeral! Capital H has value 72 in Ascii table
byte three = 3;
short one = 1;
boolean t = true; // not a numeral
double ten = 10;
float two = (float) 2.0;
long lOne = 1;
int zero = 0;
System.out.println(h + "" + three + "" + one + "" + (int) ten + " w"
+ zero + "r" + lOne + "d " + two + " " + t );
Note how I needed to cast ten to the int-type, to lose the decimal...
Above example is however not a good example of using string concatenations!
For a proper solution, and this is maybe more aimed at people with more experience, is to try using String formatting, like this:
System.out.println(String.format("%s%s%s%s w%sr%sd %s %s", h, three, one,
(int) ten, zero, lOne, two, t));
Another way is to use message formatting like this, maybe not the best choice for this assignment since the float will be printed as an integer. Also needs to import java.text.MessageFormat
// please note: the double and the float won't print decimals!
// note: import java.text.MessageFormat for this
System.out.println(MessageFormat.format("{0}{1}{2}{3} w{4}r{5}d {6} {7}", h,
three, one, (int) ten, zero, lOne, two, t));
More examples from the Ascii table.
public class Main {
public static void main(String[] args) {
int b = 3110;
int d = 0;
String e = "orld";
double f = 2;
boolean g = true;
System.out.println("H" + b + " " + "w" + d + e + " " + f + " " + g);
}
}