Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Syntax Problems
Index -> Programming, Java -> Java Help
Goto page 1, 2, 3  Next
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Aange10




PostPosted: Tue Dec 20, 2011 11:12 pm   Post subject: Syntax Problems

Okay, so, I have two classes inside a project. One class is holding an object called Dog. The class looks like this:

Java:

public class Dog {
        int age;
        String name;

        void Bark() {
                System.out.println("WOLF WOLF!");
        }
}


my other class is where my 'Main' is going to be, and it looks like this:

Java:

public class Loopy {
        Dog anthony = new Dog();
        {
                anthony.name = "Anthony";
                anthony.age = 6;
        }

        public static void main(String[] args) {
                anthony.Bark();
        }
}


In my PDF, it does something like this (it's poorly written; they just throw chunks of code without headers around, so I begin to get confused on how I connect the peices). But I'm getting the syntax error 'Cannont make a static reference to a non static field anthony.' I read the documentation for Java's Static, and they did an example just like this:

http://mindprod.com/jgloss/static.html wrote:

static methods and variable are in a sense inherited, but not in the same strong sense that instance variables and methods are. You can refer to Dog.bark() as Dalmatian.bark() if no one has written a Dalmatian.bark(). However, if you use Dog.bark() you always get the Dog version and if you say Dalmatian.bark() you always get the Dalmatian version.



After reading the documentation, I'm not sure what the problem is. I tried running the anthony.Bark(); without calling main but It was an error too. I also tried making void Bark() { into static void Bark() { but that didn't fix the problem (it still gave me the same syntax error).


Could anybody help me with seeing what the problem is with my method? Are both of my classes formatted correctly?

Also, in the PDF it does

Java:

        Dog anthony = new Dog();
        {
                anthony.name = "Anthony";
                anthony.age = 6;
        }


as

Java:

        Dog anthony = new Dog();
        anthony.name = "Anthony";
        anthony.age = 6;


why does it give me an error, but the pdf says it's good? (As I said the pdf shows a lot of blocks of code, without showing the headers etc. So It's hard to piece it all together.)


Thanks.
Sponsor
Sponsor
Sponsor
sponsor
crossley7




PostPosted: Tue Dec 20, 2011 11:26 pm   Post subject: RE:Syntax Problems

I happened to see this and although I haven't used Java much, I can see if I can help you debug a little bit. I think the problem is in relation to this section of code.

Dog anthony = new Dog();
{
anthony.name = "Anthony";
anthony.age = 6;
}

Generally at least in C++ classes (sorry, only reference I have other than really basic Java) those 2 lines of code inside the {} have to be within a function which in this case they are not.

Another issue that could be it (I discarded initially but will mention it anyway) is that anthony is a member of loopy. It shouldn't be an issue since it is within the same class but I'm never 100% sure. Also, might be something with the class names? main seems to have additional importance in a program and so you might just need to rename the second class. Once again, sorry if these are really dumb suggestions. I need to actually figure out Java before making educated guesses based on my knowledge of other languages.
Aange10




PostPosted: Tue Dec 20, 2011 11:40 pm   Post subject: RE:Syntax Problems

the
Java:

Dog anthony = new Dog();
{
anthony.name = "Anthony";
anthony.age = 6;
}


Honestly doesn't make sense to me either, but if I don't add the { and }, it gives me a syntax error. The pdf doesn't do it that way, but the way the PDF does it gives me a syntax error.
DemonWasp




PostPosted: Tue Dec 20, 2011 11:43 pm   Post subject: RE:Syntax Problems

It seems you don't really understand what "static" means...and I can't blame you, that copy-paste stuff from your PDF is awful (if technically correct).

Every field in a class is either an instance field or a static field. The same applies to methods: there are instance methods and static methods and no other kinds of methods. The default is instance; to make something static, you add the static keyword.

Instance means one-per-object. That is, every dog has a name, and they can have different names. Similarly, every dog has an age, birthdate, favourite toy, etc. These are wrapped together by an instance of the Dog class. You create a new instance every time you use the new keyword.

