+ All Categories
Home > Documents > JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE...

JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE...

Date post: 14-Dec-2015
Category:
Upload: norah-griffith
View: 226 times
Download: 1 times
Share this document with a friend
Popular Tags:
55
JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.
Transcript
Page 1: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

JAVA PROGRAMMING WITH ECLIPSE PART 1PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

Page 2: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

DOWNLOAD AND INSTALL SOFTWARE

Install Java JDK 8 (JDK: Java Development Kit)

Install Eclipse IDE for Java Developers Eclipse is a IDE: Integrated Development Environment to write Java code

in.

Both Java and Eclipse are supported on Windows and OSX

Download links are provided on the MSE101 ACCESS Website

Page 3: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

POSSIBLE ASSIGNMENTS

Possible Assignments

http://www.java-made-easy.com/fun-java-game.html

Create a Java Class that takes in a user input

Page 4: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

SECTION 1

THE STEPS FOR CREATING & RUNNING A JAVA PROGRAM

A program is a sequence of instructions that perform a task.

4

Page 5: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

STEPS FOR CREATING & RUNNING A PROGRAM

1. Write the source code in a “anyFileName.java” file. Note the .java extension.

2. The javac program will Compile the source code into byte code creating a .class file

3. JVM (Java Virtual Machine) will interprets the byte code into machine language 1s and 0s and the computer then executes the instructions

5

Page 6: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

SOURCE CODE IS WRITTEN IN A .JAVA FILE

Step1. When a programmer writes Java code, it is stored in a source code file that

has a .java extension like SampleCode.java.

The source code file is what the programmer compiles and runs to see the output of

a program. We will write our Java progams in the IDE software called Eclipse. IDE

stands for Integrated Development Environment. An IDE lets you write, compile,

and execute programs.

Source code can be typed in any simple text editor, but we will use Eclipse, which is

both a text editor and a compiler.

Eclipse is a nice Java editor and compiler because it will point out syntax errors when

java code is typed incorrectly. A program will not run until all syntax errors are

removed. 6

Page 7: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

SOURCE CODE IS COMPILED TO BYTE CODE

Step 2. An IDE (Integrated Development Environment) like Eclipse, has a built in compiler that translates the Java source code into Java byte code.

When source code is compiled into byte code, the byte code is stored in a file that has the same name as the source code file but with a .class extension. It is not a text file and you cannot open it! For example, the source code file RobotMan.java will be compiled into a byte code file named RobotMan.class.

The file is created during the compiling process, however, Eclipse sometimes translates .java files into .class files behind the scenes before you ever compile them. You can see these files in your package folders if you open your workspace folder on your hard drive. 7

Page 8: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

BYTE CODE IS INTERPRETED TO MACHINE CODE

Step 3. The JVM (Java Virtual Machine) must interpret the byte code into machine language. Interpret basically means to translate. The JVM is software that acts like hardware. That is why it is called a virtual machine. Java bytecodes are translated on the fly to 1s and 0s instead of being stored in an executable file, which some languages do. The main advantage of an interpreter is that it will run on any computer and there are JVMs for Apple and Windows machines. This makes the code portable from one platform to another.

Every kind of computer, whether it is an Apple, Windows, or Unix machine, has an operating system that contains a JVM software component. The JVM was automatically installed when your computer’s system software was installed and updates to the JVM may be contained in any system software updates you install now or in the future. 8

Page 9: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

WHAT ARE APPLETS?

Applets are small Java programs that are embedded in web pages. When you

load a web page that has a game in it, the game is an applet.

More specifically, the applet is usually a jar file that contains the byte code for all

the .java files that are needed for the game. A jar file is like a zip file, where a

number of files are compressed into one file.

An HTML web page can contain a special kind of tag called an Applet tag. That

tag tells the web page that the byte code is stored in a jar file with a specific

name.

The browser software, like FireFox, Chrome, Camino, or Safari will then use its

built-in JVM interpreter to translate the byte code into machine language 1s and

0s. 9

Page 10: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

JUST-IN-TIME COMPILATION BY THE JVM

