+ 1

What's the problem in this code?

Hello Everyone! I am a newbie java learner, and during learning classes I have coded a simple program But when I try to run it, it runs successfully but the values that it prints are 'null' If you don't understand what I am saying try to run this code yourself: public class Store { //instance fields String shopName; String productType; int brandCount; char productGrade; char profitCurrency; double profitCount; public Store(String name, String type, int count, char grade, char currency, double profit) { String shopName = name; String productType = type; int brandCount = count; char productGrade = grade; char profitCurrency = currency; double profitCount = profit; } public static void main(String []args) { Store myShop = new Store("Decent", "Cosmetics", 200, 'A', '

#x27;, 20000.00); //String in main method String Greetings = "Hello Customer!"; System.out.println(Greetings); System.out.println("Our shop name is " + myShop.shopName); System.out.println("We deal in branded " + myShop.productType); System.out.println("We have over " + myShop.brandCount + " " + myShop.productType + " brands"); System.out.println("Our " + myShop.productType + " are of " + myShop.productGrade + " grade"); System.out.println("Our average profit of this month is " + myShop.profitCurrency + myShop.profitCount); } }

20th Feb 2021, 9:25 AM
Shoaib Jamal
Shoaib Jamal - avatar
3 Réponses
+ 1
If you write for example: String shopName = name; it creates a new local variable called "shopName" which is dropped when the constructor ends. If you want to assign a value to an existing class member, don't write the data type, just write this: shopName = name;
20th Feb 2021, 11:10 AM
Lukáš Vladař
+ 3
Replace your constructor with this. public Store(String name, String type, int count, char grade, char currency, double profit) { this.shopName = name; this.productType = type; this.brandCount = count; this.productGrade = grade; this.profitCurrency = currency; this.profitCount = profit; }
20th Feb 2021, 11:05 AM
Avinesh
Avinesh - avatar
+ 2
thankyou for your answers, i have solved the problem
20th Feb 2021, 5:27 PM
Shoaib Jamal
Shoaib Jamal - avatar