Mark Martin Mark Martin - 9 months ago 32
Java Question

How to not overwrite the value at the time of inputting values ​in a class?

In this case, I input a name. I want to input a name from main class and then pass it to newClass. When I try to input another name again, I've seen that the name before is overwritten.

public class JavaApplication107 {
public static void main(String[] args) {
byte number;
NewClass obj = new NewClass();
do{
System.out.println("MENU : ");
System.out.println("1. Show Data");
System.out.println("2. Input Data");
System.out.println("3. Exit");
Scanner sc1 = new Scanner(System.in);
Scanner sc2 = new Scanner(System.in);
System.out.print("Input Number : ");
number = sc1.nextByte();
switch (number){
case 1:
obj.setShowBiodata();
break;
case 2:
System.out.print("Input your name : ");
String strTmp = sc2.nextLine();
obj.setName(strTmp);
break;
}
}while(number != 3);
}}



Blockquote


public class NewClass {
private String mName;
void setName(String name){
mName = name;
}
void setShowBiodata(){
System.out.println("Name : " + mName);
}}


So I can get more than one name

Answer Source

Try this code it should print out all of the names

public class NewClass {
private String mName ="";
void setName(String name){
    mName = mName+"\n"+name;
}
void setShowBiodata(){
    System.out.println("Name : " + mName);
}}

Here is a way you could use an array

public class NewClass {
private String[] names = new String[20];
private int number = 0;
void setName(String name){
    names[number]= name;
    number++:
}
void setShowBiodata(){
 for (int i =0; i<number; i++)
    {
     System.out.println(names[i]);
    }   
}}