Some JVMs support just-in-time compilation (JIT). JITs will

translate byte code instructions the first time they are

encountered into machine language code and that code is

saved so that the next time that code is encountered it

can be executed without being re-interpreted. This can

speed up the interpreting of the byte code of a program so

it will run faster.

10

Page 11: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

MACHINE LANGUAGE CODE IS EXECUTED

Step 4. Finally, the machine language code (patterns of 1s and 0s), those instructions that the computer understands at the lowest level, are executed. This allows the program to appear in its runnable form, either in a console window, an applet window, or a GUI (Graphical User Interface) window. Again the overall process is ….

11

Page 12: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

SECTION 2

FRAMEWORK OF A SIMPLE JAVA PROGRAM

1. PACKAGE DECLARATION

2. IMPORT STATEMENTS

3. CLASS DECLARATION LINE

4. MAIN METHOD

12

Page 13: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

FRAMEWORK OF A SIMPLE JAVA PROGRAMThe Framework (in order) of a simple console or standalone program:

1. package declaration for the file listed first (where it is stored)

2. followed by import statements (if any)

3. class declaration line

4. main method

import java.util.Scanner;

public class DistanceCalculator

{ // opening curly brace for the DistanceCalculator class

public static void main(String args[ ])

{ // opening curly brace for main method

// code for program goes inside these curly braces

} // ending curly brace for main method

} // ending curly brace for the DistanceCalculator class

All Java console and JFrame (standalone) programs have this framework. The framework for applets is different and you will become familiar with it later.

Note:

• Curly braces always appear in pairs.

• All comments start with two slashes //

Sample Skeleton Program

13

Page 14: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

CLASSES IN JAVAA Java program can use more than one class file (a .java file). In fact, it may be made up of

many .java files.

And most of the time, every .java source code file in a Java program contains only one class.

However, it is possible to have more than one class in a .java file, but this is usually done in more advanced programming projects where the code is more complicated and there is a reason for doing it.

So assume that every .java file contains only one class, but a java program can use one or more .java files.

A class is a module of code that can stand alone by itself and if made “public” other files can “see it” and “access parts of it”. Eclipse is a nice IDE for organizing Java files so that classes are accessible to each other if they are in the same package folder or if an appropriate import statement is used to direct Eclipse to where a package is located. Eclipse manages this behind the scenes automatically and lets you know if something is “unorganized”, so you can fix it.

14

Page 15: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

DECLARING CLASSES IN A FILE

A class is declared with a line like:

public class RobotMan

and has a set of curly braces that go with it { and }.

In Java, a class like RobotMan must be stored in a file named RobotMan.java. If they don’t match, then Eclipse or any other IDE will flag it with an error and it must be corrected before the file is used in a program. Eclipse has short cuts to renaming the file (compilation unit) or the class if necessary. You’ll learn about that soon.

Simple Java programs can be designed so that they contain just one class. We will now look at some examples. 15

Page 16: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

SECTION 3

THREE TYPES OFJAVA PROGRAMS

16

Page 17: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

THREE TYPES OF JAVA PROGRAMS

There are basically three types of Java programs that a programmer can make:

1. A console text output program.

2. A standalone graphics or GUI program that can be

displayed in a standard window frame.

3. An applet graphics or GUI program that is embedded in a

web page.

17

Page 18: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

CONSOLE TEXT OUTPUT PROGRAMS

Some Java programs, like RobotMan, are displayed only in a console window, because they show only text output. You will learn how to do more than draw things with text characters in a console window. Some programs may make mathematical calculations and display them.

18

Page 19: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

GRAPHICS & GUI PROGRAMS

Besides console text programs, you can have applet or standalone programs that contain graphics or GUI components:

1. GUI components are elements in a program like text fields, buttons, labels, text areas, or menus.

2. Graphics are lines, and curves, and pretty much anything that can be drawn.

So you can have:

3. A web applet program with GUI components.

4. A web applet program with graphics.

5. A standalone program with GUI components.

6. A standalone program with graphics.

7. A web applet or standalone program that has both GUI components and graphics.

19

Page 20: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

