Unit 5: Discussion - Part 2
No unread replies.No replies.
Question
Read the lecture for Chapter 5 and then answer the following:.
Present an ORIGINAL example of the correct use of the printf method. This example must show how integers, doubles and Strings are properly formatted for display. At least one integer, one double, and one String must be printed using printf. You are encouraged to consult the textbook and any other sources you deem relevant, but come up with an example of your own. Show a complete Java program and a screen capture with a sample output.
If you have any problem with the program feel free to comment
Program
class Song {//for storing the data of the songs
//instance variables
private String name, artist;
private double playtime;
private int year;
//parameterized constructor
public Song(String name, String artist, double
playtime, int year) {
this.name = name;
this.artist = artist;
this.playtime = playtime;
this.year = year;
}
//getters
public String getName() {
return name;
}
public String getArtist() {
return artist;
}
public double getPlaytime() {
return playtime;
}
public int getYear() {
return year;
}
}
public class Test {//driver class
public static void main(String[] args) {
Song[] ar = new Song[5];
//storing the list of song in the
array
ar[0] = new Song("Happy Together",
"The Turtles", 2.57, 1967);
ar[1] = new Song("Take on me",
"a-ha", 3.50, 1985);
ar[2] = new Song("Never gonna give
you up", "Rick Astley", 3.33, 1987);
ar[3] = new Song("Stand by me",
"Ben E King", 2.58, 1961);
ar[4] = new Song("Angel of the
morning", "Juice Newton", 3.54, 1981);
System.out.println("List of songs:
");
for(Song i: ar) {//printing the
list of songs using printf
System.out.printf("Name: %s\n", i.getName());
System.out.printf("Artist: %s\n", i.getArtist());
System.out.printf("Playtime: %.2fmin\n",
i.getPlaytime());//printing up to 2 decimal places
System.out.printf("Year: %d\n", i.getYear());
System.out.println();
}
}
}
Output
Get Answers For Free
Most questions answered within 1 hours.