34.2 Practice: Organizing Screenshots. Java | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

34.2 Practice: Organizing Screenshots. Java

Guys what am I missing here??? Code should display: Screenshot Desktop but displays null Desktop A little help please! 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(String name){ this.name = name; } //complete the second constructor ScreenShot(){ this.name = name; } //Setter public void setName(String name){ this.name = name; } //Getter public String getName(){ return name; } }

26th Jul 2021, 12:41 PM
Aleksandr Kovger
Aleksandr Kovger - avatar
4 Antworten
+ 2
In that case, you have to write this.name = "Screenshot" instead of this.name = name, in second constructor. In your current code, this.name refers to variable defined in class, while there is no parameter in second constructor, "name" will also refer to variable of class which is the cause for null output.
27th Jul 2021, 4:22 AM
Alaska
Alaska - avatar
+ 1
Thank you for your help!
27th Jul 2021, 6:58 AM
Aleksandr Kovger
Aleksandr Kovger - avatar
0
Your second contructor is lacking a parameter, which is why it assigns null to name. I can't see the problem so I am not sure, but this is the reason most probably.
26th Jul 2021, 12:51 PM
Alaska
Alaska - avatar
0
Requirement was to: 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. !!!You need to define two constructors: one should have a parameter (for setting the name taken from user) and the other one should not (for default name). I am missing something...
26th Jul 2021, 8:39 PM
Aleksandr Kovger
Aleksandr Kovger - avatar