Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 17 of 17

Thread: Compile error for enhanded for loop

  1. #1
    Member
    Join Date
    Jun 2014
    Posts
    33
    My Mood
    Inspired
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Compile error for enhanded for loop

    The second line is resulting in a Illegal start of type error.
    	int totalAttributes;
    	for( int value : attributesFinal ) {
    		totalAttributes =+ value;
    	}
    I'm pretty sure that there are no misplaced or missing brackets in the code. At least as far as I can see:
    abstract class Globals {
     
    	//private class variables - default values
    	private int[] attributesPrelim = {0, 0, 0, 0};
    	private int[] attributesFinal = {2, 2, 2, 2};
     
    	//set class constants
    	int totalAttributes;
    	for( int value : attributesFinal ) {
    		totalAttributes =+ value;
    	}
    	public static int TOTAL_ATTRIBUTE_VALUES = totalAttributes;
     
    	//public access methods
    	public int getNum() {
    		return attributesFinal.len();
    	}
    	public int getPrelim(int index) {
    		return attributesPrelim[index];
    	}
    	public int getFinal(int index) {
    		return attributesFinal[index];
    	}
    	public void addToPrelim(int index, int value) {
    		attributesPrelim[index] =+ value;
    	}
    	public void setFinal(int index, int value) {
    		attributesFinal[index] = value;
    	}
    }
    What gives?


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Compile error for enhanded for loop

    Please copy the full text of the error message and paste it here. It has important info about the error.
    Where is the ^?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Member
    Join Date
    Jun 2014
    Posts
    33
    My Mood
    Inspired
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Compile error for enhanded for loop

    I'm not entirely sure how to copy text from Command Prompt, but the arrow points to the letter f in for. Like:
            for( int value : attributesFinal ) {
            ^

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Compile error for enhanded for loop

    how to copy text from Command Prompt
    To copy the contents of the command prompt window:
    Click on Icon in upper left corner
    Select Edit
    Select 'Select All' - The selection will show
    Click in upper left again
    Select Edit and click 'Copy'

    Paste here.

    That for statement should be inside a constructor or method.
    If you don't understand my answer, don't ignore it, ask a question.

  5. The Following User Says Thank You to Norm For This Useful Post:

    Baldyr (July 6th, 2014)

  6. #5
    Member
    Join Date
    Jun 2014
    Posts
    33
    My Mood
    Inspired
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Compile error for enhanded for loop

    Thanks!

    So I should create like a main method which initializes the variables, then?

  7. #6
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Compile error for enhanded for loop

    Several problems here:
    	int totalAttributes;
    	for( int value : attributesFinal ) {
    		totalAttributes =+ value;
    	}
    	public static int TOTAL_ATTRIBUTE_VALUES = totalAttributes;
    First of all, you can not have a for-loop outside of a method body.

    Next thing is, that "=+" is not a true operation. You probably meant to do "+=".

    Then, if you really want to use "+=" you have to initialize "totalAttributes" to 0 or otherwise you get compile errors.

    And finally, you probably want to execute the for-loop within a "static" block:
    	public static int TOTAL_ATTRIBUTE_VALUES = 0;
    	static {
    		for( int value : attributesFinal ) {
    			TOTAL_ATTRIBUTE_VALUES += value
    		}
    	}

  8. The Following User Says Thank You to Cornix For This Useful Post:

    Baldyr (July 6th, 2014)

  9. #7
    Member
    Join Date
    Jun 2014
    Posts
    33
    My Mood
    Inspired
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Compile error for enhanded for loop

    I was actually gonna test whether or not totalAttributes would get assigned a default value of zero or not, but thanks for the info. Invaluable advice, all around!

  10. #8
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Compile error for enhanded for loop

    Just so you know, the variable TOTAL_ATTRIBUTE_VALUES is NOT a constant at this point.
    Its value can still be changed at any point in time.

    If you want it to be a constant you need to do a little hack:
    public static final int SOME_CONSTANT_INT = calculateConstantInt();
     
    private static void calculateConstantInt() {
        return /* complicated calculation */;
    }

  11. The Following User Says Thank You to Cornix For This Useful Post:

    Baldyr (July 6th, 2014)

  12. #9
    Member
    Join Date
    Jun 2014
    Posts
    33
    My Mood
    Inspired
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Compile error for enhanded for loop

    For anyone who might be interested to see the end result
    abstract class Globals {
     
    	//private class variables - default values
    	private static int[] attributesPrelim = {0, 0, 0, 0};
    	private static int[] attributesFinal = {2, 2, 2, 2};
     
    	//set class constants
    	static int totalAttributes = 0;
    	static {
    		for( int value : attributesFinal ) {
    			totalAttributes += value;
    		}
    	}
    	public static final int TOTAL_ATTRIBUTE_VALUES = totalAttributes;
     
    }

  13. #10
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Compile error for enhanded for loop

    This way you still keep the variable totalAttributes. It will forever stay in your memory as a package-private static variable of your Globals class.

    By the way, a class like this is heavily against the OOP idea. Instead you should make these variables private attributes and instanciate an object of this class. Either use the singleton pattern to access this object or keep it around as a private attribute of your controller classes.

  14. #11
    Member
    Join Date
    Jun 2014
    Posts
    33
    My Mood
    Inspired
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Compile error for enhanded for loop

    Yeah, I kinda realize this at some level. This style of coding is probably how I would have implemented this in (a language like) Python. I'll give the singleton route a try, as I've been observing similar things before without giving it much consideration myself. I'm still not sure what the actual benefit would be though.

    I tried googling for "controller class" but of course got the actual API class called Controller, while I'm thinking you're referring to a broader programming concept instead. Please do expand on this topic if you will - I'm all ears!

    On a side-note: Working with the Command Prompt and jEdit has changed my Window keyboard setting from Swedish to probably English or some default setting. While I realize this can be fixed - should I expect this to be an ongoing issue going forward? While it doesn't affect my coding it makes it very hard to write on these boards...

  15. #12
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Compile error for enhanded for loop

    What your "controller" classes are depends on your application.
    There exists a certain programming paradigm which is called Model-View-Control (MVC). The idea is, that your classes are loosely divided into these 3 categories:
    1) Model classes which contain attributes, information and management methods.
    2) View classes which are used to visualize your data, create output and show it to the user or play sound.
    3) Controller classes which create your models and the view, load data from disk, interprete user input, etc.

    For every application these classes would look differently, but their use would always be similar. At first, this might look verbose or over the top, but I can tell you from my own experience, that this architecture works great for applications with a GUI, like some kind of editor or developement enviroment. Analyse your own program. Think what the entry-point is and how you can organize all your classes. Then think about how you want to distribute information (like your "globals") through this program.

  16. #13
    Member
    Join Date
    Jun 2014
    Posts
    33
    My Mood
    Inspired
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Compile error for enhanded for loop

    That is probably what I've already done as far as the architecture goes, since I've set up a Globals class, a Enums class, a Debug class, a UserInterface class and a Test class. I actually managed to, finally, get the whole thing (clocking in at 145 lines of code) to compile without errors - and to run a preset debug test of sorts executed from the applications main class's main method. This execution pretty much involved all the code written to date, so I'm pretty satisfied with the result.

    Now I'm trying to remodel my Globals class into a singleton, as suggested, but am experiencing all the troubles I had before arriving at the above detailed previous solution. The error I'm getting at every junction seems to be "illegal start of expression". I'm not finding any missing or miss-placed braces that would explain this, and all expressions are now part of some body of code. This is the first instance where I'm having issues:
    	// constructor
    	private static void Globals( ) {
     
    		//set private class variables to default values
    		int[] attributesPrelim = {0, 0, 0, 0};
    		int[] attributesFinal = {2, 2, 2, 2};
     
    		//set class constants
    		public static final int TOTAL_ATTRIBUTE_VALUES = getTotalAttributes();
    	}
    The Command Prompt:
    Horoscope.java:60: error: illegal start of expression
                    public static final int TOTAL_ATTRIBUTE_VALUES = getTotalAttributes();
                    ^
    Horoscope.java:60: error: illegal start of expression
                    public static final int TOTAL_ATTRIBUTE_VALUES = getTotalAttributes();
                           ^
    Horoscope.java:60: error: ';' expected
                    public static final int TOTAL_ATTRIBUTE_VALUES = getTotalAttributes();
                                 ^
    This is all happening one again when I try to initiate the singleton class and assign it to a variable pointer.

    edit: I removed the static modifier as that makes no sense with a global variable. Still no luck though.
    Last edited by Baldyr; July 6th, 2014 at 03:04 PM.

  17. #14
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Compile error for enhanded for loop

    Thats not quite how the singleton pattern works.
    Here, take a look at this example, maybe it can help you:

    Our singleton
    public class Config {
     
    	public static final Config INSTANCE = new Config();
     
    	private int windowWidth;
    	private int windowHeight;
    	private String dataDirectory;
     
    	private Config() {
    		windowWidth = 0;
    		windowHeight = 0;
    		dataDirectory = "Resources/Data/";
    	}
     
    	public int getWindowWidth() {
    		return windowWidth;
    	}
     
    	public int getWindowHeight() {
    		return windowHeight;
    	}
     
    	public void setWindowSize(int width, int height) {
    		windowWidth = width;
    		windowHeight = height;
    	}
     
    	public String getDataDirectory() {
    		return dataDirectory;
    	}
     
    	public void setDataDirectory(String dir) {
    		dataDirectory = dir;
    	}
     
    }

    How it is used:
    public class Application {
     
    	public void createApplicationWindow() {
    		Config config = Config.INSTANCE;
    		int width = config.getWindowWidth();
    		int height = config.getWindowHeight();
     
    		Window wnd = new Window(width, height);
    		//...and so on
    		Data data = new Data(config.getDataDirectory());
    	}
     
    }


    Now, I would discourage this use, but it is simple and easy to implement.
    Much better would be if you had a good information distribution strategy for your project.

    For example:
    public class Config {
     
    	private int windowWidth;
    	private int windowHeight;
    	private String dataDirectory;
     
    	public Config() {
    		windowWidth = 0;
    		windowHeight = 0;
    		dataDirectory = "Resources/Data/";
    	}
     
    	public int getWindowWidth() {
    		return windowWidth;
    	}
     
    	public int getWindowHeight() {
    		return windowHeight;
    	}
     
    	public void setWindowSize(int width, int height) {
    		windowWidth = width;
    		windowHeight = height;
    	}
     
    	public String getDataDirectory() {
    		return dataDirectory;
    	}
     
    	public void setDataDirectory(String dir) {
    		dataDirectory = dir;
    	}
     
    }
    public class Application {
     
    	private Config config;
     
    	public Config getConfig() {
    		return config;
    	}
     
    	public void createApplicationWindow() {
    		config = new Config();
     
    		Data data = new Data(config);
    		Window wnd = new Window(config);
    	}
     
    }

    This way our window (view) and our data (model) will have access to our configuration because our Application (Control) will give them a reference.
    This is more OOP then the singleton and is also easier to work with in my opinion.

    But you should pick whatever strategy you prefer.

  18. #15
    Member
    Join Date
    Jun 2014
    Posts
    33
    My Mood
    Inspired
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Compile error for enhanded for loop

    Well, I really can't see the difference between your singleton class and mine. Except that mine is defining variables inside the constructor, whereas yours only assigns the values once the constructor is invoked.

    The other solution you suggest involves instantiating a new Config object every time the "global" variables av accessed, not? I don't see how that is more optimal than going the original route with an abstract class holding global class variables.

    But since I'm still struggling with my singleton setup - does anyone know what is up with the Illegal start of expression errors I'm seeing?

  19. #16
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Compile error for enhanded for loop

    You can not define attributes within a constructor, or any method for that matter.
    Attributes of a class can only be defined outside of methods.

    With the second approach you are not supposed to create multiple instances of Config. It will still be only a single instance for the entire duration of the program. The difference is, however, that it is created and managed within a Controller class, in my example this is the class Application.

  20. The Following 2 Users Say Thank You to Cornix For This Useful Post:

    Baldyr (July 6th, 2014), GregBrannon (July 8th, 2014)

  21. #17
    Member
    Join Date
    Jun 2014
    Posts
    33
    My Mood
    Inspired
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: Compile error for enhanded for loop

    By the way, I finally got the singleton solution working. Thanks Cornix!
    //singleton class for holding global variables
    class Globals {
     
    	// setup singleton instance
    	private static Globals singleton;
     
    	int[] attributesPrelim = {0, 0, 0, 0};
    	int[] attributesFinal = {2, 2, 2, 2};
    	public final int TOTAL_ATTRIBUTE_VALUES;
     
    	// constructor
    	private Globals( ) {
     
    		//set global constants
    		TOTAL_ATTRIBUTE_VALUES = getTotalAttributes( );
    	}
    	private int getTotalAttributes( ){
    		int totalAttributes = 0;
    		for( int value : attributesFinal ) {
    			totalAttributes += value;
    		}
    		return totalAttributes;
    	}
     
    	//public access methods
    	public static Globals getSingleton( ) {
    		if(singleton == null) {
    			singleton = new Globals( );
    		}
    		return singleton;
    	}
     
    }
    Consider this thread double solved, then.

Similar Threads

  1. Replies: 3
    Last Post: November 30th, 2013, 05:52 PM
  2. Why won't my program compile? (While loop with inputs)
    By LWorm in forum Loops & Control Statements
    Replies: 5
    Last Post: October 14th, 2013, 10:52 PM
  3. Error while compile
    By when im gone in forum What's Wrong With My Code?
    Replies: 3
    Last Post: January 7th, 2012, 10:53 AM
  4. Bank Balance - while loop - wont compile
    By mwardjava92 in forum Loops & Control Statements
    Replies: 15
    Last Post: November 9th, 2011, 05:19 PM
  5. Compile Error, tried everything please help
    By cdub0 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: May 17th, 2011, 03:31 AM