Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
29 views

1 - Intro+CommandLevelPrograming - Java

This document provides an introduction to the IFT 360 - Methods of Object-Oriented Design course. It discusses the topics that will be covered, including classes, objects, data structures, and file input/output. It explains that exercises and challenges will be provided to allow students to practice what they are learning. The document also provides guidance on setting up the development environment and compiling/running programs from the command line.

Uploaded by

pmpkm
Copyright
© © All Rights Reserved
Available Formats
Download as PPS, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

1 - Intro+CommandLevelPrograming - Java

This document provides an introduction to the IFT 360 - Methods of Object-Oriented Design course. It discusses the topics that will be covered, including classes, objects, data structures, and file input/output. It explains that exercises and challenges will be provided to allow students to practice what they are learning. The document also provides guidance on setting up the development environment and compiling/running programs from the command line.

Uploaded by

pmpkm
Copyright
© © All Rights Reserved
Available Formats
Download as PPS, PDF, TXT or read online on Scribd
You are on page 1/ 32

LEBANESE CANADIAN UNIVERSITY

IFT 360 - Methods of Object-Oriented Design


Instructor: Johnny Khoury

IFT 360 - Methods of Object-Oriented Design 1


Welcome

 Hi, I'm Johnny Khoury and welcome to IFT 360 - Methods of Object-Oriented
Design course. During this course, we will take a quick tour of a sample
integrated development environment, an IDE, and do a review of important
topics that are specific to Java such as: data types, expressions, decisions,
loops, reading and writing from the console, and using the IDE debugging
feature.
 At the start of the course, we will also learn how to write and run
programs without using an IDE. Next, we will move on to discussing
classes, objects, and data structures.
 Finally, we will work with reading from, and writing to external files using
Java including error handling. Along the way, you will be challenged with
writing programs that include all of the features we'll be discussing. Now, let's
get started with Java Essential Training for Students.
What you should know

 There are a few things you should know before getting started with this
course. This course builds on another course. Up and Running with Java. You
should be familiar with the basic principles of programming such as defining
variables, assigning data types, creating functions and methods, and using
assignment statements.
 Finally, you will need an IDE, or an integrated development environment. If
you do not already have an IDE ready to go, make sure to install one as soon
as possible.
Using the exercise files

 You will have access to the exercise files I use in this course. I will put them
in a folder on LCU learning Moodle. So you can follow along as we explore
various features and tools. I want to note that these files are all just for
convenience. They are required. They will definitely make things a little
easier when you're following along.
Challenges explained

 Throughout this course, you're going to run across several Challenges.


 Challenges are hands on opportunities for you to practice and master what
you're learning throughout the course. At the beginning of each Challenge I'll
give you a clear set of objectives. If there are any sample files, I'll show you
where to find those. And I'll also give you a rough estimate of how long each
Challenge took me to complete as well.
 Once you've completed the Challenge, I will give you the Solution. In that
Solution, I'll show you how I completed the Challenge, and give you some
insight on my thought process along the way. Again, Challenges are great
opportunities for you to practice what you're learning as we progress through
this course. But they are also a chance for you to have some fun as well. And
of course they will be graded.
 So be sure to try them out.
So let’s start
Exploring command level programming
 It is helpful to understand how to compile and run Java programs without using an integrated
development environment (IDE).
 For this section, we will use Brackets as our text editor to write Java code and then compile and run
the programs using the executables available from the Java Development Kit, or the JDK.
 All Java applications are compiled to bytecode that can run on any JVM, or Java Virtual Machine,
regardless of the underlying computer architecture, making it platform independent.
 A Java application can accept any number of arguments from the command line. This allows the user
to specify configuration information when the application is launched.
 To write and test programs using the command prompt, it is important to locate the folder where you
downloaded the Java JDK. This is required to compile and run Java programs on your machine. When
you installed the JDK, along with your IDE such as NetBeans, the default directory for Windows should
look similar to this,
 C:\Program Files\java\jdk1.8.0_281
 We will use this information to set the path variables so we can compile and run our program from
the command line. To open a command prompt, we go to the Windows icon and type CMD.
Highlights

Bytecode
Java Virtual Machine (JVM)
Architecture independent
Arguments from the command line
(CMD)
C:\Program Files\java\jdk1.8.0_281
Introducing environment variables
 Okay, now that we've reviewed the concept of command level programming, let's
dive in and get started with compiling and running our first program from the
command prompt window.
 We'll start by creating a folder on our C drive to store our Java programs for this
activity. Something to remember about the command prompt is that you can get a
complete list of command level options anytime by typing in the keyword help.
 In order to create a new folder, you can use the command md. Before we do that,
you can type in cls. This is a handy command to clear the screen.
 Okay, let's make a new directory. md myJava This is where I'll store the programs
for this activity. Now that I created the folder,
 md myJava
 I need to change the directory to go into that folder. cd myJava
 cd myJava
Introducing environment variables

 Awesome. Now, let's write our first Java program in a text editor.
 I've already downloaded the Brackets application, which is a free text editor that you can