Static means one-per-type. That is, only one copy, no matter how many dogs you have. Use these to describe data or behaviours that are shared across all objects of that type. Methods like Math.abs(x) and Integer.parseInt("123") are static because you don't need an instance of the Math class to know how absolute value works. It's in the Math class so that everything remains organised into logical units (Math, Integers, Doubles, etc).

You cannot override a static method. You can override instance methods. You can overload both.

A static method exists as soon as the type exists ("always", until you get really advanced). An instance field only exists when an instance of the object exists.

Your problem is that this:
Java:

public class Loopy {
    Dog anthony = new Dog();
    {
        anthony.name = "Anthony";
        anthony.age = 6;
    }
    //...
}


Defines an instance field, "anthony", inside the Loopy class. Therefore, every time you make a new Loopy(), it will automatically create a new Dog() and assign it the name "Anthony" and the age 6.

However, you never make any Loopy instances. The main method is static, which means it can be called without creating any Loopys at all. What you need to do is create your Dog instance inside your main() method. An alternate approach that works, but isn't as good, is to make anthony static, which means that it exists as soon as the Loopy type exists.

Your other question is presumably about this:
Java:

public class Loopy {
    Dog anthony = new Dog();
    anthony.name = "Anthony";
    anthony.age = 6;
}


The reason that doesn't work (but the one with the braces does) is because this version has statements (assignments, specifically) happening outside of a method or initializer. The line "Dog anthony = new Dog();" is okay because it's a variable declaration with initialization. The next two lines are statements, and are not permitted there. Wrapping them in braces produces what's called an "initializer block" (see: http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html). I've never seen one in actual use before (though I have seen static initializer blocks).
Tony




PostPosted: Tue Dec 20, 2011 11:49 pm   Post subject: RE:Syntax Problems

@crossley7 -- {} define a block which can do anywhere a statement goes. Even in C++
Quote:


McEpic:tmp tony$ cat test.cc
int main(){
int x = 1;
{
int x = 2;
}
x++;
return x;
}

McEpic:tmp tony$ g++ test.cc
McEpic:tmp tony$ ./a.out
McEpic:tmp tony$ echo $?
2


@Aange10 --
Quote:

error 'Cannont make a static reference to a non static field anthony.'

means that the field "anthony" is part of an instance of Loopy, while "public static void main" is a static method -- that is, it belongs to the class.

Even though you might have only a single instance of Loopy, the program can't know that you will not have another at some future point. As such, the shared static method can't know which "anthony" you might be referring to.
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
Zren




PostPosted: Tue Dec 20, 2011 11:53 pm   Post subject: RE:Syntax Problems

{} are used for scope. A static field requires something like this:

Java:

public class Loopy {
        Dog anthony = new Dog();

        static {
                anthony.name = "Anthony";
                anthony.age = 6;
        }

        public static void main(String[] args) {
                anthony.Bark();
        }
}


However in this case, anthony hasn't been declared (as it's an instance variable). What you should be doing, is creating a static function to set those values and call it first. What you should really be doing is making a constructor for the Dog class.

Also, you can't do more than declare (and initialize) class members within the class's 'outer' or 'root' scope (not entirely how to define this, maybe 'field'?). That's why you can't define a variable on one line (with a closing statement ';') and assign it on another line.

A good question would be to check if they're running a different/older version of Java.
Aange10




PostPosted: Wed Dec 21, 2011 12:05 am   Post subject: RE:Syntax Problems

Confusing.

Okay so

Java:

Dog anthony


is assigning a variable named anthony to a type Dog, correct?

and then

Java:

anthony = new Dog()


is making anthony, whos type is Dog, an instance of Dog.

That confuses me. If the class file was animal, with Dog in it, would I say

Java:

animal anthony = new Dog();

?

Right I understand what a type is, but not a reference type. That is, I'm not sure the difference between defining something as a reference to something, and making an instance of something.

Wherein my confusion of that,

DemonWasp wrote:

Instance means one-per-object.

Static means one-per-type


makes this very unclear.

An instance of something is just an object of it right? Like a child of it?


And my origional problem was that I was defining a new class (loopy) instead of defining a new instance of Dog? [Well, I did both]


EDIT: To clarify what I was trying to do: all I'm trying to do is make an object of dog, named Anthony, define its instances, then call its method.
DemonWasp




