我想编写一个不接受参数的构造函数,所以如果我没有实例变量,我用来创建一个构造函数,我有实例变量,我知道java创建一个默认的构造函数,如果我不有一个,但我被告知这是一个不好的编程习惯???(新课程)如果没有任何实例变量,我将如何为我的类编写构造函数?
public class Validator {
public Validator() {
}
public String getString(Scanner sc, String prompt) {
System.out.print(prompt);
String s = sc.next(); // read user entry
sc.nextLine(); // discard any other data entered on the line
return s;
}
public int getInt(Scanner sc, String prompt) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNextInt()) {
i = sc.nextInt();
isValid = true;
} else {
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}
public int getInt(Scanner sc, String prompt, int min, int max) {
int i = 0;
boolean isValid = false;
while (isValid == false) {
i = getInt(sc, prompt);
if (i <= min)
System.out.println("Error! Number must be greater than " + min
+ ".");
else if (i >= max)
System.out.println("Error! Number must be less than " + max
+ ".");
else
isValid = true;
}
return i;
}
public double getDouble(Scanner sc, String prompt) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
if (sc.hasNextDouble()) {
d = sc.nextDouble();
isValid = true;
} else {
System.out.println("Error! Invalid decimal value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return d;
}
public double getDouble(Scanner sc, String prompt, double min, double max) {
double d = 0;
boolean isValid = false;
while (isValid == false) {
d = getDouble(sc, prompt);
if (d <= min)
System.out.println("Error! Number must be greater than " + min
+ ".");
else if (d >= max)
System.out.println("Error! Number must be less than " + max
+ ".");
else
isValid = true;
}
return d;
}
}
构造函数之后的所有代码如何与您的问题相关? – Dan 2013-02-26 00:25:45
如果在构造函数中没有任何要做的事,那么你不需要声明它。 – 2013-02-26 00:26:27
我认识的人最近也在学习编程。他的教材中说:“总是创造吸气和安装者”,但他从未停下来问他为什么需要他们。现在他暴露私人变数并隐藏公众。当你设计对象时,应该比“对象导向哲学”更符合特定部分的一般规则。这只狗是否需要知道猫发出的声音?也许是这样,但它是否需要知道猫的饥饿的内部状态呢?可能不会。构造函数会遵循类似的要点 – 2013-02-26 01:01:43