forked from Nnamdikeshi/Java2545examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringFormattingExamples.java
More file actions
53 lines (33 loc) · 2.35 KB
/
Copy pathStringFormattingExamples.java
File metadata and controls
53 lines (33 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package week1_variables_if_else;
public class StringFormattingExamples {
public static void main(String[] args) {
//Some example variables
String eventName = "Minnesota State Fair";
String slogan = "12 Days of Fun Ending Labor Day!";
int numberOfRides = 48;
int daysOfStateFair = 12;
double stateFairAdmission = 12;
double priceOfCornDog = 5.25;
//Some math, to create a few more variables....
//If I go to the fair every day, and eat a corn dog every day, what will that cost?
double cornDogAndAdmissionCost = daysOfStateFair * (stateFairAdmission + priceOfCornDog);
//So I go to the fair every day, and I want to go on all of the rides. How many rides do I need to go on per day?
int ridesPerDay = numberOfRides / daysOfStateFair;
//Output some data, using String formatting
// %s is replaced with a String
// %d is replaced with an int
// %f is replaced with a double
// %.2f is replaced with a double, displayed with 2 decimal places
// %.5f is replaced with a double, displayed with 5 decimal places
// Can use as many placeholders as you like. Make sure you have a variable for each placeholder.
// IntelliJ will check that you've got the right number and types of variables.
System.out.println(String.format("This program is looking forward to going to the %s", eventName));
//Notice that the stateFairAdmission variable stores 12, but using %.2f causes it to be displayed as 12.00.
System.out.println(String.format("It costs %.2f dollars to get into the %s. A corn dog costs %.2f dollars", stateFairAdmission, eventName, priceOfCornDog));
System.out.println(String.format("If I go to the %s every day and eat a corn dog every day, it will cost a total of %.2f dollars", eventName, cornDogAndAdmissionCost));
System.out.println(String.format("Or with a dollar sign: $%.2f", cornDogAndAdmissionCost));
System.out.println(String.format("To go on all of the rides, I need to go on %d rides per day for %d days.", ridesPerDay, daysOfStateFair));
System.out.println(String.format("\"%s\" is the slogan for the %s", slogan, eventName));
System.out.println(String.format("According to my variables, the %s has %d days!", eventName, daysOfStateFair));
}
}