basic programming the program class, the main method, variables, output, and input chapters 1 and 2

68
Basic Programming Basic Programming The Program Class, the The Program Class, the main Method, Variables, main Method, Variables, Output, and Input Output, and Input Chapters 1 and 2 Chapters 1 and 2

Upload: polly-lambert

Post on 14-Dec-2015

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Basic ProgrammingBasic Programming

The Program Class, the main Method, The Program Class, the main Method, Variables, Output, and InputVariables, Output, and Input

Chapters 1 and 2Chapters 1 and 2

Page 2: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

OverviewOverview

Making Programs with NetBeansMaking Programs with NetBeans A Program “class”A Program “class” A Problem; a Solution: an AlgorithmA Problem; a Solution: an Algorithm VariablesVariables MathMath OutputOutput InputInput

Page 3: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Making a ProgramMaking a Program

We need programs to make programsWe need programs to make programs we need to we need to writewrite the program the program

» we need an we need an editoreditor we need to we need to compilecompile the program the program

» we need a we need a compilercompiler we need to we need to runrun the program the program

» for Java, we need an for Java, we need an emulatoremulator we will probably need to fix mistakeswe will probably need to fix mistakes

» back to the editor!back to the editor!

Page 4: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

The Development EnvironmentThe Development Environment

You can use separate programs…You can use separate programs… Notepad to edit, javac to compile, java to runNotepad to edit, javac to compile, java to run

……but nicer to have a do-it-all programbut nicer to have a do-it-all program Integrated Development Environment (IDE)Integrated Development Environment (IDE)

Our IDE will be NetBeans 8.0.2Our IDE will be NetBeans 8.0.2 on the desktop in lab computerson the desktop in lab computers free download for your personal computerfree download for your personal computer

» Windows, Mac OS X, Linux (x86/x64)Windows, Mac OS X, Linux (x86/x64)

Page 5: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Running NetBeansRunning NetBeans

Type program here

Run program here

Listof

projects

Programparts

Page 6: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Creating a ProgramCreating a Program

Click the “New Project…” iconClick the “New Project…” icon

or File > New Projector File > New Project

Page 7: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Creating a ProgramCreating a Program

Select Java and Java ApplicationSelect Java and Java Application

click Next >click Next >

Page 8: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Creating a ProgramCreating a Program

Name your projectName your project

Browse to your CSCI1226 folderBrowse to your CSCI1226 folder

Clear the checkboxClear the checkbox

Click FinishClick Finish

Page 9: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Creating a ProgramCreating a Program

Your project has been createdYour project has been created

NOW select the New File commandNOW select the New File command

Page 10: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Creating a ProgramCreating a Program

Select Java and Java Main ClassSelect Java and Java Main Class

click Next >click Next >

Page 11: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Creating a ProgramCreating a Program

Name your programName your program

and make sure it’s in the right projectand make sure it’s in the right project click Finish (ignore the warning!)click Finish (ignore the warning!)

Page 12: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Creating a ProgramCreating a Program

You have a program!You have a program!

Note: it doesn’t Note: it doesn’t do do anything yet!anything yet!

Page 13: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

The Basic Program ClassThe Basic Program Class

Every Java program has this stuff:Every Java program has this stuff:public class public class ProgramClassNameProgramClassName { { public static void main(String[] public static void main(String[] argsargs) {) { }}}}

the word after the word after classclass is the name of the program is the name of the program» each program will have its own nameeach program will have its own name» file will have same name, but with .java addedfile will have same name, but with .java added

the the bracesbraces {{ and and }} must be there must be there I’ll explain I’ll explain public static void public static void line laterline later

Page 14: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Where the Code GoesWhere the Code Goes