APPLET GUI OUTPUT PROGRAMS

Java applets are small Java programs downloaded from web pages that run in a Web browser. A JVM is incorporated into every browser, so the applet can be interpreted, executed and displayed inside the browser. Both applet and standalone programs can have GUI components.

A GUI program with fields, buttons, labels, and a text area. 20

Page 21: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

SECTION 4DATA TYPES AND THE BASICS

OF INPUT AND OUTPUTIn this section, you will learn some very important information about:

1. print and println Statements

2. Variables

3. Simple data types

4. The assignment operator =

5. How to declare and construct a Scanner object so you can read input from the keyboard

6. The new operator

21

Page 22: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

JAVA IS HOT SOURCE CODE

public class JavaIsHot

{

public static void main(String args[ ])

{

System.out.println( " d ");

System.out.println( " o l ");

System.out.println( " l r ");

System.out.println( " l o ");

System.out.println( " e w ");

System.out.println( " H ");

System.out.println( " xxxxxxxxxxxxxxxxx ");

System.out.println( " x x x ");

System.out.println( " x Java x x ");

System.out.println( " x xxxx ");

System.out.println( " x is Hot! x ");

System.out.println( " x x ");

System.out.println( " xxxxxxxxxxxxxx ");

} // end of main method

} // end of JavaIsHot class

System.out.println statements are used to print text to the console output window.

22

Page 23: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

PRINT AND PRINTLN STATEMENTS

Output to a console text window in Java is accomplished through the use of print and println (pronounced print-line) statements.

print and println are two operations (or as we say in Java) … methods that can be called. These operations output text information to the console window in Eclipse.

We call methods when we want to accomplish some operation or task.

23

Page 24: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

PRINT AND PRINTLN STATEMENTS

Here are lines of code that call the two methods print and println:

1. System.out.print(“Hello World”);

2. System.out.println(“Hello World”);

Think of methods as operations, but we always refer to them as methods in Java. Some other languages refer to them as functions or procedures.

When we say we are “calling a method”, what we mean is that we are executing an operation! 24

Page 25: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

PRINT AND PRINTLN STATEMENTS

You may be wondering what the difference between the two methods print and println are. print will display everything on one line but not start a new line for anything else that will be printed by the next print or println statement. println will display everything on one line and then start a new line of output for the output of any other print or println statement. Here is an example:

(Note the extra spaces at the end of the first two print statements or the sentences would jam up together in output)

The output in the console window is all on one line:

Hello World! How are you doing? I am doing fine.

25

public class HelloWorld

{

public static void main(String args[ ])

{

//Consider these three lines of code:

System.out.print(“Hello World! ”);

System.out.print(“How are you doing? ”);

System.out.print(“I am doing fine.”);

} // end of main method

} // end of HelloWorld Class

Page 26: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

PRINT AND PRINTLN STATEMENTS

Again … print will display everything on one line but not start a new line of output. println will display everything on one line and then start a new line of output.

public class HelloWorldNew

{ //Filename: HelloWorldNew.java

public static void main(String args[ ])

{

//Consider these three lines of code:

System.out. print(“Hello World! ”);

System.out. println(“How are you doing?”);

System.out. println(“I am doing fine.”);

} // end of main method

} // end of HelloWorldNew Class

The output is on two lines in the console window:

Hello World! How are you doing?

I am doing fine. 26

Page 27: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

PRINT STATEMENTS AND SYNTAX ERRORS

So when we use the line of code:

System.out.print(“Hello World”);

We are calling the print method. Printing to a console window requires that we place System.out. prior to the word print.

Please notice the periods “.” (method selector operators) that separate the words System, out, and print.

Also, notice that the first S of System is capitalized (upper case). The reason is System is the name of a class.

Also, notice that after the word print there are parentheses that include in double quotes the information that we want to display to the screen and the entire line of code ends in a semicolon.

All of this is required and must be typed correctly or you will get a syntax error. Programs with syntax errors won’t run! 27

Page 28: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

SEMICOLONS END MOST JAVA STATEMENTS

• A Semicolon (;) marks the end of most Java statements. A statement is a

