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 ...
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 out( String 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 main( String 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 Scanner( System.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 out( String 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 outln( String Message ) { system.out.println( Message ); }
.. 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 outln( String Message ) { // Use "this" keyword to refer to a sibling method, out(). this.out( Message + "\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 outln( String... 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.out( Message + "\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 outin( String Message ) { // Print a Message followed by a line break this.outln( Message );
// 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 );
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 = 5 * 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 = 5 * 7;
// string version of above int String display_answer = Integer.toString( answer );
// print string io.outln( display_answer );
//all together now: io.outln( Integer.toString( 5 * 7 ) );
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.
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 :/
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.
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.