For now our programs will be very simpleFor now our programs will be very simple only one file in the projectonly one file in the project the one file will have a the one file will have a methodmethod named named mainmain all our code will go inside the all our code will go inside the {}{} of of mainmainpublic class public class ProgramClassNameProgramClassName { {

» NOT hereNOT here public static void main(String[] public static void main(String[] argsargs) {) {

» code goes in here!code goes in here! }}

» NOT hereNOT here}}

» NOT hereNOT here

Page 15: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

What is Code?What is Code?

Code is instructions for the computerCode is instructions for the computer written in a computer languagewritten in a computer language

» for us, that language will be Javafor us, that language will be Java

Code is like a recipeCode is like a recipe lists all the steps, in order, to complete the tasklists all the steps, in order, to complete the task

But we don’t But we don’t startstart with code! with code! We start with a We start with a problemproblem

Page 16: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

ProblemsProblems

We want to do something on the computerWe want to do something on the computer keep track of stats at a basketball gamekeep track of stats at a basketball game find the average of a bunch of numbersfind the average of a bunch of numbers find the area of a rectanglefind the area of a rectangle draw a happy facedraw a happy face whateverwhatever

Need to Need to understandunderstand the problem the problem need to work out the detailsneed to work out the details

Page 17: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Problem: Draw This FaceProblem: Draw This Face

How would we do that?How would we do that? We need a planWe need a plan We need an We need an algorithmalgorithm

Page 18: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

AlgorithmsAlgorithms

A set of step-by-step instructions for A set of step-by-step instructions for solving a problemsolving a problem can be “high level”…can be “high level”…

» not very detailednot very detailed ……or “low level”or “low level”

» lots of details providedlots of details provided

PseudocodePseudocode computer instructions written in English (computer instructions written in English (e.g.e.g.))

Page 19: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

to Draw a Happy Faceto Draw a Happy Face

1.1. Draw a circleDraw a circle

2.2. Draw an eye in the Draw an eye in the upper left quadrantupper left quadrant

3.3. Draw an eye in the Draw an eye in the upper right quadrantupper right quadrant

4.4. Draw a smile in the Draw a smile in the lower halflower half

High-level pseudocode

Page 20: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

to Draw a Happy Faceto Draw a Happy Face

1.1. Draw a circle 200 pixels wide, with its left edge 100 pixels Draw a circle 200 pixels wide, with its left edge 100 pixels from the left edge of the screen, and its top 50 pixels down from the left edge of the screen, and its top 50 pixels down from the top of the screenfrom the top of the screen

2.2. Draw an oval 10 pixels tall and 20 wide, with its left edge 155 Draw an oval 10 pixels tall and 20 wide, with its left edge 155 pixels from the left edge of the screen, and its top 100 pixels pixels from the left edge of the screen, and its top 100 pixels down from the top of the screendown from the top of the screen

3.3. Draw an oval 10 pixels tall and 20 wide, with its left edge 230 Draw an oval 10 pixels tall and 20 wide, with its left edge 230 pixels from the left edge of the screen, and its top 100 pixels pixels from the left edge of the screen, and its top 100 pixels down from the top of the screendown from the top of the screen

4.4. Draw the lower half of an oval 100 pixels wide and 50 pixels Draw the lower half of an oval 100 pixels wide and 50 pixels tall, with its left edge 150 pixels from the left edge of the tall, with its left edge 150 pixels from the left edge of the screen, and its top 160 pixels down from the top of the screen.screen, and its top 160 pixels down from the top of the screen.

Low-level pseudocode

Page 21: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Programming a ComputerProgramming a Computer

Understand the problemUnderstand the problem do not skip this step!do not skip this step!

Figure out how to solve itFigure out how to solve it (make high-level pseudocode)(make high-level pseudocode)

Break solution into smaller/lower stepsBreak solution into smaller/lower steps keep going until each step is “obvious”keep going until each step is “obvious”

Write it down in computer languageWrite it down in computer language Compile it & test itCompile it & test it

Page 22: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

to Find the Area of a Rectangleto Find the Area of a Rectangle

1.1. Get the length and width of the rectangleGet the length and width of the rectangle

2.2. Multiply them together to get the areaMultiply them together to get the area Questions:Questions:

get the area from where?get the area from where? what shall we do with the area once we have it?what shall we do with the area once we have it?

Answers:Answers: usually from the user (usually from the user (inputinput) ) laterlater usually tell the user (usually tell the user (outputoutput))

Page 23: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Working with NumbersWorking with Numbers

Need the computer to keep track of numbersNeed the computer to keep track of numbers the length of the rectanglethe length of the rectangle the width of the rectanglethe width of the rectangle the area of the rectanglethe area of the rectangle

Don’t know those numbers yetDon’t know those numbers yet user will tell us when the program’s runninguser will tell us when the program’s running but we need to talk about them before that!but we need to talk about them before that!

» to tell computer what to do with themto tell computer what to do with them

Page 24: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

VariablesVariables

Use Use namesnames instead of numbers instead of numbers one number will be the length of the rectangleone number will be the length of the rectangle

» let’s call it let’s call it lengthlength one number will be the width of the rectangleone number will be the width of the rectangle

» let’s call it let’s call it widthwidth what shall we call the area of the rectangle?what shall we call the area of the rectangle?

These names are called These names are called variablesvariables they can have any number as a they can have any number as a valuevalue we must we must createcreate variables before variables before usingusing them them

Page 25: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

to Find the Area of a Rectangleto Find the Area of a Rectangle

1.1. Create variables for length, width and areaCreate variables for length, width and area

2.2. Get length and width of rectangleGet length and width of rectangle

3.3. Multiply length by width to get areaMultiply length by width to get area

4.4. Report dimensions and area to userReport dimensions and area to user

Revised pseudocode

Page 26: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

public class RectangleArea { public static void main(String[] args) { }}

