【发布时间】:2013-07-13 03:38:36
【问题描述】:
我在尝试调用 main 中的方法“displayInformation”时遇到问题:
import java.util.Scanner;
public class overload
{
public static void main (String[ ] args )
{
Scanner keyboard = new Scanner(System.in);
int task;
System.out.println("Select task 1-3: ");
task=keyboard.nextInt();
if (task==1)
{
OverloadedMethod o= new OverloadedMethod();
System.out.println( o.displayInformation(int,int) );
}
else if (task==2)
{
OverloadedMethod oo= new OverloadedMethod();
System.out.println( oo.displayInformation(String, int ) );
}
else if (task==3)
{
OverloadedMethod ooo= new OverloadedMethod();
System.out.println( ooo.displayinformation(String,String) );
}
}
}
class OverloadedMethod
{
public void displayInformation (int num1, int num2)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your first int value: ");
num1=keyboard.nextInt();
System.out.print("Please enter your second int value: ");
num2=keyboard.nextInt();
System.out.print("Values entered: " + num1 + " and " + num2);
}
public void displayInformation (String str, int num)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your first string value: ");
str=keyboard.nextLine();
System.out.print("Please enter your second int value: ");
num=keyboard.nextInt();
System.out.print("Values entered: " + str + " and " + num);
}
public void displayInformation(String str1, String str2)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter your first string value: ");
str1=keyboard.nextLine();
System.out.print("Please enter your second string value: ");
str2=keyboard.nextLine();
System.out.print("Values entered: " + str1 + " and " + str2);
}
}
在节目中。我要求用户选择一个任务,每个任务调用一个不同的“displayInformation”方法来请求一个 int&int 或 int&string 或 string&string。我在调用 main 中的方法时遇到了麻烦,我在创建对象的行中不断收到错误“错误:'.class' 预期”。我只收到变量 o 和 oo 的错误,但没有 ooo。这是为什么呢?
【问题讨论】:
-
我想你的意思是
new OverloadedMethod(); -
来吧,像
OverloadedMethod x =newOverloadedMethod()这样创建一个 x 实例,然后用x像x.displayInformation(19,90)这样的实例调用方法 -
您提供了 3 个具有未使用参数的同名方法,然后强制它们仅用于区分方法。当然,您可以找到更清洁的方法。但是,如果您想强制编译器确定要调用哪个重载,则必须传递正确类型的实际元素,如
o.displayInformation ( 0, 0 )以获取 int,int 之一。 -
@javalava 你传递的是准确的
String,这没有意义哥们,你需要发送一个真实的字符串(没有它的类),比如ooo.displayinformation("Hello","Buddy"),而且这些方法也是无效的,你真的想怎么打印它们?!!
标签: java methods overloading