最近我一直在努力学习java,最后我完成了我的第一段代码。对我能改进的地方有什么建议吗?另外,是否有可能使用类似python中的init函数向类发送一个参数,并且有什么好的和坏的习惯我应该记住呢?
class LIFO {
//Create an empty list with the lenght of the given size
//Initialize our top value as 0
int my_list[] = new int[5];
int top = 0;
//Adds a value to the list
//Add one to our top
public void push(int data)
{
my_list[top] = data;
top++;
}
//Removes the top value from the list
//Substract one from our top
public int pop()
{
int data;
top--;
data = my_list[top];
my_list[top] = 0;
return data;
}
//Prints our list
public void show()
{
for(int n : my_list)
{
System.out.print(n + " ");
}
}
}
//Driver Class
class Main {
public static void main(String args[])
{
LIFO s = new LIFO();
s.push(1);
s.push(2);
s.push(3);
s.show();
System.out.println("\n" + s.pop() + " Popped from stack");
s.show();
}
}发布于 2020-08-10 02:11:25
我相信你要找的是一个构造师。
class LIFO {
//Create an empty list with the lenght of the given size
//Initialize our top value as 0
int my_list[];
int top = 0;
public LIFO(int size) {
my_list = new int[size];
}
...像这样打电话。
public static void main(String[] args) {
LIFO lifo = new LIFO(10);
lifo.push(10);
lifo.push(20);
System.out.println(lifo.pop());
System.out.println(lifo.pop());
}发布于 2020-08-13 08:10:10
@Ted Brownlow已经回答了您的构造函数问题,但是下面还有几点值得考虑的地方.
您的类需要提供一个功能强大、可用和集中的接口。目前,您的类负责实现LIFO并将它们输出到控制台。这些都是不同的担忧。考虑一下,与其写到控制台,不如写到一个网页/不同的窗口。将显示逻辑直接构建到类中会降低其灵活性。一个很好的练习可能是删除show方法,并决定您需要在类中添加哪种方法(S),以便允许在类之外实现它。
目前,您的类的最大固定大小为5。但是,除了通过读取类之外,客户端无法知道(可能缺少maxSize方法或类似的方法)。客户端也无法知道列表中有多少项,除非他们自己跟踪它(可能缺少currentSize方法或类似的)。
没有这些大小信息,客户端就无法知道调用push或pop是否安全。考虑一下,当push被调用时,如果您已经有5个条目,会发生什么。如果0项存在并且pop被调用,会发生什么情况?目前,您正依赖于框架来处理这些场景。如果这是一个有意识的决定,这是可以的,但是您可能想要考虑添加一些边界检查,并抛出异常,从而更明确地帮助您的类的用户知道他们做错了什么。
https://codereview.stackexchange.com/questions/247699
复制相似问题