public class RectangleArea { public static void main(String[] args) { // 1. create variables for length, width and area }}

public class RectangleArea { public static void main(String[] args) { // 1. create variables for length, width and area // 2. get length and width of rectangle // 3. multiply length by width to get area // 4. report dimensions and area to user }}

Writing CodeWriting Code

Write steps in your program as Write steps in your program as commentscomments comments start with comments start with //// and go to end of line and go to end of line

Page 27: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

public class RectangleArea { public static void main(String[] args) { // 1. create variables for length, width and area // 2. get length and width of rectangle // 3. multiply length by width to get area // 4. report dimensions and area to user }}

Writing CodeWriting Code

Fill in code below each commentFill in code below each comment comment and code each comment and code each indentedindented

public class RectangleArea { public static void main(String[] args) { // 1. create variables for length, width and area // 2. get length and width of rectangle // 3. multiply length by width to get area // 4. report dimensions and area to user }}

public class RectangleArea { public static void main(String[] args) { // 1. create variables for length, width and area int length, width, area; // 2. get length and width of rectangle // 3. multiply length by width to get area // 4. report dimensions and area to user }}

public class RectangleArea { public static void main(String[] args) { // 1. create variables for length, width and area int length, width, area;

// 2. get length and width of rectangle // 3. multiply length by width to get area // 4. report dimensions and area to user }

Page 28: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Declaring VariablesDeclaring Variables

Say what kind of values the variables haveSay what kind of values the variables have intint: integer values (3, 5, -7): integer values (3, 5, -7) doubledouble: numbers with decimal points (2.4, -1.1): numbers with decimal points (2.4, -1.1) many, many, manymany more kinds of values more kinds of values

This is called the variable’s This is called the variable’s data typedata type Say it in front of the variables name(s)Say it in front of the variables name(s)

separate names with commas (,)separate names with commas (,) end line with a semi-colon (;)end line with a semi-colon (;)

Page 29: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

ExerciseExercise

State name and data type of each variable:State name and data type of each variable:int num;int num;double height;double height;int num1, num2;int num1, num2;double priceInDollars;double priceInDollars;String myName;String myName;String title, surname;String title, surname;Scanner kbd;Scanner kbd;Thingamajig whatchamacallit, doohickey;Thingamajig whatchamacallit, doohickey;

When I ask “What kind of a thing is ____?”I want you to tell me its data type.

Page 30: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Notes on NamesNotes on Names

No spaces or punctuation allowed in namesNo spaces or punctuation allowed in namesint int bad namebad name, , bad-namebad-name, , bad&namebad&name, , badPriceIn$badPriceIn$;;

Names of programs start with CapitalsNames of programs start with Capitals RRectangleAreaectangleArea, , DDrawFacerawFace, , FFindAverageindAverage, ..., ...

Names of variables start with little lettersNames of variables start with little letters llengthength, , wwidthidth, , aarearea, , nnameame

Words after first one start with CapitalsWords after first one start with Capitals RectangleRectangleAArearea, , pricepriceIInnDDollarsollars

Page 31: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

ExerciseExercise

Is your family name a valid Java identifier?Is your family name a valid Java identifier? if so, is it a variable name or a program name?if so, is it a variable name or a program name? if not, what’s wrong with it?if not, what’s wrong with it? if we got rid of those problems, then would it if we got rid of those problems, then would it

be a variable name or a program name?be a variable name or a program name?

Page 32: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Giving Variables ValuesGiving Variables Values

We will want to read values from user...We will want to read values from user... ...but for now we’ll assign values directly...but for now we’ll assign values directly

// 1. create variables for length, width and area int length, width, area;

// 2. get length and width of rectangle // 3. multiply length by width to get area // 4. report dimensions and area to user }}

// 1. create variables for length, width and area int length, width, area;

// 2. get length and width of rectangle length = 15; width = 24;

// 3. multiply length by width to get area // 4. report dimensions and area to user

Page 33: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Giving Variables ValuesGiving Variables Values

Area we want to calculateArea we want to calculate multiply length by widthmultiply length by width

// 1. create variables for length, width and area int length, width, area;

// 2. get length and width of rectangle length = 15; width = 24;

// 3. multiply length by width to get area // 4. report dimensions and area to user

// 1. create variables for length, width and area int length, width, area;

// 2. get length and width of rectangle length = 15; width = 24;

// 3. multiply length by width to get area area = length * width;

Page 34: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Assignment StatementsAssignment Statements

Give a value to a variableGive a value to a variablelength = 15;length = 15;width = 24;width = 24;area = length * width;area = length * width;

Variable name, equals sign, expressionVariable name, equals sign, expression expression may be simple or complicatedexpression may be simple or complicated can use numbers and variables in expressioncan use numbers and variables in expression

?

length

?

width

?

area

15

length

24

width

360

area

Page 35: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Simple MathSimple Math

Can assign using math expressionsCan assign using math expressions use + for additionuse + for additiontotalTaxes = federalTaxes + provincialTaxes;totalTaxes = federalTaxes + provincialTaxes; use – for subtractionuse – for subtractionnetIncome = grossIncome – totalTaxes;netIncome = grossIncome – totalTaxes; use * for multiplicationuse * for multiplicationsalesTax = totalSales * 0.15;salesTax = totalSales * 0.15; use / for divisionuse / for divisionaverage = sum / count;average = sum / count;

Page 36: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Reporting Results to the UserReporting Results to the User

Print results on the screenPrint results on the screen IDE: in the “run” area at bottom of screenIDE: in the “run” area at bottom of screen (or sometimes in a black window that appears)(or sometimes in a black window that appears)

Need to tell computer to print somethingNeed to tell computer to print somethingSystem.out.print( System.out.print( ... ... ););System.out.println( System.out.println( ... ... ););

Need to say what to printNeed to say what to print what to print goes inside the what to print goes inside the parenthesesparentheses () ()

Don’t worry about what System.out means! I’ll explain later.

Page 37: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

printlnprintln vs. vs. print print

printlnprintln prints and then ends the line prints and then ends the line printprint just prints (line doesn’t end) just prints (line doesn’t end)

System.out.println("Hello!");System.out.println("Hello!");System.out.print("Bye");System.out.print("Bye");System.out.print("-");System.out.print("-");System.out.print("bye");System.out.print("bye");System.out.println("!!!");System.out.println("!!!");

Hello!Bye-bye!!!

Page 38: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Output CommandsOutput Commands

System.out knows how to print stuffSystem.out knows how to print stuff can print Stringscan print Strings

System.out.println( "This is a String!" );System.out.println( "This is a String!" ); can print numbers, expressions, and variablescan print numbers, expressions, and variables

System.out.println( 10 );System.out.println( 10 );System.out.println( 20 + 25 );System.out.println( 20 + 25 );System.out.println( area );System.out.println( area );

This is a String!1045360

Page 39: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Quotes, or No Quotes?Quotes, or No Quotes?

Quotes Quotes print these characters print these characters No quotes No quotes print the value of this print the value of this

can be variable or math expressioncan be variable or math expressionSystem.out.println( System.out.println( ""areaarea" " ); ); // prints four letters// prints four lettersSystem.out.println( area );System.out.println( area ); // prints value of // prints value of

variablevariableSystem.out.println( 10 + 15 ); System.out.println( 10 + 15 ); // prints expression value// prints expression valueSystem.out.println( "10 + 15System.out.println( "10 + 15" ); " ); // prints seven “letters”// prints seven “letters”area3602510 + 15

Page 40: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Printing SpacesPrinting Spaces

If you want spaces printed, they need to go If you want spaces printed, they need to go insideinside the quotation marks the quotation marks spaces outside the quotation marks are ignoredspaces outside the quotation marks are ignoredSystem.out.print( System.out.print( ""Start1>Start1>"" ); );System.out.println( System.out.println( ""<End1<End1"" ); );System.out.print(System.out.print("" Start2> Start2> ""););System.out.println(System.out.println("" <End2 <End2 ""););

Start1><End1 Start2> <End2

Page 41: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Adding Things to PrintAdding Things to Print

Can add items to printCan add items to print don’t need a separate command for each itemdon’t need a separate command for each itemSystem.out.println(23 + "skidoo");System.out.println(23 + "skidoo");

» note: no space added!note: no space added! be careful with math – add parenthesesbe careful with math – add parenthesesSystem.out.println("10 + 34 is " + (10 + 34));System.out.println("10 + 34 is " + (10 + 34));

» note which parts have quotes and which don’tnote which parts have quotes and which don’t

10 + 34 is 44

23skidoo

Page 42: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Line Breaks in Your ProgramLine Breaks in Your Program

Output commands can be VERY longOutput commands can be VERY long too long to fit on one linetoo long to fit on one line

Break at + signsBreak at + signs do NOT break line between quotation marksdo NOT break line between quotation marksSystem.out.println("This is OK. "System.out.println("This is OK. "

+ "And I can add more here. " + "And I can add more here. " + "Even a number: " + 42);+ "Even a number: " + 42);

System.out.println("This is System.out.println("This is not OK!not OK!""););

Page 43: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Reporting on the RectangleReporting on the Rectangle

Report length and width as well as areaReport length and width as well as area helps user understand the answerhelps user understand the answer

// 1. create variables for length, width and area int length, width, area;

// 2. get length and width of rectangle length = 15; width = 24;

// 3. multiply length by width to get area // 4. report dimensions and area to user

// 1. create variables for length, width and area int length, width, area;

// 2. get length and width of rectangle length = 15; width = 24;

// 3. multiply length by width to get area area = length * width;

length = 15; width = 24;

// 3. multiply length by width to get area area = length * width;

// 4. report dimensions and area to user System.out.println("A " + length + " by " + width + " rectangle has an area of " + area + ".");

Page 44: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Note on Blank LinesNote on Blank Lines

Blank lines group commands togetherBlank lines group commands together create variablescreate variables

» blank lineblank line get valuesget values

» blank lineblank line calculate resultcalculate result

» blank lineblank line output resultoutput result

Computer doesn’t care – humans doComputer doesn’t care – humans do

Four stepsto completethe program:

an algorithm

Page 45: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

ExerciseExercise

Write a Write a program fragment program fragment to report how to report how much 25 boxes of girl guide cookies would much 25 boxes of girl guide cookies would cost, given that each box costs $2.cost, given that each box costs $2.

Use Use variablesvariables howMany: how many boxes of cookieshowMany: how many boxes of cookies pricePer: cost per boxpricePer: cost per box total: total amount owedtotal: total amount owedYour 25 boxes of cookies cost you $50.

Page 46: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Running Your ProgramRunning Your Program

Click the Run Project buttonClick the Run Project button

if there were no mistakes, it if there were no mistakes, it runsruns the program the program

You You WILLWILL make mistakes make mistakes II still make mistakes (30 years of experience) still make mistakes (30 years of experience)

The computer has The computer has no compassionno compassion

Page 47: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

If There are No MistakesIf There are No Mistakes

Output appears in windowOutput appears in window usually at the bottom of the NetBeans screenusually at the bottom of the NetBeans screen

the bit in black is written by your programthe bit in black is written by your program the bits in grey and green (or red) are added by the bits in grey and green (or red) are added by

NetBeansNetBeans

Page 48: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Mistakes in Computer ProgramsMistakes in Computer Programs

Two main kinds of mistakesTwo main kinds of mistakes Syntax errorsSyntax errors

what you said doesn’t make sensewhat you said doesn’t make sense ““Go the frog and.”Go the frog and.”

Logic errorsLogic errors what you said to do is not what it what you said to do is not what it shouldshould do do ““Subtract the tax from the base price to get the Subtract the tax from the base price to get the

final price.”final price.”

Page 49: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Syntax Error: NetBeansSyntax Error: NetBeans

NetBeans notices syntax errors right awayNetBeans notices syntax errors right away look for red squiggle and in marginlook for red squiggle and in margin

mouse over the to see the explanationmouse over the to see the explanation

Page 50: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Logic ErrorLogic Error

Compiler will not notice!Compiler will not notice!System.out.println("A length by width"System.out.println("A length by width"

+ "rectangle has an area of area."); + "rectangle has an area of area.");

Program just does the wrong thingProgram just does the wrong thing hopefully you can tell from the output!hopefully you can tell from the output!

Page 51: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

ExerciseExercise

Find the errors:Find the errors:

To find the area of a circleTo find the area of a circle

1. get it’s diameter1. get it’s diameter

2. raduis = diameter / pi2. raduis = diameter / pi

3. area = pi * radius * squared3. area = pi * radius * squared which ones are syntax errors?which ones are syntax errors? which ones are logic errors?which ones are logic errors?

Page 52: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Changing the Width & HeightChanging the Width & Height

If you run the program again, it’ll give you If you run the program again, it’ll give you exactly the same resultexactly the same result

Change the numbers to change the resultChange the numbers to change the result

you need to run it again, of course!you need to run it again, of course!

A 15 by 24 rectangle has an area of 360.

length = 18; width = 104;

A 18 by 104 rectangle has an area of 1872.

Page 53: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Getting Input from the UserGetting Input from the User

Want to ask user for the height and widthWant to ask user for the height and width want to set length equal to a number that the want to set length equal to a number that the

user types in; and ditto the widthuser types in; and ditto the width» area will still be length times widtharea will still be length times width

Many ways to do input in JavaMany ways to do input in Java We will use a We will use a ScannerScanner to do it to do it

a Scanner knows how to read numbers (and a Scanner knows how to read numbers (and other things) from the userother things) from the user

Page 54: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Get InputGet Input

Scanner kbd = new Scanner(System.in);Scanner kbd = new Scanner(System.in);length = length = kbd.nextInt();kbd.nextInt();width = width = kbd.nextInt();kbd.nextInt();

kbdkbd is a Scanner object is a Scanner object» it’s connected to the keyboard (System.in)it’s connected to the keyboard (System.in)

it knows how to get an integer from the userit knows how to get an integer from the user» nextIntnextInt is the command to get an int value is the command to get an int value

assignment operation (=) saves the numbersassignment operation (=) saves the numbers» first number saved in the variable named first number saved in the variable named lengthlength» second number saved in the variable named second number saved in the variable named widthwidth

Page 55: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

ProblemProblem

Java complains:Java complains: it knows that Scanner should be a classit knows that Scanner should be a class but it doesn’t know that class!but it doesn’t know that class!

Scanner is not “built in” to JavaScanner is not “built in” to Java it’s an “optional extra”it’s an “optional extra” need to tell Java you’re using itneed to tell Java you’re using it need to need to import import itit

» need to know where to import it need to know where to import it fromfrom

cannot find symbolsymbol : class Scanner

Page 56: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

The import CommandThe import Command

Goes before “public class” lineGoes before “public class” line

ScannerScanner is what we want to use is what we want to use java.util java.util is “where it is” (it’s a is “where it is” (it’s a packagepackage))

Now Java is happy with the programNow Java is happy with the program

import java.util.Scanner;

public class RectangleArea { public static void main(String[] args) {

Page 57: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Another ProblemAnother Problem

The program doesn’t seem to The program doesn’t seem to dodo anything! anything! it just sits thereit just sits there

It’s waiting for you to type a number!It’s waiting for you to type a number! type the number 15 and press the Enter keytype the number 15 and press the Enter key type the number 40 and press the Enter keytype the number 40 and press the Enter key then the output appearsthen the output appears

A 15 by 40 rectangle has an area of 600.

Page 58: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Prompting for InputPrompting for Input

Tell the user you want input!Tell the user you want input! say what you wantsay what you want say it say it just before just before the the kbd.nextInt() kbd.nextInt() lineline

// 2. get length and width of rectangle Scanner kbd = new Scanner(System.in); System.out.print( "Enter the length: "); length = kbd.nextInt(); System.out.print( "Enter the width: "); width = kbd.nextInt();

// 3. multiply length by width to get area

Page 59: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Now Program Asks for InputNow Program Asks for Input

Now program has conversation with userNow program has conversation with user program asks user for length, waits for userprogram asks user for length, waits for user user types in length, presses Enteruser types in length, presses Enter program asks user for width, waits for userprogram asks user for width, waits for user user types in width, presses Enteruser types in width, presses Enter program prints dimensions and areaprogram prints dimensions and area

Enter the length: 20Enter the width: 14A 20 by 14 rectangle has an area of 280.

User types 20 and 14 (and Enter after each). They won’t look blue on the computer.

Page 60: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Letting the User KnowLetting the User Know

It’d be nice for the program to explain to the It’d be nice for the program to explain to the user what it is going to douser what it is going to do put it between steps 1 and 2 (call it step 1.5)put it between steps 1 and 2 (call it step 1.5)

It’s nice for the program to repeat back what It’s nice for the program to repeat back what the user typed in (the length and width)the user typed in (the length and width) lets user see the right numbers got usedlets user see the right numbers got used helps user ensure it’s the result they wantedhelps user ensure it’s the result they wanted

» (“Aw, darn! I typed the width wrong.”)(“Aw, darn! I typed the width wrong.”)

Page 61: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Input MethodsInput Methods

The command to read an int is The command to read an int is kbd.nextInt()kbd.nextInt() kbdkbd because our Scanner is named kbd because our Scanner is named kbd

Scanner Scanner kbdkbd = new Scanner(System.in); = new Scanner(System.in); nextnextIntInt() () because we want to get the next intbecause we want to get the next int

What’s the command to read a double?What’s the command to read a double? How is it spelled How is it spelled exactly?exactly?

What’s the command to read a String?What’s the command to read a String? Wrong! (That’d be too easy!)Wrong! (That’d be too easy!)

Page 62: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

More Input MethodsMore Input Methods

Two methods for reading Strings:Two methods for reading Strings: kbd.nextLine() reads a whole linekbd.nextLine() reads a whole line kbd.next() reads a single “word”kbd.next() reads a single “word”String firstWord, secondWord, restOfLine;String firstWord, secondWord, restOfLine;firstWord = firstWord = kbd.next()kbd.next();;secondWord = secondWord = kbd.next()kbd.next();;restOfLine= restOfLine= kbd.nextLine()kbd.nextLine();;System.out.println(secondWord+firstWord+restOfLine);System.out.println(secondWord+firstWord+restOfLine);

First Second Third FourthSecondFirst Third Fourth

“First”firstWord

“Second”secondWord

“ Third Fourth”restOfLine

Page 63: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Reading SpacesReading Spaces

Most of the reading methods skip spacesMost of the reading methods skip spaces skip spaces until a non-space appearsskip spaces until a non-space appears

» Tabs and Enters are also spacesTabs and Enters are also spaces next(), nextInt(), nextDouble() all do thatnext(), nextInt(), nextDouble() all do that

nextLine() does not skip spacesnextLine() does not skip spaces reads reads whateverwhatever is left on the line is left on the line it’s the only reading method that reads spacesit’s the only reading method that reads spaces

Page 64: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Reading “Old” DataReading “Old” Data

If user types two numbers on first line...If user types two numbers on first line...

Program will Program will askask for the width... for the width... the prompt gets printedthe prompt gets printed

...but it won’t wait for the user to enter it...but it won’t wait for the user to enter it it’ll just use the second number from aboveit’ll just use the second number from above

Enter the length: 10 15

Enter the length: 10 15Enter the width: A 10 by 15 rectangle has an area of 150.

We’ll learn how to fix this problem next week.

Page 65: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Reading the “Enter” KeyReading the “Enter” Key

If you expect the user to press the Enter key If you expect the user to press the Enter key then you should input that data, toothen you should input that data, tookbd.nextLine();kbd.nextLine(); reads in the rest of the line, including the Enterreads in the rest of the line, including the Enter

System.out.print( "Enter the length: "); length = kbd.nextInt(); kbd.nextLine(); System.out.print( "Enter the width: "); width = kbd.nextInt(); kbd.nextLine();

Enter the length: 10 15Enter the width: 20A 10 by 20 rectangle has an area of 200.

Page 66: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

More about InputMore about Input

If the user types something wrong...If the user types something wrong... a number with a decimal point or a worda number with a decimal point or a word

...the program will ...the program will crashcrash

this crash was on line 24 of Rectangle.javathis crash was on line 24 of Rectangle.java

Enter the length: 10Enter the width: 14.4

Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:840) at java.util.Scanner.next(Scanner.java:1461) at java.util.Scanner.nextInt(Scanner.java:2091) at java.util.Scanner.nextInt(Scanner.java:2050) at RectangleArea.main(RectangleArea.java:24)

We won’t learn how to fix this problem until next term!

Page 67: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

ExerciseExercise

Ask the user what year it is and how old Ask the user what year it is and how old they are. Then calculate and print the year they are. Then calculate and print the year they were born. Use variables and suitable they were born. Use variables and suitable output.output.

Page 68: Basic Programming The Program Class, the main Method, Variables, Output, and Input Chapters 1 and 2

Questions?Questions?