Invalid method declaration; return type required

The code:
          public Reminder(int seconds) {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds*1000);
    class RemindTask extends TimerTask {
        public void run() {
            System.out.format("Time's up!%n");
            timer.cancel(); //Terminate the timer thread
public static void main(String[] args)
          JFrame.setDefaultLookAndFeelDecorated(true);
          JDialog.setDefaultLookAndFeelDecorated(true);
          try
               UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
          catch (Exception ex)
               System.out.println("Failed loading L&F: ");
               System.out.println(ex);
       new superball();
                new Reminder(5);
        System.out.format("Task scheduled.%n");
//= End of Testing =
    }Gives:
"invalid method declaration; return type required"
If i add void to public Reminder(int seconds) {It prints:
cannot find symbol
symbol : class Reminder
location: class superball
new Reminder(5);
Is it because of the public class?
public class superball extends JFrameHere is the FULL code:
/*                      superball                                 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.regex.Pattern;
import java.util.Timer;
import java.util.TimerTask;
import java.util.*;
import java.io.*;
* Summary description for superball
public class superball extends JFrame
     // Variables declaration
     int ballx;
  int bally;
     int jumpstop;
     int stopper;
     int coin;
     int coinx;
     int coiny;
     int coinvaluex;
     int coinvaluey;
  Timer timer;
  private int value = 0;
     private static Random r = new Random();
     private JLabel jLabel1;
     private JLabel jLabel2;
     private JLabel jLabel4;
     private JLabel jLabel5;
     private JLabel jLabel7;
     private JLabel jLabel9;
     private JLabel jLabel10;
     private JPanel contentPane;
     private JPanel jPanel1;
     // End of variables declaration
     public superball()
          super();
          initializeComponent();
          // TODO: Add any constructor code after initializeComponent call
          this.setVisible(true);
      * This method is called from within the constructor to initialize the form.
      * WARNING: Do NOT modify this code. The content of this method is always regenerated
      * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
      * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
      * to retrieve your design properly in future, before revising this method.
     private void initializeComponent()
          jLabel1 = new JLabel();
          jLabel2 = new JLabel();
          jLabel4 = new JLabel();
          jLabel5 = new JLabel();
          jLabel7 = new JLabel();
          jLabel9 = new JLabel();
          jLabel10 = new JLabel();
          coin = 1;
          coinx = Math.abs(r.nextInt()) % 460 + 100;
          coiny = Math.abs(r.nextInt()) % 200 + 100;
          ballx = 342;
          bally = 338;
          jumpstop = 0;
          stopper = 13;
          contentPane = (JPanel)this.getContentPane();
          jPanel1 = new JPanel();
          // jLabel1
          jLabel1.setIcon(new ImageIcon("IMG\\coin.gif"));
          jLabel1.setText("0");
          // jLabel2
          jLabel2.setIcon(new ImageIcon("IMG\\logo.PNG"));
          // jLabel4
          jLabel4.setIcon(new ImageIcon("IMG\\black.GIF"));
          // jLabel5
          jLabel5.setIcon(new ImageIcon("IMG\\ballstanding2.gif"));
          // jLabel7
          jLabel7.setIcon(new ImageIcon("IMG\\star-heart.gif"));
          jLabel7.setText(" 100");
          // jLabel9
          jLabel9.setIcon(new ImageIcon("IMG\\coin.gif"));
          // jLabel10
          jLabel10.setIcon(new ImageIcon("IMG\\stage1.GIF"));
          // contentPane
          contentPane.setLayout(null);
          contentPane.setBackground(new Color(255, 254, 254));
          addComponent(contentPane, jLabel5, 342,338,60,18);
          addComponent(contentPane, jLabel1, 561,4,100,18);
          addComponent(contentPane, jLabel2, 2,3,208,24);
          addComponent(contentPane, jLabel7, 495,4,60,18);
          addComponent(contentPane, jLabel9, coinx,coiny,19,18);
          addComponent(contentPane, jLabel2, 2,3,208,24);
          addComponent(contentPane, jLabel10, -2,29,738,412);
          addComponent(contentPane, jPanel1, 79,209,200,100);
          // jPanel1
          jPanel1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
          jPanel1.setFocusable(true);
          jPanel1.addKeyListener(new KeyAdapter() {
               public void keyPressed(KeyEvent e)
                    jPanel1_keyPressed(e);
               public void keyReleased(KeyEvent e)
                    jPanel1_keyReleased(e);
               public void keyTyped(KeyEvent e)
                    jPanel1_keyTyped(e);
          // superball
          this.setTitle("Superball created by Hannes Karlsson");
          this.setLocation(new Point(0, 0));
          this.setSize(new Dimension(617, 450));
          this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
          this.setResizable(false);
     /** Add Component Without a Layout Manager (Absolute Positioning) */
     private void addComponent(Container container,Component c,int x,int y,int width,int height)
          c.setBounds(x,y,width,height);
          container.add(c);
     // TODO: Add any appropriate code in the following Event Handling Methods
     private void jPanel1_keyPressed(KeyEvent e)
          System.out.println("\njPanel1_keyPressed(KeyEvent e) called.");
          // TODO: Add any handling code here
          if(e.getKeyCode()==e.VK_LEFT) // when the user enters left
              jLabel5.setLocation(new Point(ballx--, bally));
                    jLabel5.setLocation(new Point(ballx--, bally));
                    jLabel5.setLocation(new Point(ballx--, bally));
                    jLabel5.setLocation(new Point(ballx--, bally));
                    jLabel5.setIcon(new ImageIcon("IMG\\ballroll.gif"));
                    } // equalling PLAIN_SPEED
                                        if(e.getKeyCode()==e.VK_RIGHT) // when the user enters right
              jLabel5.setLocation(new Point(ballx++, bally));
                    jLabel5.setLocation(new Point(ballx++, bally));
                    jLabel5.setLocation(new Point(ballx++, bally));
                    jLabel5.setLocation(new Point(ballx++, bally));
                    jLabel5.setIcon(new ImageIcon("IMG\\ballroll.gif"));
                    } // equalling PLAIN_SPEED
                                                            if(e.getKeyCode()==e.VK_UP) // when the user enters up
              jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setIcon(new ImageIcon("IMG\\balljetpack.gif"));
                    } // equalling PLAIN_SPEED
                                                                                if(e.getKeyCode()==e.VK_DOWN) // when the user enters up
              jLabel5.setLocation(new Point(ballx, bally++));
                    jLabel5.setLocation(new Point(ballx, bally++));
                    jLabel5.setLocation(new Point(ballx, bally++));
                    jLabel5.setLocation(new Point(ballx, bally++));
                    jLabel5.setIcon(new ImageIcon("IMG\\ballroll.gif"));
                    } // equalling PLAIN_SPEED     
                    if(bally>=340)
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                              System.out.println("LOW!!!");
                    if(bally<=-2)
                    jLabel5.setLocation(new Point(ballx, bally++));
                    jLabel5.setLocation(new Point(ballx, bally++));
                    jLabel5.setLocation(new Point(ballx, bally++));
                    jLabel5.setLocation(new Point(ballx, bally++));
                              System.out.println("HIGH!!!");
                                        if(ballx>=594)
                    jLabel5.setLocation(new Point(ballx--, bally));
                    jLabel5.setLocation(new Point(ballx--, bally));
                    jLabel5.setLocation(new Point(ballx--, bally));
                    jLabel5.setLocation(new Point(ballx--, bally));
                              System.out.println("RIGHT!!!");
                                                            if(ballx<=-3)
                    jLabel5.setLocation(new Point(ballx++, bally));
                    jLabel5.setLocation(new Point(ballx++, bally));
                    jLabel5.setLocation(new Point(ballx++, bally));
                    jLabel5.setLocation(new Point(ballx++, bally));
                              System.out.println("LEFT!!!");
                                                                       if (bally==294 && (ballx > 218 && ballx < 274))
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                                                                       if (bally==262 && (ballx > 246 && ballx < 306))
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                                                   if (bally==230 && (ballx > 486 && ballx < 562))
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                                    if (bally==310 && (ballx > 486 && ballx < 594))
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                     if (bally==262 && (ballx > 442 && ballx < 514))
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
      if (bally==294 && (ballx > 378 && ballx < 466))
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
                    jLabel5.setLocation(new Point(ballx, bally--));
               // COIN
                     if ((bally > coiny-10 && bally < coiny+10) && (ballx > coinx-10 && ballx < coinx+10))
            coinx = Math.abs(r.nextInt()) % 617 + 1;
            coiny = Math.abs(r.nextInt()) % 300 + 1;
               jLabel9.setLocation(new Point(coinx, coiny));
                    System.out.println("Coinx:"+coinx+"");
                    System.out.println("Coiny:"+coiny+"");
                    jLabel1.setText(""+ coin++ +"");
                    System.out.println("Ballx:"+ballx+"");
                    System.out.println("Bally:"+bally+"");
     private void jPanel1_keyReleased(KeyEvent e)
          System.out.println("\njPanel1_keyReleased(KeyEvent e) called.");
          // TODO: Add any handling code here
          jLabel5.setIcon(new ImageIcon("IMG\\ballstanding2.gif"));
     private void jPanel1_keyTyped(KeyEvent e)
          System.out.println("\njPanel1_keyTyped(KeyEvent e) called.");
          // TODO: Add any handling code here
     // TODO: Add any method code to meet your needs in the following area