“sentence” in a program. Examples: Filename NumSum.java

public class NumSum

{

public static void main(String args[ ])

{

//Consider these three lines of code:

System.out.println(“Hello World!”);

num1 = reader.nextInt();

sum = num1 + num2;

} // end of main method

} // end of NumSumClass

Some Java lines do not end in a semicolon. You will learn which ones don’t as you are

introduced to other coding structures.28

Page 29: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

USING VARIABLES TO STORE VALUES

A variable names a memory address (location) in RAM memory where a value can be stored.

The variable is considered to be a nickname for the memory address.

The memory address of a variable may be some unusual combination of 1s or 0s or a hexadecimal number, so its great that we can decide on the name of variables. We do this when we declare them.

We can think of a variable as a small box that holds a value.

X Y name

an int variable a double variable a string variable

29

Page 30: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

SIMPLE JAVA DATA TYPES

In Java, we have different kinds of data types. Here you will learn three of them. We can store each of the three types of data values in different kinds of variables.

We can have …

1. int variables that can hold integers (type int)

2. double variables that can hold real numbers or what we refer to also as floating-point numbers (type double)

3. String variables that refer to an object that can hold a string of characters, in other words, a bunch of characters that make up a word (type String)

The data types int and double are simple numeric data types and we store those kind of values in simple variables that are not considered object variables.

However, Strings are objects and a String value must be stored in an object variable. Let’s look at how we do that with the assignment operator.

30

Page 31: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

THE ASSIGNMENT OPERATOR

The assignment operator is the = character and you can initialize variables to literal numeric or string values in one line of code.

So to store a value in a variable, we use the assignment operator.

Here is how to declare the different kinds of variables and store values in them or as we like to say initialize them:

int x = 129; // x is the int variable and 129 is being stored.

double y = 3.14159; // y is the double variable and π is stored.

String name = “Java”;

In the last line of code, name is the String variable and the word “Java” is being stored. Notice the double quotes around Java since we are storing a literal String value Don’t place double quotes when you store numbers. 31

Page 32: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

NUMERIC VARIABLES

A numeric variable names a memory address (location) in RAM memory where a

number can be stored. It is considered to be a nickname for the memory

address. Numeric variables are of type int or double.

When we use the line of code:

double celsius;

then enough RAM memory is allocated so that a floating-point value can be

stored in celsius. Java does this automatically for you! A double variable gets

twice as much memory as an int variable. Thus, the data type was named

double. 32

Page 33: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

IMPORTANT FACTS ABOUT VARIABLES

Important points to remember about variables:

• A variable’s value may change during a program, but its

name remains constant.

• A variable’s type defines what kind of values can be stored

in RAM. The type of the variable cannot be changed while a

program is running. Remember when we say type we are

referring to int, double, boolean, String, or other data types.

33

Page 34: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

JAVA’S MATHEMATICAL OPERATORS

Java basically has 5 mathematical operators.

Addition is represented by the + sign.

Subtraction is represented by the - sign.

Multiplication is represented by the * sign.

Division is represented by the / sign.

Mod is represented by the % sign. Mod gives the remainder of int division. (You’ll be amazed at how

much you will use mod)

In the Convert.java program, the line of code:

celsius = ( fahrenheit - 32.0 ) * 5.0 / 9.0;

uses three of the above mathematical operators.

You’ll see the code for the program in a few of slides.

34

Page 35: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

DECLARING AND USING SCANNER OBJECTS

We also use the assignment operator when creating objects (constructing objects) so an object variable can refer to them.

If we want to receive input from the keyboard during a program, then we need to construct a Scanner object first. This allows the user to enter numbers or string values into a program.

To do this we need to import Java’s Scanner class with the line:

import java.util.Scanner; // goes above the class declaration line

Next, inside the main method, we need to construct the Scanner object with the line:

Scanner reader = new Scanner(System.in);

We need to use System.in as the parameter because this indicates the keyboard, which is the default input device for Java. Note: Scanner is a class so the S is capitalized.

35

Page 36: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

GENERAL FORM FOR CONSTRUCTING OBJECTS

• In programming, the process of constructing an object is called instantiation.

• In general, constructing or instantiating and object takes the general form:

<Name of Class> <variable> = new <Name of Class> (<parameters>);

You can see that the line of code below follows this form:

Scanner reader = new Scanner (System.in);

You can think of reader as something that is “scanning the keyboard waiting for input”. 36

Page 37: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

CONSTRUCTING A SCANNER OBJECT WITH NEW

In the line of code :

Scanner reader = new Scanner(System.in);

the name of the class Scanner is used twice.

The first part of the line:

Scanner reader

declares reader to be an object variable of type Scanner. We need to do this or reader can’t refer to the Scanner object we construct.

The second part of the line:

new Scanner(System.in);

constructs the Scanner object and “attaches it” to the keyboard. The word new is the new operator that we use to construct things. The assignment operator makes reader refer to the Scanner object.

37

Page 38: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

MORE ABOUT READING INPUT FROM THE KEYBOARD

Assume the following lines of code appear in the main

method of a program.

Filename: ScanIn.java

public class ScanIn

{

public static void main(String args[ ])

{

//Consider these three lines of code:

Scanner reader = new Scanner (System.in);

System.out.print(“Enter your name and press return: ”);

String name = reader.nextLine();

System.out.print(“Enter your age and press return: ”);

int age = reader.nextInt();

System.out.print(“Enter your gpa and press return: ”);

double gpa = reader.nextDouble();

} // end of main method

} // end of ScanIn Class

Notice when we prompt the user, we use a print statement NOT a println statement. We can receive different kinds of input using reader. We use the object variable reader to “call the method nextLine() to receive a String value from the keyboard. We use reader to “call the method nextInt() to receive an integer and we use reader to “call the method nextDouble() to receive a floating-point value from the keyboard.

Note: the print statements “prompt” the user to enter data, otherwise he or she wouldn’t know the computer is waiting for input!

38

Page 39: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

ECHOING THE INPUT FROM THE KEYBOARD

We can now “echo the input” (print the information back to the screen that was entered) by using some println statements. In each line, we will print a literal string (something in double quotes) and the value contained in a variable. We use a plus sign to concatenate the literal string value and the value stored in the variable together to make a larger string that is then printed.

System.out.println(“Your name is: ” + name);

System.out.println(“Your age is: ” + age);

System.out.println(“Your gpa is: ” + gpa);

Notice that there are no double quotes around the variables name, age, and gpa.39

Page 40: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

SAMPLE CODE : NOTE TWO COLUMNSpublic class ScanIn

{

public static void main(String args[ ])

{

//Consider these three lines of code:

Scanner reader = new Scanner

(System.in);

System.out.print(“Enter your name

and press return: ”);

String name = reader.nextLine();

System.out.print(“Enter your age and

press return: ”);

int age = reader.nextInt();

System.out.print(“Enter your gpa and

press return: ”);

double gpa = reader.nextDouble();

System.out.println(“Your name is: ” + name);

System.out.println(“Your age is: ” + age);

System.out.println(“Your gpa is: ” + gpa);

} // end of main method

} // end of ScanIn Class

Page 41: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

ALGORITHM FOR CONVERTING TEMPERATURES

If we wanted to write the code for a program that would convert Fahrenheit temperatures to Celsius, it would be good to stop and develop an algorithm. An algorithm is a step by step procedure for solving a problem. This helps our code to be more efficient and we save a lot of time, because we consider all that needs to be done … NOT just the mathematical formula needed to convert the temperature.

41

Page 42: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

ALGORITHM FOR CONVERTING TEMPERATURES

Consider this algorithm(break down to solve the problem):

1. Prompt the user to enter a Fahrenheit temperature.

2. Read the value from the keyboard and store it in a variable.

3. Use the value stored in the variable in an assignment statement that applies the correct mathematical formula in code form.

4. Store the value calculated in a second variable.

5. Output the converted value to the screen.

42

Page 43: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

THE CONVERT.JAVA PROGRAMimport java.util.Scanner;