PostPosted: Wed Dec 21, 2011 3:33 am   Post subject: Re: RE:Syntax Problems

Hmm. You also seem to be confusing "instance", "type", and a few other concepts.

A "type" is a way of arranging information. An int is a type that can hold integers in a certain range. A double can hold real numbers. A String can hold a series of characters. A Dog holds a name and an age.

An "instance" is one particular thing of a type. An "instance" of an integer might be the number 3. An instance of a double could be 3.1415. An instance of a string could be "FooBarBaz". An instance of a Dog could have the name "anthony" and the age 6. A different instance could have name "Rover" and age 2.

An instance is NOT a child of its type. It is an instance of its type. For example, you and I are both humans. We could be represented by two instances of the Human class. We have type Human, and you could say "Aange10 and DemonWasp are (instances of) Human". If you changed the type Human, we would both have the same changes.




The difference between a primitive type (boolean, byte, short, int, long, char, float, double) and a reference type (String, Object, anything you define) is a little tricky to understand:

A primitive type is the simplest form of information you can store. They are each exactly one thing. For example, an int holds an integer number. A double holds a real number. A char holds a single character. They don't have additional information stored in them (unlike Dog, which has name and age and ...).

A reference type is any type that isn't primitive. All reference types extend from Object (potentially through several layers), even when they don't explicitly say so. If you say:
Java:

public class Dog {
}

Then Dog extends Object.

The difference is only important occasionally. It is most important when passing things to methods. For example:

Java:

public class Foo {
    public static void main ( String[] args ) {
        int i;
        myMethod ( i );
    }

    public static void myMethod ( int i ) {
        i = 3;    // has no effect on the i in main method
    }
}


But:
Java:

public class Foo {
    public static void main ( String[] args ) {
        Dog d;
        myMethod ( d );
    }

    public static void myMethod ( Dog d ) {
        d.name = "Rex";    // WILL change the name of the Dog d in main method

        d = new Dog();    // will NOT change the Dog d in main method, just the Dog d in myMethod
        d.name = "Fuzzy";    // will change the new dog's name, but not the Dog d in main method
    }
}

Right before Java finishes running "myMethod", it will have two instances of Dog. The first is the Dog d in main, and it has the name "Rex". The second is the Dog d in myMethod, and it has the name "Fuzzy".




To extend your example, let's assume you have defined two types of your own: Animal and Dog. Now, all animals will have an age and a name:

Animal.java:
Java:

public class Animal {
    String name;
    int age;
}


Dogs may have other information in addition. However, a Dog is-a(n) Animal. All Dogs are Animals, but not all Animals are Dogs (some are Cats, etc). So:
Java:

public class Dog extends Animal {    // because all Dogs are Animals
    String favouriteToy;
}





The words "define", "declare", "initialize" and "assign" have very specific meanings:

You define a type when you list what fields and methods it has. For example, you have defined Dog to have fields "String name" and "int age" and methods "void Bark()".

You declare a variable when you give its type. For example, "Dog myDog;" is a declaration of a variable named "myDog" of type Dog.

You initialize a variable when you first assign it. Often, you do this on the same line as the declaration: "Dog myDog = new Dog();".

Do Not*:
You never define an instance.
You never declare an instance.
You never initialize a type.
You never assign a type.




As for your original problem:
Aange10 wrote:
And my origional problem was that I was defining a new class (loopy) instead of defining a new instance of Dog? [Well, I did both]

EDIT: To clarify what I was trying to do: all I'm trying to do is make an object of dog, named Anthony, define its instances, then call its method.


None of that makes sense. What you are trying to do is:
1. Create a new instance of Dog.
2. Assign the Dog's name the value "Anthony".
3. Assign the Dog's age the value 6.
4. Call the bark() method of the Dog.

So, go put code inside the main method that does this.



* For advanced Java programmers only: you almost never do those things.
Sponsor
Sponsor
Sponsor
sponsor
2goto1




PostPosted: Wed Dec 21, 2011 7:53 am   Post subject: Re: RE:Syntax Problems

Aange10 @ Wed Dec 21, 2011 12:05 am wrote:


That confuses me. If the class file was animal, with Dog in it, would I say

Java:

