在我发布的这个程序中,当我调用(setter函数)时。主函数中的obj.setsize(res)不能将private int size = 2的值(类“ contact_entry”中的声明变量“ size”)更改为size = 1。
当我调用(getter函数)时,该值保持为2。在主程序中的obj.getsize()中,在if(obj.getsize()> 0)中。在调用set方法时,应将变量“ size的值”设置为1,但无法修改该值和“大小保持不变”的值。
请让我知道我将不胜感激的问题。
import javax.swing.JOptionPane;
public class nokia {
public static void main(String[] args)
{
int itr=0;
while(itr==JOptionPane.YES_OPTION)
{
String s3=JOptionPane.showInputDialog("Enter your option\nEnter 1 to add contact\nEnter 2 to delete contact\nEnter 3 to display contact" +
"\nEnter 4 to search a contact detail\nEnter 5 to exit");
switch(s3)
{
case "1":
{
contact_entry obj=new contact_entry();
if(obj.getsize()>0)
{
obj.add_contact();
int res=obj.getsize()-1;
obj.setsize(res);
}
else
JOptionPane.showMessageDialog(null, "MEMORY FULL....NO MORE CONTACTS CAN BE ADDED");
break;
}
case "2":
}
}
}
}
class contact_entry
{
private String fst_nme;
private String lst_nme;
private long [] mo_no=new long[3];
private int[] hme_no=new int[3];
private int size=2;
public contact_entry()
{
fst_nme="ron";
lst_nme="capton";
mo_no[0]=mo_no[1]=mo_no[2]=0;
hme_no[0]=hme_no[1]=hme_no[2]=0;
}
public void add_contact()
{
fst_nme=JOptionPane.showInputDialog("Enter the first name: ");
lst_nme=JOptionPane.showInputDialog("Enter last name: ");
int itr=0,itr1=0;
for(int i=0;itr==JOptionPane.YES_OPTION;i++)
{
if (i>2)
{
JOptionPane.showMessageDialog(null,"NO MORE MOBILE NUMBER CAN BE ADDED...MEMORY FULL");
break;
}
String s1=JOptionPane.showInputDialog("Enter mobile number: ");
mo_no[i]=Long.parseLong(s1);
itr=JOptionPane.showConfirmDialog(null, "Do you want to add addtional contact number");
}
for(int i=0;itr1==JOptionPane.YES_OPTION ;i++)
{
if(i>2)
{
JOptionPane.showMessageDialog(null, "NO MORE PHONE NUMBER CAN BE ADDED....MEMORY FULL");
break;
}
String s2=JOptionPane.showInputDialog("Enter phone number: ");
hme_no[i]=Integer.parseInt(s2);
itr1=JOptionPane.showConfirmDialog(null, "DO you want to add more contact number");
}
}
public void display()
{
String output= "First Name: "+fst_nme+"\nLast name: "+lst_nme+"\nmobile number1: "+mo_no[0]+"\nmobile number2: "+mo_no[1]+
"\nmobile number3: "+mo_no[2]+"\nphone number1: "+hme_no[0]+"\nphone number2: "+hme_no[1]+"\nphone number3: "+hme_no[2];
JOptionPane.showMessageDialog(null, output);
}
public int getsize()
{
JOptionPane.showMessageDialog(null, size);
return size;
}
public void setsize(int size1)
{
this.size=size1;
JOptionPane.showMessageDialog(null, size);
}
}
最佳答案
我无法用您的代码复制此代码。注释掉add_contact
(因为它无关紧要),我看到三个对话框:
2(第一个呼叫getsize()
)
2(第二次呼叫getsize()
)
1(呼叫setsize()
)
因此它将size
的值设置为1。
请注意,当您循环并创建一个新的contact_entry
实例时,该实例的大小将为2 ...是不是让您感到困惑?
(顺便说一句,您应该真正尝试遵循Java命名约定。此刻,您的代码非常单一。)