Java: How do I right justify a $? - java

Here's what I got:
outputStr = name + "\n" + "Gross Amount:$ " + String.format("%.2f", grossAmount) + "\n"
+ "Federal Tax:$ " + String.format("%.2f", fedIncomeTax) + "\n" + "State Tax:$ "
+ String.format("%.2f", stateTax) + "\n" + "Social Security Tax:$ " + String.format("%.2f", ssTax)
+ "\n" + "Medicare/Medicaid Tax:$ " + String.format("%.2f", medicareTax) + "\n" + "Pension Plan:$ "
+ String.format("%.2f", pensionPlan) + "\n" + "Health Insurance:$ " + String.format("%.2f", HEALTH_INSURANCE)
+ "\n" + "Net Pay:$ " + String.format("%.2f", netPay);
System.out.println(outputStr);
It prints out like this:
Random Name
Gross Amount:$ 3575.00
Federal Tax:$ 536.25
And so on...
But I want to right justify the $ and variables 15 spaces to the right, how is this done? I want it like this:
Gross Amount: $3575.00
Thanks in advance...

Printf is a good implementation here but string format should work for your purposes.
// This will give it 20 spaces to write the prefix statement and then the
//space left will be "tacked" on as blank chars.
String.format("%-20s",prefixStatement);
//Below is the printf statement for exactly what you want.
System.out.printf("%-20s$%.2f\n","Gross Amount:",3575.00);
//This executes and returns: **Gross Amount: $3575.00**
//Below will get you fifteen spaces every time.
String ga = "Gross Amount:";
System.out.printf("%-"+(ga.length()+15)+"s$%d\n","Gross Amount:",2);
//This executes and returns: **Gross Amount: $2**
The idea behind string formatting is you're building a string and then adding in characters to it later through the parameters of String.format and printf. Hope this helps.

Related

format a string for a toString() function in java with tab and new line

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

Formatting error: Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '.'

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

Creating a string with operator

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

How to include a returned string in another method - java

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.

count incrementer is wrong

My assignment calls for the line number to be display with the output. The professor suggested I do it with a counter and as seeing Java doesn't have an easy way to print out the current line number, I just created a counter as suggested. The below code is as follows:
//Count Increment
for (count = 1; count<= 5; count++)
{
}
//Display information
System.out.println(count + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
System.out.println(count + "." + " " + "Total Rooms:"+ " " + numofRooms);
System.out.println(count + "." + " " + "Total Area:"+ " " + totalSqFt + " sq.ft");
System.out.println(count + "." + " " + "The price per Sq. Ft is " + "$" + priceperSqFt);
System.out.println(count + "." + " " + "The estimated property value is "+ "$" + estimatedPropertyvalue);
However, the output starts the line counter at six as demonstrated here:
6. Street: park avenue #44
6. Total Rooms: 5
6. Total Area: 2500.0 sq.ft
6. The price per Sq. Ft is $120.4
6. The estimated property value is $301000.0
Removing the brackets doesn't help either. How can I get the line count to correctly state 1,2,3,4,5?
Please ask for clarification if needed!! Thanks.
Your prints are outside of the for loop. Your for loop ends when the counter is "6" which is when it exits the for loop. This variable doesn't change so the current value is "6",that is why it always prints "6" below on your code. If you want to print the line number for each instruction you could do something like this:
count = 0;
System.out.println(++count + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
"++count", you increment the variable the moment you write a line, in the first case it should print 1 then 2 etc. Hope this helped :)
The loop is not required cause you are only counting the lines one time each. If you put those lines in a loop that goes from 0 to 5 you will be counting each line 5 times. Since you only need to count each line ONE time you dont need the loop and just the simple increment I previously mentioned. Hope this clears out why the loop is not required
I assume that you have somewhere above this a line defining count:
int count;
So after the for loop, you've incremented count to 6 and then started printing with count left at the last incremented value from the for loop.
So, remove the for loop and just pre-increment the count variable for each line of ouput.
int count = 0;
//Display information
System.out.println( (++count) + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
...
class Print{
static int lineno = 0;
private int static getLineNo(){
lineno = lineno + 1;
return lineno;
}
}
//Display information
System.out.println(Print.getLineNo() + "." + " " + "Street:"+ " " + streetName + " " + "#" + streetNumber);
System.out.println(Print.getLineNo() + "." + " " + "Total Rooms:"+ " " + numofRooms);
System.out.println(Print.getLineNo() + "." + " " + "Total Area:"+ " " + totalSqFt + " sq.ft");
System.out.println(Print.getLineNo() + "." + " " + "The price per Sq. Ft is " + "$" + priceperSqFt);
System.out.println(Print.getLineNo() + "." + " " + "The estimated property value is "+ "$" + estimatedPropertyv

Categories

Resources