animal anthony = new Dog();

?


Class file names are simply conventions. The source code file names do not define your Java types. If you really wanted to for fun and giggles, you could place your Dog class definition inside a Cat.java source file. You would still have just a Dog type that you could instantiate using the new operator. But you would not have a Cat type that you could instantiate with the new operator. You would not have a Cat namespace. Java would not know of the existence of Cat in any way, shape, or form.

Java packages and classes typically have a 1:1 relationship with your project's directory and file structure. That is, your Dog class will almost always reside in your Dog.java source file, and your Cat class will almost always reside in your Cat.java source file. It makes your projects much easier to maintain. It's a convention for organizing your source code, since Java, like many other programming languages, relies on your OS file system to keep source code organized.

If the source code file name was animal.java, or Cat.java, and the source code file contained just your Dog class definition, then you would say:

Java:

Dog anthony = new Dog();
Aange10




PostPosted: Wed Dec 21, 2011 12:46 pm   Post subject: RE:Syntax Problems

Thanks all of you for your help, especially Demonwasp. I'll probably have more problems -- probably within a few hours -- so I'll be posting a lot of [basic] questions.

Thanks.
Aange10




PostPosted: Thu Dec 22, 2011 5:59 pm   Post subject: RE:Syntax Problems

Another problem;

Firstly, I have a question (as it is my hunch to why this isn't working), when I have a method for an object, and in the method I call one of the object's instance variables, will it call the correct number?

Example (My Problem);

I have a class Math, that looks like:

Java:

public class Math {
        int int1, int2, int3;
        double fahrenheit, celsius;
        void PrintSolution (){
                System.out.println ((int1 * int2 * int3));
        }
        void PrintConverterFtC (){
                double tempnum = (5/9) * (fahrenheit - 32);
                System.out.println ("The degrees " + fahrenheit + " fahrenheit is equal to " + tempnum + " degrees celsius.");
        }
}


If in another class I make a new instance of Math, will the fahrenheit variable in the PrintConverterFtC method hold the value of of the new instance of Math's value?

[Heres the other part of my Project]

This is my Main class

Java:

public class Main {
        public static void main (String [] args){
                Math foo = new Math();
                foo.int1 = 5;
                foo.int2 = 10;
                foo.int3 = 100;
                foo.fahrenheit = 45;
                foo.celsius = 20;
                //foo.PrintSolution();
                foo.PrintConverterFtC();
        }
}

Tony




PostPosted: Thu Dec 22, 2011 6:11 pm   Post subject: Re: RE:Syntax Problems

Aange10 @ Thu Dec 22, 2011 5:59 pm wrote:
If in another class I make a new instance of Math, will the fahrenheit variable in the PrintConverterFtC method hold the value of of the new instance of Math's value?

Yes, this is how instance variables work.

Ninja edit: to be clear, we are talking about PrintConverterFtC of the new instance, not of the old instance. The old method will still have its own variable to work with.
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
Aange10




PostPosted: Thu Dec 22, 2011 6:33 pm   Post subject: RE:Syntax Problems

So, in my Main class I defined foo.fahrenheit as 45, then I run foo.PrintConverterFtC, and it outputs 0. Which, clearly, (5/9) * (45 - 32) isn't 0. (it's 7.2)

I must be misunderstanding you.
Zren




PostPosted: Thu Dec 22, 2011 6:41 pm   Post subject: RE:Syntax Problems

5/9 is integer division, which gives 0. You need to cast the later part to a real type. Since you're using a hardcoded number you can just do either of the following.

5 / ((double)9) // Cast the integer to a double
5 / 9.0 // 9 is a real number (double)
5 / 9D // 9 is a double
Aange10




PostPosted: Thu Dec 22, 2011 6:50 pm   Post subject: RE:Syntax Problems

Thankyou, Zren, and for future reference, would 5.0/9.0 work?

Also, say that it was all variables, and not hardcoded, would it be reccomended that I did ((double) var5/var9)?


Thanks.


EDIT: 5/(double(9)) is a syntax error.

EDIT again: How would I make it only show two decimal spots?
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 3  [ 43 Posts ]
Goto page 1, 2, 3  Next
Jump to:   


Style:  
Search: