Java Option Panes
Another useful class for accepting user input, and displaying results, is the JOptionPane class. This is located in the javax.swing library. The JOptionPane class allows you to have input boxes like this one:The first thing to do is to reference the library we want to use:
import javax.swing.JOptionPane;
This tells java that we want to use the JOptionPane class, located in the javax.swing
library.You can start a new project for this, if you prefer not to adapt your previous code. (You should know how to create a new project by now. Just remember to change the name of the Class from Main to something else. We're going to have the class name InputBoxes for ours. Our package name will be userinput.)
Add the import line to your new project, and your code window should look like something like this:
To get an input box that the user can type into, we can use the showInputDialog method of JOptionPane. We'll store the input straight into a first name variable again, just like last time. So add the following line to your main method:
String first_name;
first_name = JOptionPane.showInputDialog("First Name");
As soon as you type a full stop after JOptionPane you will see the following popup list:
Add the following code so that we can get the user's family name:
String family_name;
family_name = JOptionPane.showInputDialog("Family Name");
Join the two together, and add some text:
String full_name;
full_name = "You are " + first_name + " " + family_name;
To display the result in a message box, add the following:
JOptionPane.showMessageDialog( null, full_name );
This time, we want showMessageDialog from the popup list. In between
the round brackets we first have the word null. This is a java keyword
and just means that the message box is not associated with anything else in
the programme. After a comma comes the text we want to display in the message
box. The whole of your code should look like this:
System.exit(0);
As its name suggests, this ensures that the programme exits. But it also tidies
up for us, removing all the created objects from memory.Now run your code. (Another quick way to run your programme in NetBeans is by right-clicking anywhere inside of the coding window. From the menu that appears, select Run File.)
You'll see the First Name input box. Type something into it, then click OK:
Exercise
Input boxes and Message boxes can be formatted further. Try the following for your Input boxes:
showInputDialog("First Name", "Enter
Your First Name");
showInputDialog("Family", "Enter Your
Family Name");
Exercise
For your Message boxes try this (yours should be on one line):
showMessageDialog(null, full_name, "Name",
JOptionPane.INFORMATION_MESSAGE);
Exercise
Instead of JOptionPane.INFORMATION_MESSAGE try these:
ERROR_MESSAGE
PLAIN_MESSAGE
QUESTION_MESSAGE
WARNING_MESSAGE
ExercisePLAIN_MESSAGE
QUESTION_MESSAGE
WARNING_MESSAGE
Input boxes are not just used for text: they can accept numbers as well. Write a programme that prompts the user for two numbers, the breadth of a rectangle and the height of a rectangle. Use a message box to calculate the area of the rectangle. (Remember: the area of a rectangle is its breadth multiplied by the height.) However, you'll need some extra help for this exercise.
Help for the Exercise
You have to use the String variable to get your numbers from the user:
String breadth;
breadth = JOptionPane.showInputDialog("Rectangle Breadth");
However, you can't multiply two strings together. You need to convert the Strings to integers. You can convert a string to an integer like this:
Integer.parseInt( string_to_convert )
So you type Integer then a full stop. After the stop, type parseInt( ). In
between the round brackets of parseInt, type the name of the string variable
you're trying to convert.Set up an int variable for the area. You can then multiply and assign on the same line;
int area = Integer.parseInt( string_one ) * Integer.parseInt(
string_two);
For the message box, use concatenation:
"answer = " + area
You can use any of the MESSAGE symbols for your message box.Exercise
The programme will crash if you enter floating point values for the breadth and height. How would you solve this?
When you have solved the above exercise, do you really want Integer.parseInt? What else do you think you can use?
OK, we'll move on now. Let's try some IF statements.
Accepting Input from a User
One of the strengths of Java is the huge libraries of code available to you. This is code that has been written to do specific jobs. All you need to do is to reference which library you want to use, and then call a method into action. One really useful class that handles input from a user is called the Scanner class. The Scanner class can be found in the java.util library. To use the Scanner class, you need to reference it in your code. This is done with the keyword import.
import java.util.Scanner;
The import statement needs to go just above the Class statement:
import java.util.Scanner;
public class StringVariables {
}
This tells java that you want to use a particular class in a particular library - the Scanner class, which is located in the java.util library.
The next thing you need to do is to create an object from the Scanner class. (A class is just a bunch of code. It doesn't do anything until you create a new object from it.)
To create a new Scanner object the code is this:
Scanner user_input = new Scanner( System.in );
So instead of setting up an int variable or a String variable,
we're setting up a Scanner variable. We've called ours user_input.
After an equals sign, we have the keyword new. This is used to create
new objects from a class. The object we're creating is from the Scanner class.
In between round brackets we have to tell java that this will be System Input
(System.in).To get the user input, you can call into action one of the many methods available to your new Scanner object. One of these methods is called next. This gets the next string of text that a user types on the keyboard:
String first_name;
first_name = user_input.next( );
So after our user_input object we type a dot. You'll then see a popup list of available methods. Double click next and then type a semicolon to end the line. We can also print some text to prompt the user:
String first_name;
System.out.print("Enter your first name: ");
first_name = user_input.next( );
Notice that we've used print rather than println like last time. The difference between the two is that println will move the cursor to a new line after the output, but print stays on the same line.
We'll add a prompt for a family name, as well:
String family_name;
System.out.print("Enter your family name: ");
family_name = user_input.next( );
This is the same code, except that java will now store whatever the user types into our family_name variable instead of our first_name variable.
To print out the input, we can add the following:
String full_name;
full_name = first_name + " " + family_name;
System.out.println("You are " + full_name);
We've set up another String variable, full_name. We're storing whatever is in the two variables first_name and family_name. In between the two, we've added a space. The final line prints it all out in the Output window.
So adapt your code so that it matches that in the next image:
After you hit the enter key, java will take whatever was typed and store it in the variable name to the left of the equals sign. For us, this was the variable called first_name.
The programme then moves on to the next line of code:
In the next part, we'll take a brief look at Option Panes.
String Variables
As well as storing number values, variables can hold text. You can store just one character, or lots of characters. To store just one character, the char variable is used. Usually, though, you'll want to store more than one character. To do so, you need the string variable type.Start a new project for this by clicking File > New Project from the menu bar at the top of NetBeans. When the New Project dialogue box appears, make sure Java and Java Application are selected:
String first_name;
Assign a value to your new string variable by typing an equals sign. After
the equals sign the text you want to store goes between two sets of double quotes:
first_name = "William";
If you prefer, you can have all that on one line:
String first_name = "William";
Set up a second string variable to hold a surname/family name:
String family_name = "Shakespeare";
To print both names, add the following println( ):
System.out.println( first_name + " " +
family_name );
In between the round brackets of println, we have this:
first_name + " " + family_name
We're saying print out whatever is in the variable called first_name.
We then have a plus symbol, followed by a space. The space is enclosed in double
quotes. This is so that Java will recognise that we want to print out a space
character. After the space, we have another plus symbol, followed by the family_name
variable.Although this looks a bit messy, we're only printing out a first name, a space, then the family name. Your code window should look like this:
String first_name = "W";
But this is not:
String first_name = 'W';
The second version has single quotes, while the first has double quotes.There are lot more to strings, and you'll meet them again later. For now, let's move on and get some input from a user.
Operator Precedence
You can, of course, calculate using more than two numbers in Java. But you need to take care of what exactly is being calculated. Take the following as an example:first_number = 100;
second_number = 75;
third_number = 25;
answer = first_number - second_number + third_number;
If you did the calculation left to right it would be 100 - 75, which is 25.
Then add the third number, which is 25. The total would be 50. However, what
if you didn't mean that? What if you wanted to add the second and third numbers
together, and then deduct the total from the first number? So 75 + 25, which
is 100. Then deduct that from the first number, which is 100. The total would
now be 0.To ensure that Java is doing what you want, you can use round brackets. So the first calculation would be:
answer = (first_number - second_number) + third_number;
Here's the coding window so that you can try it out:
answer = first_number - (second_number + third_number);
And here's the code window:Change your math symbols (called Operators) to plus and multiply:
answer = first_number + second_number * third_number;
Delete all your round brackets, and then run your programme.With no brackets, you'd think Java would calculate from left to right. So you'd think it would add the first number to the second number to get 175. Then you'd think it would multiply by the third number, which is 25. So the answer would be 4375. Run the programme, though. The answer that you actually get is 1975! So what's going on?
The reason Java got the "wrong" answer was because of Operator Precedence. Java treats some mathematical symbols as more important than others. It sees multiplication as having a priority over addition, so it does this first. It then does the addition. So Java is doing this:
answer = first_number + (second_number * third_number);
With the round brackets in place, you can see that second number is being multiplied
by third number. The total is then added to the first number. So 75 multiplied
by 25 is 1875. Add 100 and you get 1975.If you want it the other way round, don't forget to "tell" Java by using round brackets:
answer = (first_number + second_number) * third_number;
Division is similar to multiplication: Java does the dividing first, then the
addition or subtraction. Change your answer line to the following:
answer = first_number + second_number / third_number;
The answer you get is 103. Now add some round brackets:
answer = (first_number + second_number) / third_number;
The answer this time will be 7. So without the round brackets, Java does the
dividing first, and then adds 100 to the total - it doesn't work from left to
right.Here's a list on Operator Precedence
- Multiply and Divide - Treated equally, but have priority over Addition and Subtraction
- Add and Subtract - Treated equally but have a lower priority than multiplication and division
In the next part, we'll take a look at how to store text values using Java.
Short and Float Variables
Two more variable types you can use are short and float. The short variable type is used to store smaller number, and its range is between minus 32,768 and plus 32,767. Instead of using int in our code on the previous pages, we could have used short instead. You should only use short if you're sure that the values that you want to hold don't go above 32, 767 or below -32,768.The double value we used can store really big numbers of the floating point variety. Instead of using double, float can be used. When storing a value in a float variable, you need the letter "f" at the end. Like this:
float first_number, second_number,
answer;
first_number = 10.5f;second_number = 20.8f;
So the letter "f" goes after the number but before the semicolon at the end of the line. To see the difference between float and double, see below.
Simple Arithmetic
With the variables you've been using, you can use the following symbols to do calculations:+ (the plus sign)
- (the minus sign)
* (the multiplication sign is the asterisk sign)
/ (the divide sign is the forward slash)
Try this exercise:
Delete the plus symbol that is used to add first_number and second_number. Replace it with the symbols above, first the minus sign, then the multiplication sign, and then the divide. The answer to the final one, the divide, should give you a really big number.
The number you should get for divide is 0.5048076923076923. This is because you used the double variable type. However, change the double to float. Then add the letter "f" to the end of the numbers. So your code should look like this:
In the next lesson, you'll learn about the importance of Operator Precedence.
The Double Variable
The double variable can hold very large (or small) numbers. The maximum and minimum values are 17 followed by 307 zeros.The double variable is also used to hold floating point values. A floating point value is one like 8.7, 12.5, 10.1. In other words, it has a "point something" at the end. If you try to store a floating point value in an int variable, NetBeans will underline the faulty code. If you try to run the programme, the compiler will throw up an error message.
Let's get some practise using doubles.
Change the int from your previous code to double. So change this:
int first_number, second_number,
answer;
to this:
double first_number, second_number,
answer;
Now change the values being stored:first_number = 10.5;
second_number = 20.8;
Leave the rest of the programme as it is. Your coding window should look like this:
In the next part, you'll learn about two more Java variable types: short and float.
Java integer Variables
Programmes work by manipulating data placed in memory. The data can be numbers, text, objects, pointers to other memory areas, and more besides. The data is given a name, so that it can be re-called whenever it is need. The name, and its value, is known as a Variable. We'll start with number values.To store a number in java, you have lots of options. Whole numbers such as 8, 10, 12, etc, are stored using the int variable. (The int stands for integer.) Floating point numbers like 8.4, 10.5, 12.8, etc, are stored using the double variable. You do the storing with an equals sign ( = ). Let's look at some examples (You can use your FirstProject code for these examples).
To set up a whole number (integer), add the following to the main method of your project from the previous section:
public static void main(String[
] args) {
int first_number;
System.out.println("My First Project");
}So to tell Java that you want to store a whole number, you first type the word int, followed by a space. You then need to come up with a name for your integer variable. You can call them almost anything you like, but there are a few rules:
- Variable names can't start with a number. So first_number is OK, but not 1st_number. You can have numbers elsewhere in the variable name, just not at the start.
- Variable names can't be the same as Java keywords. There are quite a lot of these, and they will turn blue in NetBeans, like int above.
- You can't have spaces in your variable names. The variable declaration int first number will get you an error. We've used the underscore character, but it's common practise to have the first word start with a lowercase letter and the second or subsequent words in uppercase: firstNumber, myFirstNumber
- Variable names are case sensitive. So firstNumber and FirstNumber are different variable names.
public static void main(String[
] args) {
int first_number;
first_number = 10;
System.out.println("My First Project");
}
So this tells java that we want to store a value of 10 in the integer variable
that we've called first_number.If you prefer, you can do all this on one line:
public static void main(String[
] args) {
int first_number = 10;
System.out.println("My First Project");
}
To see all this in action, change the println method slightly to this:
System.out.println( "First number = " + first_number
);
What we now have between the round brackets of println is some direct text
enclosed in double quotes:
("First number = "
We also have a plus sign, followed by the name of our variable:
+ first_number );
The plus sign means "join together". So we're joining together the
direct text and the name of our variable. The joining together is known as concatenation.Your coding window should now look like this (note how each line of code ends with a semicolon):
Let's try some simple addition. Add two more int variables to your code, one to store a second number, and one to store an answer:
int first_number, second_number,
answer;
Notice how we have three variable names on the same line. You can do this in
Java, if the variables are of the same type (the int type, for us). Each
variable name is then separated by a comma.We can then store something in the new variables:
first_number = 10;
second_number = 20;
answer = first_number + second_number;
For the answer variable, we want to add the first number to the second number. Addition is done with the plus ( + ) symbol. Java will then add up the values in first_number and second_number. When it's finished it will store the total in the variable on the left of the equals sign. So instead of assigning 10 or 20 to the variable name, it will add up and then do the assigning. In case that's not clear, here's what happens:
answer = 10 + 20;
But Java already knows what is inside of the two variables, first_number and
second_number, so you can just use the names.Now change your println method slightly to this:
System.out.println("Addition Total = " + answer
);
Again, we are combining direct text surrounded by double quotes with a variable
name. Your coding window should look like this:- Stored one number
- Stored a second number
- Added these two numbers together
- Stored the result of the addition in a third variable
- Printed out the result
answer = first_number + second_number + 12;
Run your programme again. What printed out? Was it what you expected?You can store quite large numbers in the int variable type. The maximum value is 2147483647. If you want a minus number the lowest value you can have is -2147483648. If you want larger or smaller numbers you can use another number variable type: double. You'll meet them in the next part of the course.
Sharing your Java Programmes
You can send your programmes to other people so that they can run them. To do that, you need to create a JAR file (Java Archive). NetBeans can do all this for you. From the Run menu at the top, select Clean and Build Main Project.When you do, NetBeans saves your work and then creates all the necessary files. It will create a folder called dist and place all the files in there. Have a look in the place where your NetBeans projects are and you'll see the dist folder:
Now that you know how to run your java source files, let's do some programming.
Printing to the Output Window
You can run the code you have so far, and turn it into a programme. It doesn't do anything, but it will still compile. So let's add one line of code just so that we can see how it works.We'll output some text to a console window. Add the following line to your main method:
public static void main(
String[ ] args ) {
System.out.println( "My First Project"
);
}
When you type the full stop after "System", NetBeans will try to
help you by displaying a list of available options:Notice that the line ends in a semicolon. Each complete line of code in Java needs a semicolon at the end. Miss it out and the programme won't compile.
OK, we can now go ahead and test this programme out. First, though, save your work. You can click File > Save, or File > Save All. Or click the Save icon on the NetBeans toolbar.
To end this section, click below to learn how to share your Java programmes with others.
Running your Java Programmes
When you run a programme in NetBeans, it will run in the Output window at the bottom of your screen, just underneath your code. This is so that you don't have to start a terminal or console window - the Output window IS the console.There are various ways to run your programme in NetBeans. The easiest way is to press F6 on your Keyboard. You can also run programmes using the menus as the top of NetBeans. Locate the Run menu, then select Run Main Programme:
The Structure of Java Code
In the previous section, you tidied up your code a bit. Here's what your coding window should look like now:
package firstproject;
The class name comes next:
public class FirstProject
{
}
You can think of a class as a code segment. But you have to tell Java where
code segments start and end. You do this with curly brackets. The start of a
code segment is done with a left curly bracket { and is ended with a right curly
bracket }. Anything inside of the left and right curly brackets belong to that
code segment.What's inside of the left and right curly brackets for the class is another code segment. This one:
public static void main(
String[ ] args ) {
}
The word "main" is the important part here. Whenever a Java programme starts, it looks for a method called main. (A method is just a chunk of code. You'll learn more about these later.) It then executes any code within the curly brackets for main. You'll get error messages if you don't have a main method in your Java programmes. But as its name suggest, it is the main entry point for your programmes.
The blue parts before the word "main" can be ignored for now.
(If you're curious, however, public means that the method can be seen outside of this class; static means that you don't have to create a new object; and void means it doesn't return a value - it just gets on with it. The parts between the round brackets of main are something called command line arguments. Don't worry if you don't understand any of that, though.)
The important point to remember is that we have a class called FirstProject. This class contains a method called main. The two have their own sets of curly brackets. But the main chunk of code belongs to the class FirstProject.
In the next part, you'll learn how to run your Java programmes.
Java Comments
When you create a New Project in NetBeans, you'll notice that some text is greyed out, with lots of slashes and asterisks:The greyed-out areas are comments. When the programme runs, comments are ignored. So you can type whatever you want inside of your comments. But it's usual to have comments that explain what is you're trying to do. You can have a single line comment by typing two slashes, followed by your comment:
//This is a single line comment
If you want to have more than one line, you can either do this:
//This is a comment spreading
//over two lines or more
Or you can do this://over two lines or more
/*
This is a comment spreading
over two lines or more
*/
In the comment above, note how it starts with /*. To end the comment, we have
*/ instead.This is a comment spreading
over two lines or more
*/
There's also something called a Javadoc comment. You can see two of these in the coding image on the previous page. A Javadoc comment starts with a single forward slash and two asterisks (/**) and ends with an asterisk and one slash ( */ ). Each line of the comment starts with one asterisk:
/**
*This is a Javadoc comment
*/
Javadoc comments are used to document code. The documented code can then be
turned into an HTML page that will be helpful to others. You can see what these
look like by clicking Run from the menu at the top of NetBeans. From the Run
menu, select Generate Javadoc. There's not much to see, however, as you haven't
written any code yet!*This is a Javadoc comment
*/
At this stage of your programming career, you can delete the comments that NetBeans generates for you. Here's our code again with the comments deleted:
The NetBeans Software
You may have to drum your fingers and wait a while, as it's not the fastest thing in the world.
To start a new project, click on File > New Project from the NetBeans menu at the top. You'll see the following dialogue box appear:
firstproject.Main
If we leave it like that, the Class will have the name Main. Change it to FirstProject:The default location to save your projects appears in the Project Location text box. You can change this, if you prefer. NetBeans will also create a folder with your project name, in the same location. Click the Finish button and NetBeans will go to work creating all the necessary files for you.
When NetBeans returns you to the IDE, have a look at the Projects area in the top left of the screen (if you can't see this, click Window > Projects from the menu bar at the top of the software):
The coding window that appears should look like this (we've changed the author's name):
public class FirstProject {
This is the same name as the java source file in the project window:
FirstProject.java. When you run your programmes, the compiler
demands that the source file and the class name match. So if your
.java file is called firstProject but the class is called
FirstProject then you'll get an error on compile. And all because
the first one is lowercase "f" and the second one uppercase.Note that although we've also called the package firsproject, this is not necessary. We could have called the package someprogramme. So the name of the package doesn't have to be the same as the java source file, or the class in the source file: it's just the name of the java source file and the name of the class that must match.
In the next part, you'll learn about Java comments.
Before starting Java
One of the difficult things about getting started with Java is installing everything you need. Even before you write a single line of code, the headaches begin! Hopefully, the following sections will make life easier for you.We're going to write all our code using a free piece of software called NetBeans. This is one of the most popular IDEs (Interface Development Environment) in the world for writing Java programmes. You'll see what it looks like shortly. But before NetBeans will work, it needs you to install the necessary Java components and files. First up is something called the Java Virtual Machine.
The Java Virtual Machine
Java is platform independent. This means that it will run on just about any operating system. So whether your computer runs Windows, Linux, Mac OS, it's all the same to Java! The reason it can run on any operating system is because of the Java Virtual Machine. The Virtual Machine is a programme that processes all your code correctly. So you need to install this programme (Virtual Machine) before you can run any Java code.Java is owned by a company called Sun Microsystems, so you need to head over to Sun's website to get the Java Virtual Machine, also known as the Java Runtime Environment (JRE). Try this page first:
You can check to see if you already have the JRE on your computer by clicking the link "Do I have Java?". You'll find this link under the big Download button at the top of the page. (Unless Sun have changed things around, again!) When you click the link, your computer will be scanned for the JRE. You will then be told whether you have it or not. If not, you'll be given the opportunity to download and install it.
Or you could just head over to this page:
The "manual" in the above links means "manual download". The page gives you download links and instructions for a wide variety of operating systems.
After downloading and installing, you may need to restart you computer. When you do, you will have the Java Virtual Machine.
The Java Software Development Kit
At this stage, you still can't write any programmes. The only thing
you've done is to install software so that Java programmes can be
run on your computer. To write code and test it out, you need
something called a Software Development kit. Java's Software Development Kit can currently be downloaded from here:
The one we're going to be using is called Java SE. (The SE stands for Standard Edition.). Click on that link, then on "Java SE (JDK) 7 Download". You'll then find yourself on a page with a bewildering list of options to download. Because we're going to be using NetBeans, locate this:
JDK 7 Update X with NetBeans 7.x
Click the Download link to be taken to yet another page. Click the
top download to be taken to a page that asks you to select your
operating system. Click Continue to finally get the download you
need. A word of warning, though - this download will be big, at over
a 130 megabytes at the time of writing! Once you've downloaded the
JDK and NetBeans, install it on your computer. We're going to be using NetBeans to write our code. Before launching the software, however, here's how things work in the world of Java.
How things work in Java
You write the actual code for your programmes in a text editor. (In NetBeans, there's a special area for you to write code.) The code is called source code, and is saved with the file extension .java. A programme called Javac is then used to turn the source code into Java Byte Code. This is known as compiling. After Javac has finished compiling the Java Byte Code, it creates a new file with the extension .class. (At least, it does if no errors are detected.) Once the class file has been created, it can be run on the Java Virtual Machine So:- Create source code with the extension .java
Use Javac to create (compile) a file ending in .class
Run the compiled class
Now that you have a general idea of how Java works, launch your NetBeans software. Then click the next link to continue with the lesson
Subscribe to:
Posts
(
Atom
)
No comments :
Post a Comment