- 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
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);
+ 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;
}
}
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
0
Thanks Hatsy Rei !!!