public class Convert{

public static void main(String args[]){

Scanner reader = new Scanner(System.in);

double fahrenheit;double celsius;

// prompt the user to enter a value from the keyboard when the program runs.System.out.print("Enter degrees Fahrenheit and press return: ");

// read the value from the keybaord and store it in the variable fahrenheit.fahrenheit = reader.nextDouble();

// calculate the equivalent celsius value and store it in the variable celsiuscelsius = (fahrenheit - 32.0) * 5.0 / 9.0;

// print out the following string of characters to the terminal window.System.out.print("The equivalent in Celsius is ");

// print out the value stored in the variable celsius to the terminal window.System.out.println(celsius);

}}

Note the key Scanner lines identified by the red arrows.43

Page 44: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

MORE ABOUT IMPORT STATEMENTS

In the Convert.java code you saw that the first line after the package declaration was an

import statement:

import java.util.Scanner;

This tells the compiler where to find a class that will be used during the program. The

class may be either in a Java library file or another file you have in a folder. The

import statement contains the path name of where to find the class.

The import statement tells us that the Scanner class is found in a sub-package folder

named util that is in the java package folder.

Now you know enough that you can finish the second half of the Convert.java program!44

Page 45: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

SECTION 5

CALLING METHODS

IN THIS SECTION, YOU WILL LEARN SOME VERY IMPORTANT INFORMATION ABOUT:

1. METHOD CALLS AND PARAMETERS

2. CONCATENATION

3. READABILITY OF CODE

45

Page 46: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

METHOD CALLS WITH PARAMETERS

Consider the following line of code:

System.out.println(“Hello World!”);

• System is a class and out is an object of that class that knows how to display or print characters in a console or terminal window.

println is the name of the method (operation) being executed. (Another way to say it is we are “sending the message println to the object represented by System.out”.)

The item inside the parentheses “Hello World” is the parameter of what needs to be printed. Here the parameter is a string (string of characters) that make up the words “Hello World”. Notice they appear in quotation marks. This tells Java to print to the screen the literal string value “Hello World”. The parameter could be a variable that contains a value instead of a literal string value in double quotes. 46

Page 47: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

GENERAL RULE OF METHOD CALLS

The general form for calling methods is:

<name of object> . <name of method> (<parameters>)

A message may require zero, one, or multiple parameters. Here are some examples:• To print a blank line, we can use System.out.println(); without any parameters in

the ( ).

• To print “Hello World”, we need only one parameter the literal string value “Hello World” in the parenthesis … System.out.println(“Hello World!”);

• To print “Hello World. Java Rules”, we still need only one parameter but the parameter may be the concatenation of two literal string values as in …System.out.println(“Hello World!” + “Java Rules!”); Notice that we concatenate two literal strings together using a + symbol.

• To call a method named calculateArea with two parameters length and width, we use the code ...calculateArea(length, width);

Notice the two parameters are separated by a comma. 47

Page 48: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

THE METHOD SELECTOR IS THE PERIOD

The Method selector operator is the period . and is always placed between the object’s name and the method’s name. It is also placed between the name of a class and the name of an object when needed as in System.out.

Scanner reader = new Scanner(System.in);

System.out.println(“Enter an integer: ”);

int num1 = reader.nextInt();

System.out.println(“Enter an integer: ”);

int num2 = reader.nextInt();

System.out.println(“Enter a floating-point number: ”);

double num3 = reader.nextDouble();

Above, reader has been declared to be a Scanner class variable that represents a new Scanner object. That Scanner object can read data from the input of the keyboard. Reader can call either of the methods nextInt() or nextDouble() to read integers or floating-point numbers from the keyboard. The variable reader is also referred to specifically as an object variable.

48

Page 49: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

DECLARING INT AND DOUBLE VARIABLES

TIME OUT!!! What are we doing with the lines?

int num1 = reader.nextInt();

double num3 = reader.nextDouble();

In the first line, we declare a variable named num1, but we have to tell what type of data we intend for it to hold. Since we want it to hold an integer (whole number), we use Java’s int data type. The type of data must be listed before the name of the variable!

