0

我在尝试调用 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。为什么是这样?

4

1 回答 1

0

OverloadedMethod是一个类,没有定义参数的构造函数。

所以你必须做

   OverloadedMethod o= new OverloadedMethod();


   switch (task){
   case 1:
    System.out.println( o.displayInformation(num1,num2) );break;
   case 2:
    System.out.println( o.displayInformation(str,num ) );break; 
   case 3:
    System.out.println( o.displayinformation(str1,str2) );break;
   default:
      System.out.println("invalid option");     

你需要定义和赋值给num1 num2 str num strstr2

同样重要的是,displayInfomartion必须返回ObjecttoString()实现人类可读的(或子类)。

例子 :

public String displayInformation(...)

于 2013-07-13T03:49:24.160 回答