Welcome to the RaGEZONE - MMORPG development forums.

[Java] An IO Class (#2)

This is a discussion on [Java] An IO Class (#2) within the Coders' Paradise forums, part of the Evolution : RaGEZONE category; Previous: [Java] A Console Application (#1) Before I basically just gave you an introduction to a java console application. Mostly ...

Results 1 to 10 of 10
  1. #1
    :-)
    Rank
    Alpha Member
    Join Date
    Jun 2007
    Location
    Next Door
    Posts
    2,039
    Liked
    388

    [Java] An IO Class (#2)

    Previous: [Java] A Console Application (#1)


    Before I basically just gave you an introduction to a java console application. Mostly how to make a java console program from a file using Notepad++ or any text editor.


    I ended somewhat openly on the "static" keyword.

    Later I'll be going over static in more depth. Today we're going to work without the static keyword, except for the test-run. This tutorial should help clear up some things, by showing by example how to work without static, using "this" and instantiation.

    Open up you're favorite text-editor, and create a file named "io.java". Save it in "../somewhere/java/io/" where "../somewhere" is anywhere you like.

    We'll be saving a file called "test_run.java" here as well. Go ahead and create that file as well.

    Now remember, the class name must be the same as the file-name.

    So inside io.java, you should already have code like this:
    PHP Code:

    class io
    {


    and inside test_run.java,
    PHP Code:

    class test_run
    {


    Get in the habit of doing this right away for every java file. Occasionally you'll have some keywords as well, but the class files start relatively the same plus or minus some keywords and libraries.


    Moving on, our io class is an input/output class. Remember the library we need for input? Import it in io.java now.
    PHP Code:
    // Import the scanner library.
    import java.util.Scanner;

    // Input/Output Class
    class io
    {


    Don't forget to comment you're code! Notice how it's more clear to see what this class is going to be with the use of comments.


    We don't need a main method for this class, because we're not going to use this file as a stand-alone, it's pretty much a tiny library we're going to use on other files.

    It's job is to make input and output simpler to do in Java. Mostly for educational purposes.

    Now then, I'm going to make a method for output, named "out()". We don't want to make it static.

    PHP Code:
    // Import the scanner library.
    import java.util.Scanner;

    // Input/Output Class
    class io
    {
        
    // Prints some output
        
    public void outString Message )
        {
            
    System.out.print( Message );
            
        }
        

    Since this method only has 1 line inside it, the comment would be the same for that line as for the entire method. In cases like that, I just comment the method itself. Any programmer could link the method comment to the single line within the method as well.

    Now switch to test_run.java.

    To use our io class, we need to create a variable to instantiate the io class, and then we can use the methods (like io.out( "hi" ) ).

    We need a main method inside test_run.java, and that's about it. Inside the main method we instantiate the io class and make a test-call to out("hi");

    PHP Code:
    class test_run 
    {
        public static 
    void mainString args[] )
        {
            
    // variable (type "io", and named "io") instantiates a new In/Out class
            
    io io = new io();
            
            
    // Test the out() method:
            
    io.out"hi!" );
            
        }
        

    Once we instiate a class into a variable, we can use that variable to run the underlying methods.

    Take a minute to test this and play around with it.

    Open up a console, navigate using cd to "../somewhere/java/io". Compile using javac io.java, and then javac test_run.java. Then run the test_run by typing "java test_run".

    ...

    Now let's create some more methods for our io class. We need to take some input, so, let's set that up now.

    Switch back to io.java.

    Let's create a method called "in" for taking input. It's type is String, so it must return a string every time.

    We've already imported the Scanner library. So, naturally, we'll be using the scanner to take input. Since the class is named "io", I'm putting the input methods before the output methods, simply because of organization.

    Here's what it looks like now:
    PHP Code:
    // Import the scanner library.
    import java.util.Scanner;

    // Input/Output Class
    class io
    {
        
        
    // Returns a line of input
        
    public String in()
        {
            
    // Create Scanner for Input
            
    Scanner in = new ScannerSystem.in );

            
    // Fill input String with a line of data from Input Scanner
            
    String input in.nextLine();

            
    //Close the scanner stream
            
    in.close();
        
            
    // Return the input as a String
            
    return input;
            
        }
        
        
    // Prints some output
        
    public void outString Message )
        {
            
    System.out.print( Message );
            
        }
        

    You may have noticed a need for line breaks in the console. So let's add a new "outln" method, which prints output followed by a new line.

    Java has a system.out.println() method which does this. I think io.outln() is easier to type, but not much easier.

    A method like this would work:

    PHP Code:
    // Print output followed by a line break
    public void outlnString Message )
    {
        
    system.out.printlnMessage );

    .. But I want to use our "out()" method instead.

    We have two choices:
    - Instantiate the io class and call io.out(), or simply use the "this" keyword. Which is great for sibling methods, such as out(), in this case.

    That's as simple as this:
    PHP Code:
    // Print output followed by a line break
    public void outlnString Message )
    {
        
    // Use "this" keyword to refer to a sibling method, out().
        
    this.outMessage "\n" );


    Now then. I also have a new requirement which makes this much trickier. I want it to be possible to use io.outln() with no arguments at all, to print a line break.

    The Problem: Java doesn't really support default arguments. We can use a quick little work around, though, which also adds a pretty cool feature to our little io library.

    We can have an array of strings, which includes null, and multiple arguments. We than use a for() loop to cycle through the given array of strings. Much like a foreach loop in other languages.

    Once we do that, we can use outln("1..", "2..", "3!") to print:
    Code:
    1..
    2..
    3!
    Now then, we need to support outln() as well. It won't print an empty line on it's own, so we need to figure whether or not any input was given, and if not, print an empty line. We wouldn't want to print an extra empty line if input has been given.

    Here's one way it could work:
    PHP Code:

        
    // Prints some output followed by a line break
        
    public void outlnString... Args )
        {
            
            
    // Predefine a boolean to see if there are any args
            
    boolean ran false;
            
            
    // Simulate for-each Message as Args loop
            
    for( String Message Args )
            {
                
    // set boolean, ran, to true.
                
    ran true;
                
                
    // print a message with a line break.
                
    this.outMessage "\n" );
                
                
    // or System.out.println( Message );
                
            
    }
            
            
    // If we haven't printed a message already
            
    if( !ran )
            {
                
    // print a line break [Ex: io.outln(); ]
                
    this.out"\n" );
                
            }
            
        } 
    Now that we have outln() set up the way we want it to be, let's make a new kind of input method. One which takes a string for a message prompting for input, (like "Say something and press enter"), but also returns a string of input (like in() does).

    The difference is, it takes a message, prints a line break, and then returns a string of input. I think I'll name it outin(), since it puts output, then takes input.

    Here's how that could work:
    PHP Code:
        // Prints a message, then returns a line of input.
        
    public String outinString Message )
        {
            
    // Print a Message followed by a line break
            
    this.outlnMessage );
            
            
    // Return a string of input
            
    return this.in();
            
        } 
    You could use this in test_run.java like this:
    PHP Code:
    // Prompt for and take some input
    String input io.outin"Say Something:" );

    // Print an empty line
    io.outln();

    // Display the input
    io.outln"You Said:"input ); 
    Which can be shortened to this:
    PHP Code:
    io.outln"""You Said:"io.outin"Say Something:" ) ); 
    The entire thing:
    Spoiler:

    io.java:
    PHP Code:
    import java.util.Scanner;

    class 
    io {
        
        
    // Returns a line of input
        
    public String in()
        {
            
    // Create Scanner for Input
            
    Scanner in = new ScannerSystem.in );

            
    // Fill input String with a line of data from Input Scanner
            
    String input in.nextLine();

            
    //Close the scanner stream
            
    in.close();
        
            
    // Return the input as a String
            
    return input;
            
        }
        
        
    // Prints a message, then returns a line of input.
        
    public String outinString Message )
        {
            
    // Print a Message
            
    this.outlnMessage );
            
            
    // Return a line of input
            
    return this.in();
            
        }
        
        
    // Prints some output
        
    public void outString Message )
        {
            
    System.out.print( Message );
            
        }
        
        
    // Prints some output followed by a line break
        
    public void outlnString... Args )
        {
            
            
    // Predefine a boolean to see if there are any args
            
    boolean ran false;
            
            
    // Simulate for-each Message as Args loop
            
    for( String Message Args )
            {
                
    // set boolean, ran, to true.
                
    ran true;
                
                
    // print a message with a line break.
                
    this.outMessage "\n" );
                
                
    // or System.out.println( Message );
                
            
    }
            
            
    // If we haven't printed a message already
            
    if( !ran )
            {
                
    // print a line break [Ex: io.outln(); ]
                
    this.out"\n" );
                
            }
            
        }
        

    test_run.java:
    PHP Code:
    class test_run 
    {
        public static 
    void mainString args[] )
        {
            
    // variable (type "io", and named "io") instantiates a new In/Out class
            
    io io = new io();
            
            
    //Prints "Hello, World!", takes input, prints a line, prints "You Said:" and then the input.
            
    io.outln"""You Said:"io.outin"Hello, World!" ) );
            
            
    /*
            String input = io.outin( "Hello, World!" );
            io.outln();
            io.outln( "You Said:" );
            io.outln( input );
            */
        
    }



    Exercise 2.1:
    As an exercise, add to, modify, test, and publish a new io.java class, using a brand new test_run.java class to test and demonstrate the features.

    Here's some ideas (it's encouraged to implement your own ideas, as well):

    Create an input method which takes a single character.
    Create an input method which takes integers.
    Create an input method which supports a custom delimiter (instead of the return/enter key)
    Create a new innovative output method. Consider support for tabular data.


    Exercise 2.2:
    Create a multiplication calculator using your io class from Exercise 2.1. Take any amount of numbers (at least 2). Getting creative and adding extra features is expected, for this exercise.

    You could use integers:
    PHP Code:
    // Integer variable:
    int number 1
    Here's how to multiply:
    PHP Code:
    // multiplication (*):
    int answer 7
    Here's how to convert an integer to a string: (using the built-in Integer's "toString" method)
    PHP Code:
    // an int
    int answer 7;

    // string version of above int
    String display_answer Integer.toStringanswer );

    // print string
    io.outlndisplay_answer );

    //all together now:
    io.outlnInteger.toString) ); 
    Be sure to search google for quick problem-solvers like these.

    If participating in the exercises and you'd like to receive some constructive criticism, feel free to turn in your answers to me as a PM or as a reply to this thread. If in a reply, please enclose your answer into a spoiler so others don't immediately see the answer before getting a chance to try for themselves.

    Previous: [Java] A Console Application (#1)
    Last edited by s-p-n; 10-08-11 at 06:53 PM.
    caja and Darksta like this.

  2. #2
    TeamRev
    Rank
    Member +
    Join Date
    Feb 2010
    Location
    Planet Earth
    Posts
    593
    Liked
    322

    Re: [Java] An IO Class (#2)

    Excellent tutorial, thanks for this!

  3. #3
    Account Upgraded | Title Enabled!
    Rank
    Member +
    Join Date
    Dec 2010
    Location
    Ur Mom's Pants.
    Posts
    939
    Liked
    363

    Re: [Java] An IO Class (#2)

    Good job on this, it's sure to help a lot of beginners :)
    But it was misleading for me haha. Java's IO is very expansive, I was expecting you to cover more advanced concepts. It would have been nice to see a guide that covered Java's byte and char streams, and file reading & writing would have been nice, I'm not too good with that :/
    -Jaws theme song-

  4. #4
    :-)
    Rank
    Alpha Member
    Join Date
    Jun 2007
    Location
    Next Door
    Posts
    2,039
    Liked
    388

    Re: [Java] An IO Class (#2)

    Quote Originally Posted by Sharky View Post
    Good job on this, it's sure to help a lot of beginners :)
    But it was misleading for me haha. Java's IO is very expansive, I was expecting you to cover more advanced concepts. It would have been nice to see a guide that covered Java's byte and char streams, and file reading & writing would have been nice, I'm not too good with that :/
    File IO is next ;)

    The reason I didn't venture into that so much is because this is only the second tutorial in a series, so it would be a little pre-mature.

    Thanks for pointing that out, though.

    Also, for anyone who's wondering why I'm not explaining conditional statements, loops, and variables that much, is because this series of tutorials is for programmers coming from other languages to Java. Therefore, I expect knowledge up to & including Object Oriented Programming in some other language, at least in a basic sense- like PHP, for instance.
    Last edited by s-p-n; 23-05-11 at 05:28 AM.

  5. #5
    Alpha Member
    Rank
    Alpha Member
    Join Date
    Sep 2008
    Location
    United States
    Posts
    1,929
    Liked
    33
    Gamertag: tajdadon

    Re: [Java] An IO Class (#2)

    I see that you've gotten more efficient with Java. Good stuff

  6. #6
    Registered
    Rank
    Member
    Join Date
    Mar 2011
    Posts
    18
    Liked
    0

    Re: [Java] An IO Class (#2)

    this make things clear

  7. #7
    Registered
    Rank
    Member
    Join Date
    Aug 2011
    Location
    BIH Bosnia
    Posts
    15
    Liked
    11

    Re: [Java] An IO Class (#2)

    tnx man great tutorial

  8. #8
    Member
    Rank
    Member
    Join Date
    Jun 2010
    Posts
    92
    Liked
    53

    Re: [Java] An IO Class (#2)

    Close your stream after you're done using it.
    s-p-n likes this.

  9. #9
    :-)
    Rank
    Alpha Member
    Join Date
    Jun 2007
    Location
    Next Door
    Posts
    2,039
    Liked
    388

    Re: [Java] An IO Class (#2)

    Quote Originally Posted by EroticPatches View Post
    Close your stream after you're done using it.
    Ah, thanks for that

  10. #10
    something
    Rank
    Subscriber
    Join Date
    Dec 2007
    Location
    Oslo, Norway
    Posts
    830
    Liked
    13
    Gamertag: Erlendftw Steam ID: superemineem

    Re: [Java] An IO Class (#2)

    Good to see you creating tutorials, i remember reading your tutorials for some time ago.

    This is a very good guide, and in addition to tutorials like this i would recommend the book (not e-book) "Beginning programming with java for dummies" By Barry Burd.

 

 

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •