我正在尝试编写从我的课本中复制的此类。据我了解,我完全按照原样复制了代码,只对变量名做了些微改动。但是,当我做任何事情时,两行number = getInt(Sc3, prompt);
和d = getDouble(sc3, prompt);
会抛出错误,指出“找不到适合getInt/getDouble(Scanner, String)
的方法。为什么会这样,我可以用什么代码来解决呢?下面的代码。
import java.util.Scanner;
public class Console {
private static Scanner sc3 = new Scanner(System.in);
public static String getString(String prompt) {
System.out.print(prompt);
String s = sc3.next();
sc3.nextLine();
return s;
}
public static int getInt(String prompt) {
int number = 0;
boolean isValid = false;
while (isValid) {
System.out.print(prompt);
if (sc3.hasNextInt()) {
number = sc3.nextInt();
isValid = true;
}else {
System.out.println("Error! Entry must be an integer. Please try again.");
}
sc3.nextLine();
}
return number;
}
public static int getInt(String prompt, int minimum, int maximum) {
int number = 0;
boolean isValid = false;
while (!isValid) {
number = getInt(sc3, prompt);
if (number <= minimum) {
System.out.println("Error. User entry nust be greater than" + " " + minimum + " " + ".");
} else if (number >= maximum) {
System.out.println("Error. User entry must be less than" + " " + maximum + " " + ".");
} else {
isValid = true;
}
}
return number;
}
public static double getDouble(String prompt) {
double d = 0;
boolean isValid = false;
while (!isValid) {
System.out.print(prompt);
if (sc3.hasNextDouble()) {
d = sc3.nextDouble();
isValid = true;
} else {
System.out.println("Error. Invalid number. Try again.");
}
sc3.nextLine();
}
return d;
}
public static double getDouble(String prompt, double minimum, double maximum) {
double d = 0;
boolean isValid = false;
while (!isValid) {
d = getDouble(sc3, prompt);
if (d <= minimum) {
System.out.println("Error. Number must be greater than" + minimum + ".");
}else if (d >= maximum) {
System.out.println("Error. Number must be less than" + maximum + ".");
}else {
isValid = true;
}
return d;
}
}
}
答案 0 :(得分:0)
Java编程语言支持重载方法,并且Java可以区分具有不同方法签名的方法。这意味着,如果类中的方法具有不同的参数列表,则它们可以具有相同的名称
来自here
因此您缺少getInt(Scanner Sc3, String prompt)
和getDouble(Scanner sc3, String prompt)
方法。