"_main", referenced from:

im trying to migrate my project from windows to mac , when i use xcode to compile my code , i get the following error
Undefined symbols:
"_main", referenced from:
start in crt1.10.5.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
please help

The short answer to your question is that the entry point to a Windows app is named 'WinMain', while the entry point to an OS X app is named 'main'. The linker message you reported just means that no main function was found, which is to be expected.
Of course you can't simply change the name of WinMain to main, since everything from the parameters to the API calls are going to be entirely different. If your Windows app is built on one of the libraries intended for an OS X port, a lot of the problems may be solved for you. Otherwise I think it's safe to say that the changes to WinMain are going to be the very least of your challenges.
Have you decided on whether to port to Carbon or Cocao? The choice might depend on whether your Windows program is written in "C" with direct calls to the Win32 API or written in C++ using MFC. I wish I could be of more help, but I've never moved a Windows program to OS X without a complete re-write.
All the very best of luck!!

Similar Messages

  • Undefined symbols: "_NewSpeechChannel", referenced from...

    Hello.
    I'm an absolute beginner in developing for OSX and C programming in general.
    I'm following the instructions step-by-step to writing a very simple program that makes use of the OSX Speech Synthesizer.
    However the program won't compile and instead it lanuches this error:
    >  Undefined symbols:
    >    "_NewSpeechChannel", referenced from:
    > >    _main in ccRRVBTR.o
    >  ld: symbol(s) not found
    >  collect2: ld returned 1 exit status
    I'm aware that the problem arises from the lack of proper linking to the actual implementation of the NewSpeechChannel function.
    However it is a system function and I guess it should be linked by default. In any case, what should I do next to make it compile properly?
    The simple program is this (so far):
    #include<stdio.h>
    #include<ApplicationServices/ApplicationServices.h>
    int main(int argc, char **argv, char **envp, char **apple) {
    SpeechChannel speechchannel;
    NewSpeechChannel( NULL, &speechchannel );
    The reference of the Speech Synthesis Manager (the C API for speech synthesis) sits here:
    https://developer.apple.com/library/mac/#documentation/Carbon/Reference/Speech_S ynthesis_Manager/Reference/reference.html
    None of the functions listed in the reference compile, along with NewSpeechChannel.
    I know it is a very basic question by any help is welcome, as I'm stuck at the very beginning of my project.
    Thanks!
    PS: I tried it on both OS X 10.6.8 and 10.7.5

    Add the Application  Services framework to your project.

  • _OBJC_IVAR_$_        Referenced From Error while trying to deploy in iphone

    Hi All,
    I am facing one problem. any one who are aware of this project please help me.
    My problem is:
    i have Mac OS of 10.5.8 and xcode of 3.1.4
    while i am trying to implement a application of audio files i want the frame work called "AVFoundation.Framework" i didn't found that frame work in my library.
    so i added that framework from "MACOS10.4" .
    but in simulator 3.1 it works fine. while trying to deploy in my iphone i am getting error like:
    "-(avTouchcontroller updatecurrenttime)", referenced from:
    _OBJC_IVAR_$_ avTouchcontroller._ivlmeter_in in avTouchController.o

    Why don't you post here (again) and you might get some answers:
    http://discussions.apple.com/message.jspa?messageID=10512489#10512489

  • ORA-30937 when validating element referenced from included schema

    I've boiled my latest problem down to a simple test case. Basically it seems as though the included schema is the problem, but I can't figure out why:
    begin
    dbms_xmlschema.deleteSchema('http://www.forensic.gov.uk/eMessages/Pnclink/NDNA/testinclude.xsd', dbms_xmlschema.DELETE_CASCADE_FORCE);
    dbms_xmlschema.registerSchema('http://www.forensic.gov.uk/eMessages/Pnclink/NDNA/testinclude.xsd',
    '<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified" versionfiltered="1-00" id="NDNASimpleTypes">
    <xsd:complexType name="MessageHeaderType">
    <xsd:sequence>
    <xsd:element name="MESSAGE_NUMBER" type="xsd:long"/>
    <xsd:element name="MESSAGE_TYPE" type="MessageTypeType"/>
    <xsd:element name="MESSAGE_DATE" type="xsd:dateTime"/>
    </xsd:sequence>
    </xsd:complexType>
    <xsd:simpleType name="MessageTypeType">
    <xsd:annotation>
    <xsd:documentation>The definition of the Sample Message Types</xsd:documentation>
    </xsd:annotation>
    <xsd:restriction base="xsd:string">
    <xsd:maxLength value="2"/>
    <xsd:enumeration value="CT"/>
    <xsd:enumeration value="CA"/>
    <xsd:enumeration value="CD"/>
    </xsd:restriction>
    </xsd:simpleType>
    </xsd:schema>',TRUE,FALSE,FALSE,FALSE);
    dbms_xmlschema.deleteSchema('http://www.forensic.gov.uk/eMessages/Pnclink/NDNA/Test.xsd', dbms_xmlschema.DELETE_CASCADE);
    dbms_xmlschema.registerSchema('http://www.forensic.gov.uk/eMessages/Pnclink/NDNA/Test.xsd',
    '<xsd:schema xmlns="http://www.forensic.gov.uk/eMessages/Pnclink/NDNA" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.forensic.gov.uk/eMessages/Pnclink/NDNA" elementFormDefault="qualified" attributeFormDefault="unqualified" versionfiltered="1.0" id="Test">
    <xsd:include schemaLocation="http://www.forensic.gov.uk/eMessages/Pnclink/NDNA/testinclude.xsd"/>
    <xsd:element name="SAMPLE_MESSAGE">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element name="MESSAGE_HEADER" type="MessageHeaderType"/>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    </xsd:schema>',TRUE,TRUE,FALSE,FALSE);
    END;
    update xml_in
    set xml_data = xmltype ( '<?xml versionfiltered="1.0" encoding="UTF-8"?>
    <!--Sample XML file generated by XMLSpy v2005 rel. 3 U (http://www.altova.com)-->
    <SAMPLE_MESSAGE xmlns="http://www.forensic.gov.uk/eMessages/Pnclink/NDNA" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.forensic.gov.uk/eMessages/Pnclink/NDNA http://www.forensic.gov.uk/eMessages/Pnclink/NDNA/Test.xsd">
    <MESSAGE_HEADER>
    <MESSAGE_NUMBER>2147483647</MESSAGE_NUMBER>
    <MESSAGE_TYPE>CT</MESSAGE_TYPE>
    <MESSAGE_DATE>2001-12-17T09:30:47</MESSAGE_DATE>
    </MESSAGE_HEADER>
    </SAMPLE_MESSAGE>
    where msg_id = 8
    and I get the error:
    ORA-30937: No schema definition for 'MESSAGE_NUMBER' (namespace 'http://www.forensic.gov.uk/eMessages/Pnclink/NDNA') in parent 'MESSAGE_HEADER'
    ORA-06512: at "SYS.XMLTYPE", line 0
    ORA-06512: at line 27
    But if I remove the MESSAGE_NUMBER I get
    ORA-31154: invalid XML document
    ORA-19202: Error occurred in XML processing
    LSX-00213: only 0 occurrences of particle "MESSAGE_NUMBER", minimum is 1
    ORA-06512: at "SYS.XMLTYPE", line 0
    ORA-06512: at line 37
    So it knows there is supposed to be a particle called message_number if it's not there, but not what to do with it if it is.
    One other thing, which I think is significant: If I amend my test.xsd schema so I define MESSAGE_HEADER there, so the only thing being referenced from testinclude.xsd is the SIMPLE type "MessageTypeType", I don't have a problem. It seems to be only when I include COMPLEX types.
    Any suggestions?

    Dave
    I can't register the XML Schemas with XML DB, since we do think versionfiltered is a valid attribute for a schema element...
    SQL> declare
      2    res boolean;
      3    xmlSchema xmlType := xmlType(
      4  '<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified" versionfilt
    ered="1-00" id="NDNASimpleTypes">
      5
      6          <xsd:complexType name="MessageHeaderType">
      7                  <xsd:sequence>
      8                          <xsd:element name="MESSAGE_NUMBER" type="xsd:long"/>
      9                          <xsd:element name="MESSAGE_TYPE" type="MessageTypeType"/>
    10                          <xsd:element name="MESSAGE_DATE" type="xsd:dateTime"/>
    11                  </xsd:sequence>
    12          </xsd:complexType>
    13          <xsd:simpleType name="MessageTypeType">
    14                  <xsd:annotation>
    15                          <xsd:documentation>The definition of the Sample Message Types</xsd:documentation>
    16                  </xsd:annotation>
    17                  <xsd:restriction base="xsd:string">
    18                          <xsd:maxLength value="2"/>
    19                          <xsd:enumeration value="CT"/>
    20                          <xsd:enumeration value="CA"/>
    21                          <xsd:enumeration value="CD"/>
    22                  </xsd:restriction>
    23          </xsd:simpleType>
    24  </xsd:schema>');
    25  begin
    26    if (dbms_xdb.existsResource(:schemaPath)) then
    27      dbms_xdb.deleteResource(:schemaPath);
    28    end if;
    29    res := dbms_xdb.createResource(:schemaPath,xmlSchema);
    30  end;
    31  /
    Queuing DELETE Event
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.04
    SQL> begin
      2    dbms_xmlschema.registerSchema
      3    (
      4      :schemaURL,
      5      xdbURIType(:schemaPath).getClob(),
      6      TRUE,TRUE,FALSE,TRUE
      7    );
      8  end;
      9  /
    begin
    ERROR at line 1:
    ORA-30937: No schema definition for 'versionfiltered' (namespace '##local') in parent '/schema'
    ORA-06512: at "XDB.DBMS_XMLSCHEMA_INT", line 20
    ORA-06512: at "XDB.DBMS_XMLSCHEMA", line 31
    ORA-06512: at line 2XMLSPY agrees with us on this...
    If I change version filtered to version I get
    SQL> var schemaURL varchar2(256)
    SQL> var schemaPath varchar2(256)
    SQL> --
    SQL> begin
      2    :schemaURL := 'http://www.forensic.gov.uk/eMessages/Pnclink/NDNA/testinclude.xsd';
      3    :schemaPath := '/public/testinclude.xsd';
      4  end;
      5  /
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.00
    SQL> call dbms_xmlSchema.deleteSchema(:schemaURL,4)
      2  /
    Queuing DELETE Event
    Call completed.
    Elapsed: 00:00:00.07
    SQL> declare
      2    res boolean;
      3    xmlSchema xmlType := xmlType(
      4  '<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified" version="1-
    00" id="NDNASimpleTypes">
      5
      6          <xsd:complexType name="MessageHeaderType">
      7                  <xsd:sequence>
      8                          <xsd:element name="MESSAGE_NUMBER" type="xsd:long"/>
      9                          <xsd:element name="MESSAGE_TYPE" type="MessageTypeType"/>
    10                          <xsd:element name="MESSAGE_DATE" type="xsd:dateTime"/>
    11                  </xsd:sequence>
    12          </xsd:complexType>
    13          <xsd:simpleType name="MessageTypeType">
    14                  <xsd:annotation>
    15                          <xsd:documentation>The definition of the Sample Message Types</xsd:documentation>
    16                  </xsd:annotation>
    17                  <xsd:restriction base="xsd:string">
    18                          <xsd:maxLength value="2"/>
    19                          <xsd:enumeration value="CT"/>
    20                          <xsd:enumeration value="CA"/>
    21                          <xsd:enumeration value="CD"/>
    22                  </xsd:restriction>
    23          </xsd:simpleType>
    24  </xsd:schema>');
    25  begin
    26    if (dbms_xdb.existsResource(:schemaPath)) then
    27      dbms_xdb.deleteResource(:schemaPath);
    28    end if;
    29    res := dbms_xdb.createResource(:schemaPath,xmlSchema);
    30  end;
    31  /
    Queuing DELETE Event
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.04
    SQL> begin
      2    dbms_xmlschema.registerSchema
      3    (
      4      :schemaURL,
      5      xdbURIType(:schemaPath).getClob(),
      6      TRUE,TRUE,FALSE,TRUE
      7    );
      8  end;
      9  /
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.20
    SQL> begin
      2    :schemaURL := 'http://www.forensic.gov.uk/eMessages/Pnclink/NDNA/Test.xsd';
      3    :schemaPath := '/public/Test.xsd';
      4  end;
      5  /
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.01
    SQL> call dbms_xmlSchema.deleteSchema(:schemaURL,4)
      2  /
    Queuing DELETE Event
    Call completed.
    Elapsed: 00:00:00.06
    SQL> declare
      2    res boolean;
      3    xmlSchema xmlType := xmlType(
      4  '<xsd:schema xmlns="http://www.forensic.gov.uk/eMessages/Pnclink/NDNA" xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="ht
    tp://www.forensic.gov.uk/eMessages/Pnclink/NDNA" elementFormDefault="qualified" attributeFormDefault="unqualified" version="1.0" id="Test">
      5
      6          <xsd:include schemaLocation="http://www.forensic.gov.uk/eMessages/Pnclink/NDNA/testinclude.xsd"/>
      7        <xsd:element name="SAMPLE_MESSAGE">
      8                  <xsd:complexType>
      9                          <xsd:sequence>
    10                                  <xsd:element name="MESSAGE_HEADER" type="MessageHeaderType"/>
    11                          </xsd:sequence>
    12                  </xsd:complexType>
    13          </xsd:element>
    14    </xsd:schema>');
    15  begin
    16    if (dbms_xdb.existsResource(:schemaPath)) then
    17      dbms_xdb.deleteResource(:schemaPath);
    18    end if;
    19    res := dbms_xdb.createResource(:schemaPath,xmlSchema);
    20  end;
    21  /
    Queuing DELETE Event
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.04
    SQL> begin
      2    dbms_xmlschema.registerSchema
      3    (
      4      :schemaURL,
      5      xdbURIType(:schemaPath).getClob(),
      6      TRUE,TRUE,FALSE,FALSE
      7    );
      8  end;
      9  /
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.14
    SQL> var xmltext varchar2(4000)
    SQL> --
    SQL> begin
      2    :xmltext :=
      3  '<SAMPLE_MESSAGE xmlns="http://www.forensic.gov.uk/eMessages/Pnclink/NDNA" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:sc
    hemaLocation="http://www.forensic.gov.uk/eMessages/Pnclink/NDNA http://www.forensic.gov.uk/eMessages/Pnclink/NDNA/Test.xsd">
      4     <MESSAGE_HEADER>
      5        <MESSAGE_NUMBER>2147483647</MESSAGE_NUMBER>
      6        <MESSAGE_TYPE>CT</MESSAGE_TYPE>
      7        <MESSAGE_DATE>2001-12-17T09:30:47</MESSAGE_DATE>
      8     </MESSAGE_HEADER>
      9  </SAMPLE_MESSAGE>';
    10  end;
    11  /
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.01
    SQL> drop table xml_in
      2  /
    Table dropped.
    Elapsed: 00:00:00.04
    SQL> create table xml_in
      2  (
      3    msg_id   number(4),
      4    xml_data xmltype
      5  )
      6  /
    Table created.
    Elapsed: 00:00:00.03
    SQL> insert into xml_in values ( 8, xmltype ('<FOO/>'))
      2  /
    1 row created.
    Elapsed: 00:00:00.01
    SQL> declare
      2    xmldata xmltype;
      3  begin
      4    xmldata := xmltype(:xmltext);
      5    xmldata.schemaValidate();
      6  end;
      7  /
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.09
    SQL> update xml_in
      2     set xml_data = xmltype ( :xmltext )
      3   where msg_id = 8
      4  /
    1 row updated.
    Elapsed: 00:00:00.01
    SQL> select * from xml_in
      2  /
        MSG_ID
    XML_DATA
             8
    <SAMPLE_MESSAGE xmlns="http://www.forensic.gov.uk/eMessages/Pnclink/NDNA" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLo
    cation="ht
    tp://www.forensic.gov.uk/eMessages/Pnclink/NDNA http://www.forensic.gov.uk/eMessages/Pnclink/NDNA/Test.xsd">
      <MESSAGE_HEADER>
        <MESSAGE_NUMBER>2147483647</MESSAGE_NUMBER>
        <MESSAGE_TYPE>CT</MESSAGE_TYPE>
        <MESSAGE_DATE>2001-12-17T09:30:47</MESSAGE_DATE>
      </MESSAGE_HEADER>
    </SAMPLE_MESSAGE>
    Elapsed: 00:00:00.06
    SQL>

  • Another question: non-static variable super cannot be referenced from ...?

    class a
    int i;     
    int j=2;
    a(int i)
    this.i=i;
    public class b extends a
         b()
         super(8);     
    public static void main(String args[])
    b test=new b();
    System.out.print(test.i);
    test.j=1;
    System.out.print("test.j="+test.j);
    System.out.print("super.j="+super.j);
    b.java:28: non-static variable super cannot be referenced from a static context
    System.out.print("super.j="+super.j);
    ^
    1 error
    thanks

    You cannot call "super" from a static context. Just like you can't use "this" or call any non-static methods in a static context.
    Try with test.super.j, although I'm not sure if it works. But you can call super.j in a non-static context, e.g. in your constructor, or in a non-static method.

  • "non-static variable cannot be referenced from a static contex"

    Hi, i'm writing a booking program at school and i'm getting 27 "non-static variable cannot be referenced from a static contex" errors. I can't find anything wrong with the code so I'm just asking you guys to look it through..
    public class bokningsmeny
    Bokning[] bokningslista = new Bokning[1000];
    String fornamn;
    String efternamn;
    String civilstand;
    String adress;
    String personnr;
    String telefonnr;
    int regnr;
    double inkomst;
    public static void main(String[] args)
    for(;;)
    System.out.println("\nMeny");
    System.out.println("________\n");
    System.out.println("1. Mata in nya personer.");
    System.out.println("2. S&ouml;k personen via personnummer och skriv personens andra uppgifter.");
    System.out.println("3. S&ouml;k personen via efternamn och skriv personens andra uppgifter.");
    System.out.println("4. S&ouml;k personen via personnummer och &auml;ndra adress.");
    System.out.println("5. S&ouml;k personen via personnummer och &auml;ndra telefonnummer.");
    System.out.println("6. S&ouml;k personen via personnummer och &auml;ndra civilst&aring;nd.");
    System.out.println("7. S&ouml;k personen vis personnummer och &auml;ndra inkomst");
    System.out.println("8. Skriv ut alla personer med givet namn.");
    System.out.println("9. Skriv ut alla personer med givet efternamn");
    System.out.println("10. Skriv ut alla personer med given adress");
    System.out.println("11. Skriv ut hela listan");
    System.out.println("12. Avsluta\n");
    int menyval = Keyboard.readInt();
    System.out.println("\n");
    switch(menyval)
    case 1:
    System.out.println("Mata in nya personer.\n______________________\n");
    boolean BOOuppgifter = false;
    for(int i = 0; i <= 1000; i++)
    if(bokningslista +== null)+
    +{+
    +SkrivInUppgifter();+
    +System.out.println("\nSt&auml;mmer informationen? (Y/N)");+
    +boolean BOOcase1yesorno = IsInputCorrect();+
    +if(BOOcase1yesorno == true)+
    +{+
    +System.out.println("\nBokningen lyckades!\n");+
    +bokningslista += new Bokning(fornamn, efternamn, civilstand, adress, personnr, telefonnr, regnr, inkomst);
    ++++else if(BOOcase1yesorno == false
    ++++System.out.println("\nBokningen avbruten.\n")
    ++++break
    ++++++break
    ++++case 2
    ++++System.out.println("Sok person med personnummer och &auml;ndra uppgifter.")
    ++System.out.println("___________________________________________________________\n")
    ++System.out.print("Skriv in sokord: ")
    ++String query = Keyboard.readString()
    ++query = query.toUpperCase()
    ++String personnummersok
    ++boolean contains
    ++int antal = 0
    ++boolean BOOcase2result = false
    ++System.out.println("Resultat: \n_________\n")
    ++for(int i = 0; i < 1000; i++
    ++++if(bokningslista +!<b<br />+<em<b<br />+++personnummersok = (bokningslista+.hamtaPersonnum()).t
    ++++contains = personnummersok.con
    ++++if(cont
    +<<br />++++BOOcase2r
    ++++ant
    ++++fornamn = bokningslist
    +++++efternamn = boknin
    ++++++personnr
    +++++++System.out.println(antal + ". " + fornam
    ++++<e<br />+++++++System.out.pri<br<br />+++++<em<br />+++++++System.out.println("\nVilket sokresultat vill du v&bdquo
    ++++<<br />+++++++if(case2ch
    +++++++System.ou
    +++<e<<br />+++<em<br />++++
    ++<em<br />+++++++System.out.p
    +++++<e<br />+++<<br<br /<br />+++++++System.out.printl
    +++<em<br />+++++<em<br />++
    <e<br />++++++++Sy
    +++++
    ++++++<e<br /><em<br />++++++++<<br />+++++<e<br />+++
    +++<<br />+++++++++else if(case11exit != 'y' &<br<br />+<<br />++++
    ++++
    +++++
    ++++<e<br />+++++++
    ++++<em<br />+++++
    +++<em<br />+++++<em<br />++++<<br />++++++
    ++++<e<br />+++++++<e<br />++<em<br />++++<e<br />+++<<br />+++++++++System.out.println("\n\nNamn: " + fornamn + "
    ++++++++++ "\nHemadress: " + adr
    ++++++++++ telefon
    +<<br />+++++++++Syste
    ++++<em<br />+++++++++if(correct
    <em<br />++<em<br />++<<br />++++<e<br /><<<br /><e<br />+++++++++I have another file with the Bokning.java class in it but I know for sure that its error free. Notice that I'm not nearly done with the program, theres like 10 more 'cases' to be created but I dont w
    ++<em</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Your code goes "+" crazy there, but here is your problem:
    public class B extends A {
        public void method() {}
        public static void main(String[] args) {
            //method(); //non-static method method() cannot be referenced from a static context
            B b = new B();
            b.method();
    }You need to be clear about the difference between static methods and non-static (instance) methods. Instance methods are applied to objects.

  • Non-static variable total cannot be referenced from a static context

    i am trying to write a program that uses the if-else statements and when i wrote my program i got "non-static variable total cannot be referenced from a static context" for three lines of my input.
    A:\Disks.java:20: non-static variable total cannot be referenced from a static context total = (10000 * .95 + ((diskCount - 10000) * .85));
    ^
    A:\Disks.java:22: non-static variable total cannot be referenced from a static context total = (diskCount * .95);
    ^
    A:\Disks.java:24: non-static variable total cannot be referenced from a static context System.out.print(total);
    ^
    Do you know what I did wrong?

    I apologise in advance for the general tone of this reply.....
    Ummm, let me think for a second... You referenced a non static
    variable from a static context. Yup, yup. That's it !
    If you can't figure this out, you really need to do a Java tutorial or
    buy a text book. Basically though, total is a member of some class
    and you are trying to use it from a static function. I bet you have
    something like:
    public class Test {
        public int total;
        // blah blah blah
        public static void main(String[] args) {
            // This won't work cos "total" is a member and we are static
            System.out.println(total);
            // This works cos now you have an instance to pull total
            // out of.
            Test t = new Total();
            System.out.println(t.total);
    }

  • Non-static variable aceYears cannot be referenced from a static context

    This is my error...
    investment.java:53: non-static variable aceYears cannot be referenced from a static context
    lwInvest.numberAceYears(aceYears);
    ^
    This is my code...
    public static void main (String[] args)
    investment.Invest.numberAceYears(aceYears);
    and more code
    String termInvested = JOptionPane.showInputDialog
    ("Please enter the amount of years to invest your investment.");
    int intTermInvested = Integer.parseInt(termInvested);
    and yet more code..
    public void numberAceYears (int aceYears)
    for (int aY = 5 ; aY <= aceYears; aY++)
    double aceInterest = aceCoBalance * aceCoRate /100;
    aceCoBalance = aceCoBalance + aceInterest;
    aceYears = aceYears + aY;
    Suggestions?

    Short version: Either make the variable in question static, or create an instance of your class and use that to access it. Either one will work, but one probably suits your design better. It's up to you to figure out which one.
    For details, see the relevant section of your favorite Java book or tutorial, or poke around here:
    http://www.google.com/search?q=java+non+static+variable+cannot+be+referenced+from+a+static+context

  • Non-static variable change cannot be referenced from a static context

    My compiler says: : non-static variable change cannot be referenced from a static context
    when i try to compile this. Why is it happening?
    public class change{
      int coin[] = {1,5,10,25,50};
      int change=0;
      public static void main(){
        int val = Integer.parseInt(JOptionPane.showInputDialog(null, "Type the amount: ", "Change", JOptionPane.QUESTION_MESSAGE));
        change = backtrack();
    }

    A static field or method is not associated with any instance of the class; rather it's associated with the class itself.
    When you declared the field to be non-static (by not including the "static" keyword; non-static methods and fields are much more common so it's the default), that meant that the field was a property of an object. But the static main method, being static, didn't have an object associated with it. So there was no "change" property to refer to.
    An alternative way to get this work, would be to make your main method instantiate an object of the class "change", and put the functionality in other instance methods.
    By the way, class names are supposed to start with upper-case letters. That's the convention.

  • Non-static method cannot be referenced from a static context

    Hey
    Im not the best java programmer, im trying to teach myself, im writing a program with the code below.
    iv run into a problem, i want to call the readFile method but i cant call a non static method from a static context can anyone help?
    import java.io.*;
    import java.util.*;
    public class Trent
    String processArray[][]=new String[20][2];
    public static void main(String args[])
    String fName;
    System.out.print("Enter File Name:");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    fName="0";
    while (fName=="0"){
    try {
    fName = br.readLine();
    System.out.println(fName);
    readFile(fName);
    catch (IOException ioe)
    System.out.println("IO error trying to read File Name");
    System.exit(1);
    public void readFile(String fiName) throws IOException {
    File inputFile = new File(fiName); //open file for reading
         FileReader in = new FileReader(inputFile); //
    BufferedReader br = new BufferedReader(
    new FileReader(inputFile));
    String first=br.readLine();
    System.out.println(first);
    StringTokenizer st = new StringTokenizer(first);
    while (st.hasMoreTokens()) {
    String dat1=st.nextToken();
    int y=0;
    for (int x=0;x<=3;){
    processArray[y][x] = dat1;
    System.out.println(y + x + "==" + processArray[y][x]);
    x++;
    }

    Hi am getting the same error in my jsp page:
    Hi,
    my adduser.jsp page consist of form with field username,groupid like.
    I am forwarding this page to insertuser.jsp. my aim is that when I submit adduser.jsp page then the field filled in form should insert into the usertable.The insertuser.jsp is like:
    <% String USERID=request.getParameter("id");
    String NAME=request.getParameter("name");
    String GROUPID=request.getParameter("group");
    try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mynewdatabase","root", "root123");
    PreparedStatement st;
    st = con.prepareStatement("Insert into user values (1,2,4)");
    st.setString(1,USERID);
    st.setString(2,GROUPID);
    st.setString(4,NAME);
    // PreparedStatement.executeUpdate();//
    }catch(Exception ex){
    System.out.println("Illegal operation");
    %>
    But showing error at the marked lines lines as:non static method executeupdate can not be referenced from static context.
    Really Speaking I am newbie in this java world.
    whether you have any other solution for above issue?
    waiting Your valuable suggestion.
    Thanks and regards
    haresh

  • Cannot be referenced from a static context

    im trying to link my user interface to the Game class to jump,
    i get the error - non static method jump() cannot be referenced from a static context
    private void jButton1_actionPerformed(ActionEvent e)
              System.out.println("\njButton1_actionPerformed(ActionEvent e) called.");
              // code
    Game.jump();
    any ideas? thanks

    ah, it works if i change jump() to static
    i was now wondering how to make the user interface
    work with this ethod in the Game() class
    private void goRoom(Command command)
    if(!command.hasSecondWord()) {
    // if there is no second word, we don't know where to go...
    System.out.println("Go where?");
    return;
    String direction = command.getSecondWord();
    // Try to leave current room.
    Room nextRoom = currentRoom.getExit(direction);
    if (nextRoom == null)
    System.out.println("There is no door!");
    else {
    currentRoom = nextRoom;
    System.out.println(currentRoom.getLongDescription());
    i was thinking something like
    private void jButton1_actionPerformed(ActionEvent e)
    // code
    Game.goRoom(Command north);
    it doesnt seem to like that though.. :s

  • "non-static ... cannot be referenced from a static..." BUT they're static!

    Well, this is starting to get a little frustrating.
    I compile and get "non-static method cannot be referenced from a static context", BUT I declared the method as static!!! Why am I still getting this!?!
    I'm calling the method from my main, as it is in another class. I've done this before and never ran into problems, but for some reason this time I am. Can anyone let me know what the problem could be and some possible solutions for fixing it.
    Thank you so much.

    A lot of people don't know this, but whenever you run javac or use a compiler in an IDE, it doesn't actually compile the code. It just packages it up and emails it to an email address at sun.com. There, a Sun developer reads your code and then turns it into bytecode by hand. It seems to go really fast, but that's because it's sent to to hundreds of offshore developers working in parallel. Then the lead developer emails your compiled class file back to javac, which then writes it to disk, unless the developer there had problems, in which case they email you back a list of error messages that javac displays to the screen.
    So what happened was, the first time you compiled it, the offshore developers didn't like you personally, so they sent you error messages. But the second time you tried to compile it, they had changed shifts, and the new developers did like you, so they compiled your code.
    Your code didn't change, you didn't invoke javac differently, and your code and your skills as a developer are all flawless. It's just a matter of whether the folks doing the compiliation like you.

  • Non-static cannot be referenced from a static context - ?

    Hi, i understand (kinda) what the error means
    i think its saying that i cannot call a non-static method "bubbleSort"
    from the static method main (correct?)
    but i dont know how to fix it...
    do i make bubbleSort
    public static void bubbleSort???
    C:\jLotto\dataFile\SortNumbers.java:80: non-static method bubbleSort(int[]) cannot be referenced from a static context
              bubbleSort( a ); //sort the array into ascending numbers
    my code:
    import java.io.*;
    import java.util.*;
    public class SortNumbers
         public static void main( String args[]) throws IOException
          int num;
              int a[] = new int[7]; //an array for sorting numbers
              File inputFile = new File("C:\\jLotto\\dataFile\\outagain.txt");
              File outputFile = new File("C:\\jLotto\\dataFile\\sortedNum.txt");
            BufferedReader br = new BufferedReader( new FileReader( inputFile ));
          PrintWriter pw = new PrintWriter( new FileWriter( outputFile ));
          String line = br.readLine();
          while( line != null ){//reads a single line from the file
             StringBuffer buffer = new StringBuffer(31);          //create a buffer
             StringTokenizer st = new StringTokenizer( line," "); //create a tokenizer
             while (st.hasMoreTokens()){
                        // the first 4 tokens are id,month,day,ccyy, no sorting needed
                        // so they are simply moved into the buffer
                        for (int i =1; i<5; i++){
                             num = Integer.parseInt(st.nextToken());
                             buffer.append( num );
                             buffer.append( "|");
                        //tokens 5 to 11 need to be sorted into acending order
                        //so read tokens 5 to 11 into an array for sorting
                        for (int i =0; i<7; i++){
                             a[i] = Integer.parseInt(st.nextToken());
                     bubbleSort( a ); //sort the array into ascending numbers
                      //the array is sorted so read array back into the buffer
                      for ( int i = 0; i < a.length; i++ ){
                           buffer.append( a[ i ] );
                           buffer.append(  "|" ) ;
                   }//end of while st.hasMoreTokens
             //then write out the record from the stringBuffer
             pw.println( buffer );
             line = br.readLine();
          }//end of while != null
              br.close();
              pw.close();
         }//end of static main
       // sort the elements of an array with bubble sort
       public void bubbleSort( int b[] )
          int swapMade = 0; //if after one pass, no swaps were made - exit
          for ( int pass = 1; pass < ( b.length - pass) ; pass++ ) // passes reduced for speed
              for ( int i = 0; i < b.length - 1; i++ ) // one pass
                  if ( b[ i ] > b[ i + 1 ] )            // one comparison
                      swap( b, i, i + 1 );              // one swap
                      swapMade = 1;
                  }  // end of if
               } //end of one pass
             if (swapMade == 0) pass = 7; //no swaps, so break out of outter for loop
          }//end of passes, end of outter for loop
       }//end of bubblesort method
       // swap two elements of an array
       public void swap( int c[], int first, int second )
          int hold;  // temporary holding area for swap
          hold = c[ first ];
          c[ first ] = c[ second ];
          c[ second ] = hold;
       }   //end of swap
    }//end of class SortNumbers

    Static means
    when u run the program (a class), there is only one variabel / type in memory.
    ex static int a; //assume it's inside the aStaticClass
    mean no wonder how many u create object from this class, variabel a only have 1 in memory. so if u change a (ex a=1;) all instance of this aStaticClass will effected (because they share the same variabel).
    Try to read more at :
    http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html
    I hope this will help you....happy new year
    yonscun

  • Non-static method cannot be referenced from a static context....again sry

    Hey, I know you guys have probably seen a lot of these, but its for an assignment and I need some help. The error I'm getting is: non-static method printHistory() cannot be referenced from a static context. Here are the classes effected
    public class BankAccount {
    private static int nextAccountNumber = 1000;
    //used to generate account numbers
    private String owner; //name of person who owns the account
    private int accountNumber; //a valid and unique account number;
    private double balance; //amount of money in the account
    private TransactionHistory transactions; //collection of past transactions
    private Transaction transaction;
    //constructor
    public BankAccount(String anOwnerName){
    owner = anOwnerName;
    accountNumber = nextAccountNumber++;
    balance = 0.0;
    transactions = new TransactionHistory();
    //public String getOwner() {
    public void deposit(double anAmount ){
         balance=balance+anAmount;
         transaction=new Transaction(TransactionType.DEPOSIT,accountNumber,anAmount,balance);
         transactions.add(transaction);
    //public void withdraw(double anAmount){
    //public String toString() {
    ***public void printHistory(){
         TransactionHistory.printHistory();
    AND
    public class TransactionHistory {
    final static int CAPACITY = 6; //maximum number of transactions that can be remembered
    //intentionally set low to make testing easier
    private Transaction[] transactions = new Transaction[CAPACITY];
    //array to store transaction objects
    private int size = 0;
    //the number of actual Transaction objects in the collection
    public void add(Transaction aTransaction){
         if (size>5){
         transactions[0]=transactions[1];
         transactions[1]=transactions[2];
         transactions[2]=transactions[3];
         transactions[3]=transactions[4];
         transactions[4]=transactions[5];
         transactions[5]=aTransaction;     
         transactions[size]=aTransaction;
         size=size++;
    public int size() {
         return size;
    ***public void printHistory() {
         for(int i=0;i<6;i++){
              System.out.println(transactions);
    //public void printHistory(int n){
    The project still isn't finished, so thats why some code is commented out. The line with *** infront on it are the methods directly effected, I think. Any help would be great.

    In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term +instance+ is often substituted for +non-static+, as in "instance method" or "instance variable."
    The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    ~

  • Non-static method paint cannot be referenced from static context

    i cant seem to figure out this error dealing method paint:
    public class TemplateCanvas extends Canvas implements Runnable {
        //static
        public static final int STATE_IDLE      = 0;
        public static final int STATE_ACTIVE    = 1;
        public static final int STATE_DONE      = 2;
        private int     width;
        private int     height;
        private Font    font;
        private Command start;   
        private int state;
        private String message;
        public TemplateCanvas() {
            width = getWidth();
            height = getHeight();       
            font = Font.getDefaultFont();
            //// set up a command button to start network fetch
            start = new Command("Start", Command.SCREEN, 1);
            addCommand(start);
        public void paint(Graphics g) {
            g.setColor(0xffffff);
            g.fillRect(0, 0, width, height);
            g.setColor(0);
            g.setFont(font);
            if (state == STATE_ACTIVE) {
                Animation.paint(g);
            } else if (state == STATE_DONE) {
                g.drawString(message, width >> 1, height >> 1, Graphics.TOP | Graphics.HCENTER);
        public void commandAction(Command c, Displayable d) {
            if (c == start) {
                removeCommand(start);
                //// start fetching in a new thread
                Thread t = new Thread(this);
                t.start();
        public void run() {
            state = STATE_ACTIVE;
            //// start network fetch
            Network network = new Network();
            network.start();
            //// start busy animation
            Animation anim = new Animation(this);
            anim.start();
            //// wait for network to finish
            synchronized (network) {
                try {
                    wait();
                } catch (InterruptedException ie) { }
            //// end animation
            anim.end();
            //// get message from network
            message = network.getResult();
            //// repaint message
            state = STATE_DONE;
            repaint();
    }TemplateCanvas.java:38: non-static method paint(javax.microedition.lcdui.Graphics) cannot be referenced from a static context

    Animation.paint(g); paint() is not a static method. That means you have to call it on an instance of an Animation class (an object), not on the class itself. This is designed this way because the paint() method uses variables that have to be instantiated, so if you don't have an instance to use, it can't access the variables it needs. Static methods don't use instance variables, they only use what's passed in to them, so they don't need to be called on an object. Hope that was clear.

Maybe you are looking for

  • How do I delete iCloud account to change apple id, when iCloud demands password from defunct account to turn off find my iPhone?

    How do I delete iCloud account to change apple id, when iCloud demands password from defunct account to turn off Find my iPhone? I read all the replies that ignore this gotcha.

  • Maximum page size in fireworks

    hi, what is the maximum size fireworks can handle. As i have one file in Tiff format which i want to edit in firewroks but by maintaining the same pge size . the page size is 112x112 inches . now the problem is i can open the same file in fw but if i

  • How to stop a while loop with long delay

    Hi everyone, I am building a simple program for turning on and off a single Bit.  The task is to turn ON the Bit for a period length T1, and OFF the Bit for a period length T2. T1 is normally different from T2, and can be controlled  by users.  Since

  • Setting of next focus for components

    Hi, I am working on GUI using text fields and buttons and stuff, and I need to make it such that when I press the Tab button on the keyboard, the focus will move from one text field to the other. I tried using setNextFocusableComponent(), but during

  • IBase & Component table names ?

    Hi, Can anyone tell me, the table names where the IBase & Component related to a support message ticket are stored? Thanks, mahantesh