The assignment operator = means we want to store something in num1. What we want to store is what is on the right side of the = sign. It could be an arithmetic expression or a reader line.

When a program runs and it encounters a line like reader.nextInt(), the program will pause and wait for something to be entered from the keyboard. Once the user enters an integer and presses return, then the number is read by reader’s nextInt() method, and then the value is stored in num1.

With the second line of code, we declare a variable num3 that can hold a floating-point number (one that contains a decimal point like 4.237). The method nextDouble() is used to read the value from the keyboard and store it in the double (floating-point) variable num3.

49

Page 50: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

CONCATENATING OUTPUT ITEMS

Consider this segment of code:

System.out.println(“Enter an integer: ”);

int num1 = reader.nextInt(); // a whole number is stored in num1

System.out.println(“Enter an integer: ”);

int num2 = reader.nextInt(); // a whole number is stored in num2

int sum = num1 + num2; // a whole number is stored in sum

System.out.println(“The sum of ” + num1 + “ and ” + num2 + “ is ” + sum);

In the last output line, we concatenate 6 things together to be written to output. Three of the items are literal strings and three are variables of type int that hold integers. Notice there are NO double quotes around the variables. You never place double quotes around any variable … only literal string values. Also, notice the blank spaces at the beginning and end of some literal string values. This keeps the numbers from being jammed up against the words.

50

Page 51: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

REVIEW OF SIMPLE AND OBJECT VARIABLES

In the Convert.java program, simple variables like fahrenheit and celsius each hold a

single floating-point number.

Object variables like reader and System.out hold references to objects.

Object variables are used to send messages to objects.

reader.nextDouble() sends the message “get me the next floating point number” from

the keyboard.

In summary, to write effective Java programs, a programmer does not need to have

detailed knowledge of the inner workings of any object, he or she just needs to know

how to construct objects and how to send messages to the object by calling methods.51

Page 52: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

THE READABILITY OF CODE

It is important for your code to be readable by others. In the real world, programmers are on software teams as they develop and maintain software. So everyone must be able to read your code! Programmers have developed a standard for how code should be formatted.

• The main factors that determine whether code is readable or not are Spacing (referring to extra blank lines that space things out) Indentation (referring to tabs or indentions on a specific line)

• Spacing and Indentation are just for programmer readability. The compiler ignores any kind of spacing and indentation. It just checks to make sure that everything is syntactically correct (spelled correctly)!

• Eclipse assists you with indenting segments of code as you type by automatically properly indenting your next line depending on the kind of Java code you are writing. But if you mess up the indenting then all you have to do is select all code by typing Control “a” on a Windows machine or Apple “a” on a Mac, then type either Control “i” for Windows or Apple “i” for a Mac and everything will get indented properly. 52

Page 53: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

COMMENTS ARE USED TO …

Comments are used to:• begin a program with a statement of its purpose

• explain the purpose of a variable that needs it

• explain the purpose of a major segment of code, like a method

• explain the workings of complex or tricky sections of code

53

Page 54: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

THE THREE TYPES OF PROGRAM COMMENTSProgram comments come in three varieties:

End of line or Single comments: All text following a double forward slash (//) on a single line may explain a line of code and are ignored by the compiler.

Multi-line comments: All text occurring between a /* and a */ is ignored by the compiler. Multi-line comments are used where lengthy explanations are needed or you want to deactivate a large segment of code temporarily.

54

public class HelloWorld{

public static void main(String args[ ]){//Consider these three lines of code:

System.out.println(“Hello World!”);

} // end of main method} // end of HelloWorld

Notice the //. Everything after the // are programmer comments about the code. It is does not perform any task when the code is executed.

Page 55: JAVA PROGRAMMING WITH ECLIPSE PART 1 PLEASE READ ALL THE CONTENT ON THE SLIDES. WATCH THE RECOMMENDED VIDEOS LISTED.

USEFUL READING AND YOUTUBE VIDEO

How to Create first Application in Javahttp://www.java-made-easy.com/java-hello-world.htmlhttps://www.youtube.com/watch?v=m9vN0HJoUTI


Recommended