我想編寫一個不接受參數的構造函數,所以如果我沒有實例變量,我用來創建一個構造函數,我有實例變量,我知道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