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.

  • Java Tutorials

    by Published on January 10th, 2012 03:59 AM
    1. Categories:
    2. Java Tutorials

    I was surprised to notice that there wasn't a single tutorial on this forum which covered the creation of your own Exception classes, so I decided to make a small tutorial for you.
    TL;DR - If you don't fancy reading all the details, you may jump straight to the code, as it's pretty self explanatory if you have a basic concept of Exceptions and their hierarchy.

    Introduction

    You might be surprised to know that creating your own Exception is as easy, if not easier than any other occasion where you would extend a super class.

    The steps are simple:
    1.) Realise a situation where creating your own Exception would be a benefit
    2.) Name your Class the name you want your Exception to be known as
    3.) Make a decision on what Exception to subclass, checked or unchecked (explained below)
    4.) Throw it!
    ...
    by Published on December 22nd, 2011 02:35 PM
    1. Categories:
    2. Java Tutorials

    I’ve been asked to make a post on the dangers of relying on an IDE, so here goes…

    Tl;dr version: Relying too heavily on an IDE makes you a bad programmer. To demonstrate my point, think about trying to get your girlfriend to write hello world in notepad and compile and run from the command prompt, explaining to her what’s going on in each step. Chances are, she’d have a pretty good (if not vague) notion of what’s going on, and she’d be able to explain the gist of the process back to you. Now think about having her install eclipse, run it, set up a new project, generate a new main class template, write hello world using autocomplete, and press play. Even if you tried to explain each step to her, she’d have nowhere near the same understanding she gained from the simpler approach.

    Anyway… ...
    by Published on November 1st, 2011 01:23 PM
    1. Categories:
    2. Java Tutorials

    Oftentimes constructing a class might require many different variables - in short a particular class might need to be built with a range of options; options that are only decided at runtime. Creating a constructor that accepts several different parameters is an option, as is using a series of setter methods as needed (see below).

    As an example, lets build a Pizza. The following class contains the information we want to specify for our pizza - it allows us to specify the toppings, if we want it delivered, etc...This is a simple class, all of its variables are private and accessed only through the modifier get/set methods. For brevity I have left out comments in the code.

    import java.util.ArrayList;
    import java.util.List;
     
    public class Pizza{
     
    	private String crustType = "Thick";
    	private boolean extraCheese = false;
    	private boolean forDelivery = false;
    	private List<String> toppings = new ArrayList<String>();
     
    	public Pizza(){
     
    	}
     
    	public Pizza(String crust, boolean extraCheese, boolean forDelivery, String...toppings){
    		this.crustType = crust;
    		this.extraCheese = extraCheese;
    		this.forDelivery = forDelivery;
    		for ( String t : toppings ){
    			this.topings.add(t);
    		}
    	}
     
    	public String getCrustType() {
    		return crustType;
    	}
    	public void setCrustType(String crustType) {
    		this.crustType = crustType;
    	}
    	public boolean isExtraCheese() {
    		return extraCheese;
    	}
    	public void setExtraCheese(boolean extraCheese) {
    		this.extraCheese = extraCheese;
    	}
    	public boolean isForDelivery() {
    		return forDelivery;
    	}
    	public void setForDelivery(boolean forDelivery) {
    		this.forDelivery = forDelivery;
    	}
    	public List<String> getToppings() {
    		return toppings;
    	}
    	public void addTopping(String topping) {
    		this.toppings.add(topping);
    	}
    }
    ...
    by Published on October 27th, 2011 04:16 PM
    1. Categories:
    2. Java Tutorials

    Wasn't sure if this was to go here or in other. (Mod please move it if it should be somewhere else)

    I have noticed a large amount of posts that are doing something along the lines of
    public static void main(String[] args) throws Exception
    {
     
    }
    The reason that methods throw exceptions, is that the creators of that method believe that the program can still be saved. EG
    /**
     * If the program is in debug mode
     */
    public final boolean DEBUG = true;
    /**
     * Some Instance String
     */
    private String someString;
    /**
     * Get the first line from a file and save it to a variable
     */
    public void getFirstLine(File f)
    {
      try
      {
        BufferedReader in = new BufferedReader(new FileReader(f));
        someString = in.readLine();
        in.close();
      }catch(IOException e)
      {
        if(DEBUG)
        {
          e.printStackTrace():
        }
        System.err.println("An error occured reading the file, setting default properties");
     
        someString = "Yellow Unicorn";
      }
    }
    ...
    by Published on August 24th, 2011 05:17 PM
    1. Categories:
    2. Java Tutorials

    Processing Homepage: Processing.org
    Processing API: Extended Language (API) \ Processing.org
    Processing on Wikipedia: Processing (programming language) - Wikipedia, the free encyclopedia
    Processing Monsters: Processing monsters (a collection of open source Processing sketches that display monsters)
    Open Processing: OpenProcessing - Share Your Sketches! (a collection of open source Processing sketches that do other cool stuff)
    The game I made in Processing: Escape from Monster City

    Full disclosure- this started to feel like an advertisement, so I just want to say that I’m not affiliated with Processing at all. I just started playing with it, and I’m really excited about how it can be used to not only introduce new programmers to Java, but for experienced users to take Java to the next level.

    I participated in Ludum Dare last weekend, and I took that as an opportunity to learn Processing, which is “an open source programming language and environment for people who want to create images, animations, and interactions” built on top of Java.

    I’m extremely impressed by what Processing allows you to do in such a short amount of time. Out of the box, you have a 60 fps rendering loop, easy access to 3D primitives, and cool lighting effects, as well as image handling, camera manipulation, input processing, and a ton of other stuff I haven’t gotten into yet- all done in the object oriented style of Java. ...
    by Published on August 19th, 2011 03:54 PM
    1. Categories:
    2. Java Tutorials

    Where can I store my application data?
    I see a lot of people starting threads because they're struggling to persist (often) a little bit of data from one run of their Java application to the next. The offered solutions are often some kind of jiggery-pokery involving java.io.File. Not only is File handling a cross-platform morass (our favourite OSes can't even agree on path separators, let alone filesystem roots and GoodPlacesToPutApplicationData™), but every so often another limited-resource computing device appears, some of them without a natural filesystem at all.

    So if we can't store data in files, where can we store it? Enter the Java Preferences API in the java.util.prefs package. Preferences is a platform neutral way to store a small amount of simple data. It offers support to store Strings and built-in data types and retrieve them without having to worry how they are persisted. You simply obtain a Preferences instance, store your value-to-be-persisted on a key, exit your app and sleep easy. The next time you start your app, you obtain the Preferences instance and invoke get([key you used previously], [default if nothing's there]). Ideal - for simple use. ...
    by Published on June 21st, 2011 04:50 PM
    1. Categories:
    2. Java Tutorials

    This class simplifies the common task of asking the user for valid input. It was designed to be as simple to use as possible.

    Example usage:
    //Ask for the users name
    String name = Console.readString("Enter your name:");
     
    //Ask for the users age (between 6 and 110)
    int age = Console.readInteger("Enter you age:", "You cannot be that old!", 6, 110);
     
    //Ask for a float
    float pay = Console.readFloat("How much do you earn per hour:");
     
    //Ask for a double
    double pi = Console.readDouble("Enter as many digits of PI as you can remember:");
     
    //Ask a yes/no question
    boolean isProgrammer = Console.readYesNo("Are you a programmer [YES or NO]:");
     
    //Ask for an integer with the default prompt
    int i0 = Console.readInteger();
     
    //Ask for an integer with a custom prompt
    int i1 = Console.readInteger("Enter a number: ");
     
    //Ask for an integer with a custom prompt and custom error message
    int i2 = Console.readInteger("Enter a number: ", "Try again.");
     
    //Ask for an integer in the range 1..10 with a custom prompt and custom error message 
    int i3 = Console.readInteger("Enter a number between 1 and 10", "Not in range.", 1, 10);
     
    //Ask if the user would like to quit (put this in an infinite loop)
    if (Console.readYesNo("Really Quit [y/n]")) { System.exit(0); }
    ...
    Page 1 of 2 12 LastLast