34.3 Practice Constructors | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

34.3 Practice Constructors

We are creating our own application for taking screenshots. It has an option to set a name for screenshot-file to be saved. If user doesn't insert a name for it while saving, program automatically sets "Screenshot" name for it. Given program should create and save two screenshots: one with default name and one with name given by user. But something goes wrong. Fix the program by completing two constructors, so that given outputs works correctly. Sample Input Desktop Sample Output Screenshot Desktop

7th Aug 2021, 5:37 AM
Chin Eu
Chin Eu - avatar
4 Answers
+ 6
The way you are invoking name in the constructors make Java think you are looking for a name() method in the class, when name is in fact a member variable. Instead, do: this.name = "Screenshot"; this.name = name; Either that, or use your setName() method. setName("Screenshot"); setName(name);
7th Aug 2021, 6:11 AM
Hatsy Rei
Hatsy Rei - avatar
+ 3
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); String name = read.next(); //screenshots ScreenShot screenshot1 = new ScreenShot(); ScreenShot screenshot2 = new ScreenShot(name); //outputting the names System.out.println(screenshot1.getName()); System.out.println(screenshot2.getName()); //Please Subscribe to My Youtube Channel //Channel Name: Fazal Tuts4U } } class ScreenShot{ private String name; //complete the first constructor ScreenShot(){ this.name = "Screenshot"; } //complete the second constructor ScreenShot(String name){ this.name = name; } //Setter public void setName(String name){ this.name = name; } //Getter public String getName(){ return name; } }
4th Sep 2021, 7:16 AM
Fazal Haroon
Fazal Haroon - avatar
0
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner read = new Scanner(System.in); String name = read.next(); //screenshots ScreenShot screenshot1 = new ScreenShot(); ScreenShot screenshot2 = new ScreenShot(name); //outputting the names System.out.println(screenshot1.getName()); System.out.println(screenshot2.getName()); } } class ScreenShot{ private String name; //complete the first constructor ScreenShot(){ this.name("Screenshot"); } //complete the second constructor ScreenShot(String name){ this.name("name"); } //Setter public void setName(String name){ this.name = name; } //Getter public String getName(){ return name; } } My code as above but it says cannot find symbol for this.name Please help
7th Aug 2021, 5:39 AM
Chin Eu
Chin Eu - avatar
0
Thanks Hatsy Rei !!!
7th Aug 2021, 1:14 PM
Chin Eu
Chin Eu - avatar