download from the Brackets site. But you can use whatever editor that you're comfortable
with.
 I'll create a new file: File, New. But before entering the code, we should save the file with
a .java extension. That way, the text editor uses the correct indentation for my app.
 File, Save As..., myJava, and we're going to call this Demo.java. Notice the capital D in
Demo, Java's case sensitive. And Save.
 Here's the code that we need to enter into the text editor.
1. We'll start with our class definition. public class Demo Again, capital D.
It has to be the same name as the file name.
2. Now we'll declare our main method, public static void main( In parentheses, we'll identify the
parameters. (String[ ] args) { ,
3. System.out.println("Hello world");
Introducing environment variables

1. public class Demo{


2. public static void main(String[] args)
3. {
4. System.out.println("Hello World");
5. }
6.

7. }
Now we can save this program. Okay, let's go back to the command prompt.
Introducing environment variables

 Before we can start compiling and running the program, we need to make
sure we specify the location of the Java virtual machine and the Java
compiler to enable us to compile and run this program from within our
myJava folder.
 In order to do that, we have to set the path variables as indicated. I already
looked up the version of my JDK, but make sure you do that prior to setting
your path command.
 We'll type in: set path=%path%; Make sure you don't put any spaces before or
after the equal sign. C:\Program Files\Java\jdk1.8.0_281 which is the
version I have on my machine, \bin and then hit Enter.
 c:\myJava>set path=%path%;C:\Program Files\java\jdk1.8.0_281\bin
 One thing to note is that you will need to reset the path every time you close
and reopen your command prompt.
Introducing environment variables

 Alright, we compiled the program using the javac executable, so let's type javac
and the name of our program, Demo.java Again, make sure you use all the right
upper and lower case and you want to include the extension when you compile
the program.
 The compiler compiles the program and creates a class file. A class file contains
the byte code for the program and that's needed for the Java virtual machine.
 Once we have the class file, we can run the program using the JVM, or the Java
virtual machine. So let's hit Enter to compile our program.
 Let's check and make sure it created a class file. We shall use the command dir to
see the elements inside this directory.
 We have Demo.class and Demo.java.
 Okay, let's run the program, we type in java Demo (the name of the class file).
This time, we do not use an extension and right now, I don't have any defaults
arguments being passed to the program so that's all I need to do and hit Enter.
Hey, it says "Hello world."
Conclusion

 We wrote our program using a standard text editor, compiled and ran the
program directly from the command prompt. Using the command prompt is
not difficult, but it does require an understanding of file and folder
structures.
 At the end of this section there's a challenge, so make sure you give it a try.
Have fun!
Getting started with parsing

 In our demo program we did not pass any arguments to the main method.
 There are times when the user needs to enter command line arguments when
invoking the application.
 Let's create a new program to take in a message and then echo back each
string on a separate line.
 In the text editor brackets, we will create a new program and call it
DemoWithArguments.java and save it to our My Java folder on the C drive.
Getting started with parsing

 We'll start by declaring the class, public class DemoWithArguments. Don't


forget, this name has to be the exact same name as the file name.
 Inside the class we should add a main method, public static void main. And
in the parentheses for the main I'll have the argument, an array of strings,
and usually we give it the name A-R-G-S to represent arguments.
 The code for my main method is going to be fairly simple. We are going to use
an advanced for loop to loop through all the values in the A-R-G-S array, and
then print them out.
 So for String s:args open curly bracket System.out.println s.
PS: Don’t forget to close for loop, close main method, and end class.
DemoWithArguments

1. public class DemoWithArguments {


2. public static void main(String[] args)
3. {
4. for(String s:args)
5. {
6. System.out.println(s);
7. }
8. }
9. }
Getting started with parsing

 Now we can go over to the My Java folder in the command prompt. And the first
thing we should do is to make sure the path is set.
 Now we can go ahead and compile the program.
1. Type in javac
2. Give it the name DemoWithArguments.java. Don't forget the .java extension here.
3. Hit enter. And again, if you don't get any errors that mean you are doing good.
4. Run it with the Java virtual machine, you type in the word java space
DemoWithArguments space no extension,
5. Give it an argument. Ex: Welcome to LCU.
6. Hit enter and you can see the program printed out each of the words on a separate
line, Welcome to LCU.
 So when the application was launched the Runtime system passed the command
line arguments to the application's main method via an array of strings.
Getting started with parsing

 Now let's consider the situation where the program needs to read in the
number instead of a string. Because the argument value is in an array of
strings, we need to parse the value which converts the string to a numeric
value.
 In brackets, let's create another program to convert the command line
argument to an integer.
1. File, New,
2. Call this public class NumConversion.
3. Save this out to my folder, Save As, my C drive, My Java,
4. Call it NumConversion.java.
Getting started with parsing

 Inside the class the next thing you need to do is


 add my public static void main String bracket bracket args.
 And inside the main, the first thing to do is
 declare an integer variable called firstArg to represent the first argument.
 give it a default value of zero.
 Now, you should check and make sure that the user did pass an argument, so
check the length of args array.
 If the length is greater than zero, then the user typed in an argument.
 Now, add a try and catch to make sure that the use typed in a number and not a
string.
PS: Don't be concerned if you don't recognize the try catch portion of this
program. This is error handling code that is included later in the course.
Getting started with parsing

 Assign firstArg to the first element in the args array.


 But don't forget, you are expecting an integer.
 type Integer.parseInt parentheses,
 args bracket zero bracket closed parentheses, and a semi colon.
 Close try block,
 Now you should add a catch statement. So if the user did not enter a number, this is what's
gonna happen.
 You should catch the error which will be a NumberFormatException error,
 type in the name of the exception, and I give it a variable name, such as E,
 print out an error message System.err.println,
 Argument plus and I want to print out whatever was in position zero so the user can see what
the problem was. Add must be an integer.
 And if you do encounter an error and you want to get out, so add System.exit and give it a
value of one. That is the end of catch statement.
Getting started with parsing
 If you got through the try and catch without an error you want to echo
back out the number the user entered.
 Type System.out.prntln,
 Put “You entered” and print out the first arg that they entered.
 Close main, Close class.
 Before we actually run it, in this example we used Integer.parseInt to
find the integer portion of the first argument, which will be located in
the array of position zero. If the value entered by the user is not an
integer remember the parseInt method throws a number format
exception error, which is why we have the try and catch logic in our
program. If the value is valid it's stored in the first arg variable and
then printed back to the console.
Getting started with parsing
1. public class NumConversion {

2. public static void main(String[] args)

3. {

4. int firstArg = 0;

5. if(args.length >0)

6. {

7. try{

8. firstArg = Integer.parseInt(args[0]);

9. }

10. catch(NumberFormatException e) {

11. System.err.println("Argument " + args[0] + " must be an integer");

12. System.exit(1);

13.

14. }

15. System.out.println("You entered "+firstArg);

16. }

17. }

18. }
Getting started with parsing

 Try the new program, both with a valid


numeric argument, and again, with a string.
Before you do that, you have to compile it.
 So in My Java
 type javac space NumConversion.java.
 run the program.
 java space NumConversion.
 Remember, to give it a value.
Getting started with parsing

 Let's start by giving it a valid value of one two three four five(12345).
 Now let's see what happens if you run it again, but this time you forgot, and you
give it a string(Hello).
 This time your program caught the error, and it says, Argument Hello must be an
integer. In this example we were expecting the user to enter an integer, but the
program can handle all types of numeric arguments by calling the parse method.
 Depending on the data type, this string can be parsed into a numeric object such
as integer, which is what we used in this program, double, float, etcetera. These
objects are called wrapper classes. Every permanent data type has a
corresponding wrapper class that can be used to create an object with a
numerical value of the argument. We will talk more about the numeric wrapper
classes later in the course. For the remainder of our program and examples,
except for the debugging section, we will be using the net beans IDE.
Challenge: Hello world

Let's look at our first challenge. In this challenge you should use a text editor to write
a Java program. I use brackets but Notepad++ or even Notepad would work just fine.
The program should take in a string prompt as an argument. Then it's going to print
that back to the screen. The prompt message should ask the user to enter their name
and their age. Use the Scanner class to read in the name as a string and the age as an
integer. Using this information, display the information back to the console. Once
your program is written make sure to save the program to your myJava folder on the
C: drive. Don't forget to set your environment variables before trying to compile
the .java file. Go ahead and compile it using the command line. javac, space, your
program name, .java. And finally you can run it using the java command. Run the
program from the command line. Don't forget to include your message after the
program name. I'm estimating that this will take you about 10 minutes to do. So go
ahead and give it a try. Good luck and have fun.
Challenge Objectives

 Write a program using a text editor. ( Brackets, Notepad, Notepad++)


 Read a string prompt as a n argument.
 The prompt asks for user name and age
 Use Scanner to read name and age.
 Save program to myJava directory.
 Set environment variables.
 Compile using the command line.
 Run program from the command line.
Challenge Solution

 import java.util.Scanner;
 public class NameAndAge {
 public static void main(String[] args)
 {
 String prompt = args[0];
 System.out.println(prompt);
 String name;
 int age;
 Scanner in = new Scanner(System.in);
 name = in.nextLine();
 age = in.nextInt();
 System.out.println("Hello, "+name + " nice to meet you\nYou are "
 +age+" years old!");
 }
 }
Chapter Quiz

 Question 1 of 3

 A Java application can accept any number of arguments from the command
line.
a) True
b) False
Chapter Quiz

 Question 2 of 3

 To compile a Java program from the command line, the _____ environment
variable must be set to the bin folder in the jdk directory.
a) Java
b) Path
c) Location
d) Jdk
Chapter Quiz

 Question 3 of 3

 Which command is used to find an integer argument when reading from the
command line?
a) Int.parseInt(args[0]).
b) Int.parseInteger(args[0])
c) Integer.parseInt(args[0])
d) parseInteger(args[0])
THANK YOU

You might also like