-1

I want to update the employee name giving the choice from the user and update the corresponding player details.I am using getter and setter method to update the value. But in the output the new updated value is not showing. Review the below code where i am wrong.

 import java.io.*;
import java.util.*;
class product
{
    String name;
    public product(String name)
    {
        this.name = name;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public void display()
    {
        System.out.println("Name is " + getName());
    }
}

class Main {
    public static void main (String[] args) 
    {
        Scanner sc = new Scanner(System.in);
        String n;
        System.out.println("Update player name");
        n = sc.nextLine();

        product p1 = new product(n);
        p1.display();

        while(true)
        {
            int num=sc.nextInt();

            switch(num)
            {
                case 1:
                    System.out.println("Update name");
                    String n1 = sc.nextLine();
                  product p2 = new product(n1);
                    p2.display();
                case 2:
                    System.out.println("Display");
                    p1.display();

            }

        }

    }
}

Here in output i am not getting the updated name and while displaying the details its showing the previous name not the updated name. Plaese tell me how can i get the updated value using getter and setter. Thank You

ananya
  • 1
  • 1
  • 4

4 Answers4

1

In case 1 you don't update the name but create a new instance of the class. Try p1.setName() instead of new.

Zsolt V
  • 517
  • 3
  • 8
1

You are not using your setter to change the value of p1... instead you are making a new object (which you are then not displaying). That is a different approach than what you stated you wanted. Your way of doing things can be valid as long as you change

product p2 = new procuct(n1);

to

p1 = new product(n1);

But onto what you asked... To use a setter to do the changing you should, in case 1, use your setter method by replacing the first mentioned line of code to

p1.setName(n1);

neh11
  • 74
  • 1
  • 9
0

Check the below

 product p2 = new product("Ananya");//Create a new object with a name
 p2.display(); //prints Ananya
 p2.setName("Ananyaaa");//set a new name
 p2.display(); prints Ananyaaa
Jeeppp
  • 1,553
  • 3
  • 17
  • 39
0

You can change

case 1:
    System.out.println("Update name");
    String n1 = sc.nextLine();
    product p2 = new product(n1);
    p2.display();

to

case 1:
    System.out.println("Update name");
    String n1 = sc.nextLine();
    p1.setName(n1);
    p1.display();

You don't need another object, when all you're trying to do is actually update the existing one.

Naman
  • 27,789
  • 26
  • 218
  • 353