//============================= Testing ================================//
//=                                                                    =//
//= The following main method is just for testing this class you built.=//
//= After testing,you may simply delete it.                            =//
//======================================================================//
          public void Reminder(int seconds) {
        timer = new Timer();
        timer.schedule(new RemindTask(), seconds*1000);
    class RemindTask extends TimerTask {
        public void run() {
            System.out.format("Time's up!%n");
            timer.cancel(); //Terminate the timer thread
     public static void main(String[] args)
          JFrame.setDefaultLookAndFeelDecorated(true);
          JDialog.setDefaultLookAndFeelDecorated(true);
          try
               UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
          catch (Exception ex)
               System.out.println("Failed loading L&F: ");
               System.out.println(ex);
       new superball();
                new Reminder(5);
        System.out.format("Task scheduled.%n");
//= End of Testing =
}

No, it's because you can't have a constructor called Reminder if you don't have a class named Reminder.

Similar Messages

  • Invalid method declarations?

    hi, new to JAVA, and i have a problem, I am getting invalid method declarations for "printStraightLine()" and "printSumOfYears();" and would like them to become valid so that way i am able to start cracking away at the formulas...any type of suggestions would be appreciated...Mike...so here's the code:
    import java.io.*;
      class Depreciation
        private char choice;
        private int purchasePrice;
        private int salvageValue;
        private int usefulLife;
        private printSumOfYears();
        private printStraightLine();
        private double deprec;
       Depreciation()   {}
       Depreciation(char choice, int purchasePrice, int salvageValue, int usefulLife)
           this.choice = choice;
           this.purchasePrice = purchasePrice;
           this.salvageValue = salvageValue;
           this.usefulLife = usefulLife;
        public char getchoice()
                {return choice;}
        public int getpurchasePrice()
                {return purchasePrice;}
        public int getsalvageValue()
                {return salvageValue;}
        public int getusefulLife()
                {return usefulLife ;}
      void setDepreciation(int purchasePrice, int salvageValue, int usefulLife)
        this.purchasePrice = purchasePrice;
          this.salvageValue = salvageValue;
          this.usefulLife = usefulLife;
      void setChoice(char choice)
      {  this.choice = choice;}
    public printStraightLine()
    {   double deprec;
        while (usefulLife < 0);
        for (usefulLife = 1; usefulLife <= usefulLife; usefulLife++)
            deprec = (purchasePrice - salvageValue) / (usefulLife);
            System.out.println("Year"+ usefulLife + "\t" + "Depreciation" + "\t" + deprec);
    public printSumOfYears()
      { double deprec;
          while (usefulLife <=1);
          for (usefulLife = usefulLife; usefulLife <= 1; usefulLife--)
              deprec =
              System.out.println("Year"+ usefulLife + "\t" + "Depreciation" + "\t" + deprec);
    public String toString();
              String s = new String();
              s = ' ' + "Purchase Price = " + purchasePrice + "  " + "Salvage Value = " + salvageValue + "  " + "Use Life = " + usefulLife + "  " + "Sum of Years = " + SumOfYears + "  " + "Straight Line = " + StraightLine;
              return s;
     

    That did it! I forgot to declare printSumof... and print Straight... as String Methods...
    ok now ive gotten rid of all the syntax errors in it and now ive run into a larger problem...the menu class that i have, wont accept my Depreciation...i think its perhaps theres something wrong with the toString Method perhaps but this is the last bit i need to get over the hill, per se...so heres the Depreciation Coding(without syntax errors and following it will be my MenuDrivenClass that corresponds....
    DEPRECIATION CODING
    import java.io.*;
      class Depreciation
        private char choice;
        private double purchasePrice;
        private double salvageValue;
        private int usefulLife;
       Depreciation()   {}
       Depreciation(char choice, double purchasePrice, double salvageValue, int usefulLife)
           this.choice = choice;
           this.purchasePrice = purchasePrice;
           this.salvageValue = salvageValue;
           this.usefulLife = usefulLife;
        public char getChoice()
                {return choice;}
        public double getpurchasePrice()
                {return purchasePrice;}
        public double getsalvageValue()
                {return salvageValue;}
        public int getusefulLife()
                {return usefulLife ;}
      void setDepreciation(double purchasePrice, double salvageValue, int usefulLife)
        this.purchasePrice = purchasePrice;
          this.salvageValue = salvageValue;
          this.usefulLife = usefulLife;
      void setChoice(char choice)
      {  this.choice = choice;}
    public String printStraightLine()
    {   double deprec;
        while (usefulLife < 0);
        for (usefulLife = 1; usefulLife <= usefulLife; usefulLife++)
            deprec = (purchasePrice - salvageValue) / (usefulLife);
            System.out.println("Year"+ usefulLife + "\t" + "Depreciation" + "\t" + deprec);
    public String printSumOfYears() //musthave decrementing loop
      { double deprec;
          while (usefulLife >=1);
          for (usefulLife = usefulLife; usefulLife >= 1; usefulLife--)
              deprec = 20-10;
              System.out.println("Year"+ usefulLife + "\t" + "Depreciation" + "\t" + deprec);
    public String toString()
              String d = new String();
              d = ' ' + "Purchase Price = " + purchasePrice + "  " + "Salvage Value = " + salvageValue + "  " + "Use Life = " + usefulLife + "  " + "Sum of Years = " + printSumOfYears() + "  " + "Straight Line = " + printStraightLine();
              return d;
      NOW HERES THE MENU DRIVEN CLASS
    // Professor Dreher
    import java.text.DecimalFormat;
    import java.io.*;
    public class MenuDrivenClass2
        public static void main(String[] args)throws IOException
          BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
          char choice;
          Depreciation myDepreciation = new Depreciation();
          do
            PrintMenu();
            choice = GetChoice();
            switch (choice)
              case 'i': myDepreciation= getInput();
                        break;
              case 'a': System.out.println(myDepreciation);
                        myDepreciation.printStraightLine();
                        break;
              case 'b': System.out.println(myDepreciation);
                        myDepreciation.printSumOfYears();
                        break;
              case 'q': System.out.print(" Goodbye, have a nice day! ");
                        break;
           }//ends switch
         }while(choice != 'q');
       }//ends main
      static void PrintMenu()
          System.out.println("\n\n i - to input new depreciation information ");
          System.out.println(" a - to use the straight-line method ");
          System.out.println(" b - to use the sum-of-the-years' digits method ");
          System.out.println(" q - to quit ");
          System.out.print(" --> " );
      static char GetChoice()throws IOException
           BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
           char choice;
           do
             String text = in.readLine();
             choice = Character.toLowerCase(text.charAt(0));
             if(choice != 'i' && choice != 'a' && choice != 'b'  && choice != 'q')
               {  System.out.print(" Incorrect choice, please try again! ");}
            } while (choice != 'i' && choice != 'a' && choice != 'b'  && choice != 'q');
           return(choice);
      static Depreciation getInput()throws IOException
           BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
           System.out.print("\n Enter Purchase Price: ");
           double purchasePrice = Double.parseDouble(in.readLine());
           System.out.print(" Enter Salvage Value: ");
           double salvageValue = Double.parseDouble(in.readLine());
           System.out.print(" Enter Useful Life: ");
           int usefulLife = Integer.parseInt(in.readLine());
           Depreciation d = new Depreciation(purchasePrice,salvageValue,usefulLife);
           return(d);              
    }IN THE LAST LINE(Depreciation d=....), the "new" is a syntax error, reading..."cannot resolve symbol Depreciation (double, double, int) @ line 86"....I thank all for helping me...the Duke Dollars is now up to 10...any help is greatly appreciated....SO, any thoughts?

  • Invalid method declaration

    Hi there,
    I have a problem to compile below sentences.
    import java.awt.* ;
    import javax.swing.* ;
    import java.awt.event.* ;
    public class p662 extends JFrame
    public ShowColors()
    ** invalid method declariration for ShowColors ****
    super ("Using colors") ;
    Please help me.
    Best regards

    What the diddley?
    Your class name is p662 (what the heck is that?).
    The declaration public ShowColors looks like a constructor. You call super in it with a String argument, which looks like you want to invoke a JFrame ctor.
    You can't invoke a super class constructor in any method except a class constructor. The class constructors must have the same name as the class. The class must go in a file whose name is the same as the public class inside.
    You should follow the Sun coding standards for naming:
    http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
    What are you doing here? This is unintelligible. - MOD

  • Why return type required on a constructor?

    I am trying to show student number, grade and course number. When I try to compile the start of my work, it won't compile. It keeps getting hung up on my constructor.
    It is stating that I need a return type for line: "public StuID(int idNum)" line. (for me it is line 13.
    . This isn't even homework. This is exactly how they have it in my book. Very easy if I typed something wrong, but the textbook doesn't show a type either.
    public class Students
         private int stuNum;
         private String grade;
         public int courseNum;
         public StuID(int idNum)
              String[] gradeSchedule = {A, B, C, D, F};
              int[] courseList = {"X", "101", "102", "103", "104", "105"};
              stuNum = idNum;
              if (idNum > gradeSchedule.length)
         idNum=0;
              grade = gradeSchedule[idNum];
              course = courseList[idNum];
         public int getStu()
         return stuNum;
          public String getGrade()
         return grade;
          public int getCourseNum()
         return courseNum;
          public void setStu(int numStu)
         stuNum = numStu;
          public void setGrade (String stuGrade)
         grade = stuGrade;
          public void setCourse (int numCourse)
         courseNum = numCourse;
    }As I stated earlier, I have just started typing this section. I follow the text and compile when they tell me to. However at this point, I get the return type is needed message.
    Looking at a book and trying to type what they have, I could have left something out, but I sure think it looks like what they have in the book. Can anyone spot why it is asking me for a return type on the "public StuID(int idNum)" line?
    Thanks,
    Gizelle

    Since the class is named Students, a constructor for the class will look like public Students() { ... } StuId is just a method (and a poorly named one) and so it must have a return type (which could be void).

  • Implementing Empty Versions of Interface Methods with Return Types

    Subject probably is probably a bit long but I was stumped for a brief way to summarize my question. Let's say I have the interface below:
    public interface DAO {
        ...snip...
        public Object get(int id);
        public Object[] get(String clause);
        ...snip...
    }From this I want to make two concrete classes, say ClassOne and ClassTwo. Given the type of data each one is fetching, ClassOne only needs (and should only) implement get(int id) and ClassTwo only needs (and should only) implement get(String clause). This is because the first class will always deal with only one record from table_a and the second class will always deal with one or more records from table_b. So my question is what is the correct way to provide empty implementations for the unnecessary methods?
    I've thought of using an adapter to implement empty methods but a) I'm not sure that makes sense and b) I still end up have to return something. Another option was maybe having multiple interfaces, one returning a single object and the other returning an array. Neither of those options felt right and looked a bit goofy when I prototyped them out. It seems to me that I wouldn't want the classes using the concrete DAO classes to be able to call the wrong method, but I don't know how to hide the unused method. Right now I just return an empty Object or Object[] for the unused method but that seems goofy too, and makes the class using ClassOne or ClassTwo know the innards of the implementations.
    Anyway, any tips appreciated.
    Thanks,
    Pablo

    It sounds as if the methods weren't meant to be together, and so I'm wondering if you aren't better off with two distinct interfaces, one for each method. Otherwise one solution would be to implement a method that throws an exception if it is not meant to be called.
    edit: D'oh! Just when you least expect them, Ninjas! They're everywhere!
    Edited by: Encephalopathic on Apr 30, 2009 1:41 PM

  • Method declaration problem

    Hi,
    I'm trying to write a class that lets the user enter the values for some parameters all of which are Floats.
    I have get and set methods for each parameter.
    example of some code:
    public class Parameters
           private Float loat affinityThresholdScalar;
            public InitialiseParams(Float aT)
                  affinityThresholdScalar = aT;
         public void setAffinityThresholdScalar(Float aT)
                  affinityThresholdScalar = aT;
           public Float getAffinityThresholdScalar()
                  return affinityThresholdScalar;
    }The error i'm getting is:
    invalid method declaration; return type required
    public InitialiseParams(Float aT,Float cR,Float hR,Float k,Float s,Float sV,Float tR)
    can anybody help?
    Thanks

    The error i'm getting is:
    invalid method declaration; return type required
    public InitialiseParams(Float aT,Float
    aT,Float cR,Float hR,Float k,Float s,Float sV,Float tR)
    can anybody help?Yup: read the error diagnostic: the compiler found a method 'InitialiseParams',
    but it didn't find the return type of that method (because you didn't supply any).
    Even methods that return nothing, return 'void', so you should simply
    alter the method definition to:public void InitialiseParams(Float aT) {
          affinityThresholdScalar = aT;
    }kind regards,
    Jos

  • Jcombobox: additem does not work! "invalid method decl."

    hi all.
    i have a gui with a jComboBox. but when i try to add an item with addItem() the compiler tells me
    invalid method declaration; return type required
    whats the problem here?? :(
    JComboBox jComboBox1 = new JComboBox();
    jComboBox1.addItem("xyz");
    thanks for help.

    I'd bet the problem is not in these 2 lines of code. Maybe you have a method that has no return type specified(as the compiler already said). Check if you have spelled the names of the constructors of your class properly and the orher methods too. An example could be
    private fillCombo(){
    must be
    private void fillCombo()...Mike

  • How to add User defined return type in service interface of AppModule

    HI All,
    I am creating service interface using AppModule. Added custom method with Java primitives and working fine. Now i want to added custom method with return type is EMP object means user defined object. How can i do so?
    Thanks in advance.

    I looked it up in the mean time ...
    The docs state that you only can use simple data type or java.util.list or AttributeList (which is a wrapper for any viewRow). So I guess you have to somehow flatten your complex data type or create a custom VO which holds it.
    http://download.oracle.com/docs/cd/E12839_01/web.1111/b31974/bcextservices.htm#CJAEHFJD
    Scroll down to 11.2.3
    Timo

  • Two methods with same name but different return type?

    Can I have two methods with same name but different return type in Java? I used to do this in C++ (method overloading or function overloading)
    Here is my code:
    import java.io.*;
    public class Test{
    public static void main(String ar[]){
    try{          
    //I give an invalid file name to throw IO error.
    File file = new File("c:/invalid file name becasue of spaces");
    FileWriter writer = new FileWriter(file ,true);
    writer.write("Test");
    writer.close();     
    } catch (IOException IOe){
         System.out.println("Failure");
    //call first method - displays stack trace on screen
         showerr(NPe);
    //call second method - returns stack trace as string
            String msg = showerr(NPe);
            System.out.println(msg);
    } // end of main
    public static void showerr(Exception e){
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
         e.printStackTrace(pw);
         try{
         pw.close();
         sw.close();
         catch (IOException IOe){
         IOe.printStackTrace();     
         String stackTrace = sw.toString();
         System.out.println("Null Ptr\n" +  stackTrace );
    }//end of first showerr
    public static String showerr(Exception e){
         StringWriter sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
         e.printStackTrace(pw);
         try{
         pw.close();
         sw.close();
         catch (IOException IOe){
         IOe.printStackTrace();     
         return sw.toString();
    }//end of second showerr
    } // end of class
    [\code]

    Overloading is when you have multiple methods that have the same name and the same return type but take different parameters. See example
    public class Overloader {
         public String buildError(Exception e){
              java.util.Date now = new java.util.Date() ;
              java.text.DateFormat format = java.text.DateFormat.getInstance() ;
              StringBuffer buffer = new StringBuffer() ;
              buffer.append(format.format(now))
                   .append( " : " )
                   .append( e.getClass().getName() )
                   .append( " : " )
                   .append( e.getMessage() ) ;
              return buffer.toString() ;
         public String buildError(String msg){
              java.util.Date now = new java.util.Date() ;
              java.text.DateFormat format = java.text.DateFormat.getInstance() ;
              StringBuffer buffer = new StringBuffer() ;
              buffer.append(format.format(now))
                   .append( " : " )
                   .append( msg ) ;
              return buffer.toString() ;
         public String buildErrors(int errCount){
              java.util.Date now = new java.util.Date() ;
              java.text.DateFormat format = java.text.DateFormat.getInstance() ;
              StringBuffer buffer = new StringBuffer() ;
              buffer.append(format.format(now))
                   .append( " : " )
                   .append( "There have been " )
                   .append( errCount )
                   .append( " errors encountered.")  ;
              return buffer.toString() ;
    }Make sense ???
    Regards,

  • Error 136 Functions that can be compossed must declare a return type

    Hello,
    I have downloaded the EF Final Release driver and Im working with Oracle 11g express.
    I have the following Procedure:
    PROCEDURE ProductosPedido(
    Datos Out SYS_RefCursor) IS
    BEGIN
    OPEN Datos FOR
    SELECT Nombre,
    TO_NUMBER(Precio * (SELECT SUM(unidades)
    FROM DETALLES_PEDIDO
    WHERE PRODUCTO = PRODUCTO.ID)) Importe
    FROM PRODUCTO;
    END;
    And the following config section:
    <oracle.dataaccess.client>
    <settings>
    <add name="System.Productospedido.RefCursor.Datos" value="implicitRefCursor bindinfo='mode=Output'"/>
    <add name="System.Productospedido.RefCursorMetaData.Datos.Column.0" value="implicitRefCursor metadata='ColumnName=Nombre;BaseColumnName=Nombre;BaseSchemaName=System;BaseTableName=Producto;NativeDataType=nvarchar2;ProviderType=NVarchar2;DataType=System.String;ColumnSize=50;AllowDBNull=true;IsKey=false'" />
    <add name="System.Productospedido.RefCursorMetaData.Datos.Column.1" value="implicitRefCursor metadata='ColumnName=Importe;NativeDataType=number;ProviderType=Decimal;DataType=System.Decimal;AllowDBNull=false;IsKey=false;ColumnSize=8'" />
    </settings>
    </oracle.dataaccess.client>
    I have imported succesfully in my EF Model, but when I try to consume the Procedure it gives me Error 136 Functions that can be compossed must declare a return type
    Any solutions?
    Thanks and best regards!

    A stored procedure does not have a ReturnType, therefore IsComposable="false" and it cannot be used in LINQ queries.
    This limitation is imposed by EF and not by ODP.
    You may want to create a stored function which has a ReturnType ref cursor, and include this stored function into your model. Then, under the same namespace, you create a class with a "stub" method/function and use EdmFunction() to map this stub to the stored function. For example,
    class myFuncClass
    [EdmFunction("Model.Store", "MY_STORED_FUNC_1")]
    public static <your_complex_type_or_DbDataRecord> MyFunc_1(int? column1, ...)
    throw new NotSupportedException("Direct calls are not supported");
    You should be able to call myFuncClass.MyFunc_1(x) in your LINQ query. Your stored function MY_STORED_FUNC_1 will be called in the generated query.

  • Rmic and "contains an invalid return type."

    Hello,
    since two days, rmic does not compile anymore. rmic is called via an Ant job like this:
    <javac srcdir="${src}" destdir="${bin}" depend="true">
    </javac>
    <rmic base="${bin}" includes="../**/*.class" iiop="true" idl="true">
    </rmic>
    And I get errors like
    [rmic] error: Class Session contains an invalid return type.
    in the Eclipse output console. On the other hand, the Session interface looks like this:
    public interface Session extends Remote {
    public Enumeration enumerateLocks() throws RemoteException;
    [more Methods]
    (yes, all methods throw RemoteException)
    If I comment out all methods of Session, other messages appear, such as:
    [rmic] error: Class ....AccessService contains an invalid argument type in method findSession.
    [rmic] error: Class Loader contains an invalid return type.
    [rmic] error: Class ....Service contains an invalid argument type in method init.
    All classes compile fine with both Jikes and the Eclipse compiler.
    Thanks for any help,
    Johann

    Sorry, even if I comment out Enumeration, rmic will not compile the classes. To me it looks like something in the interface for Session is wrong, but I dont know what it is...
    public interface Session extends Remote {
    public Unique sessionID() throws RemoteException;
    public long sessionCreated() throws RemoteException;
    public long sessionDestroyed() throws RemoteException;
    public void destroySession() throws RemoteException;
    public int actionsPerformed() throws RemoteException;
    public Enumeration enumerateActions() throws RemoteException;
    public Lock createLock(Reference ref) throws RemoteException, LockedException;
    public Lock createLock(Reference ref, long milliseconds)
    throws RemoteException, LockedException;
    public void releaseAllLocks() throws RemoteException;
    public Enumeration enumerateLocks() throws RemoteException;
    public boolean isDestroyed() throws RemoteException;
    If I comment out all methods in Session, I can compile Session with rmic, but other errors appear:
    [rmic] error: Class ...AccessService contains an invalid argument type in method isValidSession.
    [rmic] error: Class Loader contains an invalid return type.
    [rmic] error: Class ...Service contains an invalid argument type in method init.

  • Have an object as return type in a method in the WebDynproComponent

    Hello together.
    I've wrote an EJB in which is a method that read out a DB Table XYZ. In this EJB also are methods to search a single entry.
    In my WebDynpro applixcation i have a method in the Component that access the EJB and retrive the single entry for example. In the View implemantation i call the method from the "WEbDynPro component" which have a string as return type.
    Is it possible to have an object as return type?
    public java.lang.String sr( int KVNR )
        //@@begin sr()
        KVNummerDTO kvnrObject = new KVNummerDTO();
        String Kasse = "";
          try
              KVNRSessionLocal kVNummerSessionLocal = kVNRSessionLocalHome.create();
              kvnrObject = kVNummerSessionLocal.getKVNummer(KVNR);
              Kasse = kvnrObject.getKasse();
          catch (Exception e)
               e.printStackTrace();
               wdComponentAPI.getMessageManager().reportException(e.getMessage(), true);
          return Kasse;
        //@@end
    I want to return kvnrObject  and not only a string!

    Hello Micheal,
    While Creating a method in front of the return type click on the browse and select Java Native Type Radio Button and again click on the browse button available there. Type the name of the class in the class in it and you can select the return type. If it is a user made class then first the required Java files under the path Resources>src>packages><create a folder>java file. Then build the project so that the class name is visible in list while selecting the return type.
    Regards,
    Ardhendu

  • Guideline for deciding method return type

    Hi All,
    I have some concerns in deciding the return type of some specific methods in the application (web service application to be specific).
    Concern: There are methods like 'deleteData', 'cancelProcess', 'uploadData' etc. Ideally these methods don't require server to perform complex business logic. Now there are 2 views to decide the return type of these methods. The first approach could be to return a boolean indicating whether the operation is successful or not and the other apporach is to return void but throw an exception if anything goes wrong.
    Both approaches have their own advantages and drawbacks. Sending a boolean seems to be cleaner but in case of unsuccess caller won't get the exact exception but just a flag. In second apporach, the caller has to rely on try/catch to decide the logical flow.
    I know, there can't be any generic answer to this question but I just wanted to know comments from experts on this or probably some guidelines.
    Thanks and Regards,
    Ashish Arya

    If there is a legitimate reason why your method might not actually do what it should, then use the boolean return value.
    Example: someList.remove("foo") will return false if "foo" is not actually in the list (because remove() simply specifies that it will make sure that the element is not in the list after the call. Since this is fulfilled in this case, there's no case to throw an exception, even if it didn't actually remove anything).
    If the only reason for not doing what it should is some error condition, then throw an exception:
    Example: someList.get(100) will throw an exception, when the list has less than 101 elements.

  • Dynamic return types? (public T extends E Vector T method(T param)

    Is it possible to have a method that returns Vector<MyType extends MyBaseType> dynamically? So that I could call the method using something like
    Vector<MyType> test1 = method(new MyType());
    as well as
    Vector<MyBaseType> test2 = method(new MyBaseType());
    For the first call, method would do something like
    Vector<MyType> retval = new Vector<MyType>();
    MyType c1 = new MyType();
    retval.add(c1);
    and for the second call
    Vector<MyBaseType> retval = new Vector<MyBaseType>();
    MyBaseType c1 = new MyBaseType();
    retval.add(c1);
    The best I've managed to come up with after going through various online sources (the most helpful being Gilad Bracha's generics tutorial) was
    public <T extends MyBaseType> Vector<T> test(T param)
    Class<T> entry2 = (Class<T>) param.getClass();
    Vector<T> retval = new Vector<T>();
    retval.add(entry2);
    return retval;
    But that doesn't even compile.
    I could also live having to specify an instance of Vector<T> (e.g. Vector<MyType>) as method parameter (but I'd still need to be able to instantiate objects of MyType in the method body and add those to the vector.

    >
    Hi there: in the future, please highlight your code and click the CODE button in the editor to format your code properly.
    You're close with your attempt. You can fix it by doing this:
       public <T extends MyBaseType> Vector<T> test(T param)
             throws IllegalAccessException, InstantiationException {
          Class<T> entry2 = (Class<T>) param.getClass();
          Vector<T> retval = new Vector<T>();
          retval.add(entry2.newInstance());
          return retval;
       }But you're better off, if possible, to do something like this:
       public <T extends MyBaseType> Vector<T> test(Class<T> type)
             throws IllegalAccessException, InstantiationException {
          Vector<T> retval = new Vector<T>();
          retval.add(type.newInstance());
          return retval;
       }This assumes you were just passing "param" to tell the method the type to use. If the parameter you're passing is what you actually want to add to the vector, it's really simple:
       public <T extends MyBaseType> Vector<T> test(T param) {
          Vector<T> retval = new Vector<T>();
          retval.add(param);
          return retval;
    Edit: Rereading your original post, it looks like yes, you need to create the instance in the method itself. So the second snippit is the one you want. Remember that this would require the type to have a visible, no-argument constructor.
    Edited by: endasil on 19-Oct-2009 11:16 AM

  • Defining enum with abstract method which returns a generic type

    Is it possible to define an abstract method which returns an geneic type like below? Thanks
    public enum Type{
         A{
              public List<Integer> getData(){}
         B{
              public Set<String> getData{}
         abstract<T> T getData();
    }

    vulee wrote:
    Why not?
    List<Integer> lst = Type.A.getData();Wonder, which compiler you use. Can't be Java6:
    # javac Enums.java
    Enums.java:23: incompatible types
    found   : java.util.Collection<capture#376 of ?>
    required: java.util.List<java.lang.Integer>
                    List<Integer> data = Type.A.getData();
                                                       ^
    1 errorEdit: Unless you do it the generic way as you proposed, which actually is a phoney. Because of the T being a generic method parameter, the compiler will infer it from the type of the variable it gets assigned to. Hence, both of the following will compile:
    List<Integer> lst = Type.A.getData();
    Set<String> lst2 = Type.A.getData(); // Runtime exceptionActually, javac is telling you that giving warnings on the enum constants redefined method return types.
    Edited by: stefan.schulz on Sep 10, 2008 11:38 PM

Maybe you are looking for