Gentle Introduction to Programming in Java Dr. Jey Veerasamy 1.

Slides:



Advertisements
Similar presentations
Introduction to Eclipse. Start Eclipse Click and then click Eclipse from the menu: Or open a shell and type eclipse after the prompt.
Advertisements

Introduction to Programming using Java Dr. Jey Veerasamy July 31 st – August 23 rd 9:30 am to 12 noon 1.
Solving Problems with Repetition. Objectives At the end of this topic, students should be able to: Correctly use a while statement in a C# program Correctly.
Programming TBE 540 Farah Fisher. Objectives After viewing this presentation, the learner will be able to… Given a task, create pseudocode Given pseudocode,
Programming in Visual Basic
Computer Programming and Basic Software Engineering 4. Basic Software Engineering 1 Writing a Good Program 4. Basic Software Engineering 3 October 2007.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Program Design and Development
Loop variations do-while and for loops. Do-while loops Slight variation of while loops Instead of testing condition, then performing loop body, the loop.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Chapter 1 Program Design
1 Lab Session-III CSIT-120 Spring 2001 Revising Previous session Data input and output While loop Exercise Limits and Bounds GOTO SLIDE 13 Lab session.
Welcome to C++ Programming Workshop at The University of Texas at Dallas Presented by John Cole March 14-15, 2013.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Fundamentals of Python: From First Programs Through Data Structures
CC0002NI – Computer Programming Computer Programming Er. Saroj Sharan Regmi Week 7.
Fundamentals of Python: First Programs
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Advanced Programming LOOP.
General Programming Introduction to Computing Science and Programming I.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
Chapter 2 - Algorithms and Design
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
How to Run a Java Program CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
How to Run a Java Program CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Programming Logic and Design Sixth Edition Chapter 5 Looping.
Working with the VB IDE. Running a Program u Clicking the”start” tool begins the program u The “break” tool pauses a program in mid-execution u The “end”
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
1 Loops. 2 Topics The while Loop Program Versatility Sentinel Values and Priming Reads Checking User Input Using a while Loop Counter-Controlled (Definite)
A Simple Quiz: Ask User Functions. By Lana Dyck under the direction of Professor Susan Rodger Duke University June 2009, added Part 2 July 2011.
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
Discussion 4. Labs public MyPoint(double xInit, double yInit ) { MyPoint p = new MyPoint(0, 0); } ClassProblem.java recursive java.lang.StackOverflowError.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4: Control Structures II
Chapter 5: Control Structures II
Review, Pseudocode, Flow Charting, and Storyboarding.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02  Reading: Textbook(4 th Ed.), Chapter 2 Textbook (6 th Ed.), Chapters.
Agenda Perform Quiz #1 (20 minutes) Loops –Introduction / Purpose –while loops Structure / Examples involving a while loop –do/while loops Structure /
PROGRAMMING IN PYTHON LETS LEARN SOME CODE TOGETHER!
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 3 Friday 03 Oct 2014 EGR 115 Introduction to Computing for Engineers.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
1 BUILDING JAVA PROGRAMS CHAPTER 5 PROGRAM LOGIC AND INDEFINITE LOOPS.
Solving Problems with Repetition Version 1.0. Objectives At the end of this topic, students should be able to: Correctly use a while statement in a C#
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Loops, Part II IT108 George Mason University. Indefinite Loop Don’t always have access to the number of iterations ahead of time If a condition (user-response,
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
CIS 115 All Exercises Devry University (Devry) FOR MORE CLASSES VISIT CIS 115 All Exercises Devry University.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Information and Computer Sciences University of Hawaii, Manoa
Chapter 5: Control Structures II
Primitive Data, Variables, Loops (Maybe)
Repetition-Sentinel,Flag Loop/Do_While
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Escape sequences: Practice using the escape sequences on the code below to see what happens. Try this next code to help you understand the last two sequences.
Building Java Programs
Building Java Programs
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Building Java Programs
Building Java Programs
Presentation transcript:

Gentle Introduction to Programming in Java Dr. Jey Veerasamy 1

NetBeans IDE – getting started Start the tool Click on new Project icon in top toolbar Java category and Java Application have been pre-selected. Click on Next Use a meaningful project name for each project/program. Click on Finish. It will add a Java source file automatically with a skeleton code. 2

Sample skeleton code package hello; /** * veerasam */ public class Hello { /** args the command line arguments */ public static void main(String[] args) { // TODO code application logic here } 3

Program to print Hello! package hello; import java.util.*; public class Hello { public static void main(String[] args) { System.out.println("Hello to Java!"); } 4 Comments have been removed to conserve space. Assumes project name “hello”

Few notes Compiler translates the program to binary executable. NetBeans features automatic incremental compilation – syntax errors appear as you type in. It is good to keep the code formatted properly (indentation). Right-click within the editor any time and select Format. Comments are ignored by the compiler. Comments are used for recording ideas/thoughts in plain English so that we can make sense of the code later. // is used for one line comment, /* …. */ is used multi-line comments. For initial sessions, almost all our code will go into main() method. Do not change anything else. Java is case-sensitive. Example: int and Int are treated differently. 5

Structure for simple programs Input – get the necessary user input Processing – do some computation Output – show the results to the user 6

Idea/pseudocode - why? As the problems become bigger, it is harder to code directly from the problem description. It is better to capture the logic first, build confidence, then convert it to actual code. Pseudocode is for human understanding, so plain English is preferred. It can use indentation and language constructs like IF, WHILE, FOR, … but no need to follow any language syntax specifics. Can contain just high level ideas or detailed instructions that is equivalent to actual code. Another option is to use Flowcharts, but it occupies too much space & it cannot be stored as comments within the source files. 7

Problem: Country Store Let us say we have a simple store that sells only the following 5 items. Write a program to do the check-out. That is, ask the user to input the weights for each product and output the total price. 8 ProductPrice per pound Bananas$ 0.44 Apples$ 0.99 Cucumbers$ 1.19 Carrots$ 0.89 Oranges$ 0.79

Sample input & output Enter weight for Bananas: 2.5 Enter weight for Apples: 3.4 Enter weight for Cucumbers: 2.3 Enter weight for Carrots: 4.5 Enter weight for Oranges: 3.7 Total price is $ ProductPrice per pound Bananas$ 0.44 Apples$ 0.99 Cucumbers$ 1.19 Carrots$ 0.89 Oranges$ 0.79

Pseudocode #1 Prompt & get the weight for Bananas Prompt & get the weight for Apples Prompt & get the weight for Cucumbers Prompt & get the weight for Carrots Prompt & get the weight for Oranges total = bananaWeight * appleWeight * cucumberWeight * carrotWeight * orangeWeight * 0.79 output total 10

Pseudocode #2 Initialize total to 0 Prompt & get the weight for Bananas total += weight * 0.44 Prompt & get the weight for Apples total += weight * 0.99 Prompt & get the weight for Cucumbers total += weight * 1.19 Prompt & get the weight for Carrots total += weight * 0.89 Prompt & get the weight for Oranges total += weight * 0.79 output total 11 See store.java for the code.

Pseudocode #1 vs #2 2 nd version uses minimal # of variables – reuses weight for all 5 products since individual weights are not needed after computing sub-totals. Both are acceptable mechanisms! 12

Selection structures in Java if (condition) statement; if (condition) statement1; else statement2; if (condition) { statement1; … } else { statement2; … } 13

if statement – be careful! if (condition) statement1; statement2; is treated by compiler as if (condition) statement1; statement2; Important to use { } when there are multiple statements in the body! 14

Problem: Country Store Version 2 Enhance the checkout program to apply the following discount based on final total price. 15 Total priceDiscount $50 and above10% $75 and above15% $100 and above20%

Pseudocode/idea After computing the total: if (total > 100) apply 20% else if (total > 75) apply 15% else if (total > 50) apply 10% 16

Java : switch structure switch (num) { case 0: …. break; case 1: …. break; case 2: … break; case 3: … break; default: … } if (num == 0) … else if (num == 1) … else if (num == 2) … else if (num == 3) … else … 17 Note: int or char is commonly used ones with switch(). Real numbers cannot be used with switch().

series of if statements vs. switch() case statements within switch() look bit cleaner, compared to so many IF conditions. 18

Problem: Math practice Program should come up with 2 random integers (first one between 1 and 100 and second one between 1 and 20) and randomly select an operator (+, -, * or /) and post the question to the user. Get the answer and validate and output a message. Sample input & output: 45 * 15 ? 675 Very good. 19

Ideas Use Java’s random number generator to get numbers. For operator, generate random number 0 to 3, then map it to operator (+, -, *, /) using switch statement. See MathPractice.java for full Java code. 20

Repetition structures in Java while (condition) statement; while (condition) { statement1; statement2; … } do { statement1; … } while (condition); for( int i=0 ; i<n ; i++ ) statement; for( int i=0 ; i<n ; i++ ) { statement1; statement2; … } 21

while vs. do … while vs. for body of while loop may not execute at all! body of do…while loop is guaranteed to execute at least once. for loop is a simpler version of while loop & it is used when we know exact # of times loop needs to be executed. 22

Problem: Lotto: 6 numbers between 1 and 50 23

Idea Repeat the loop until -1 is seen as input. Keep track of # of input items Compute the average as total / count 24

break statement breaks the loop and continues to the statement after the loop body: 25

continue statement Ignores the lines below that statement and continues with the loop. 26

Problem: Math Practice - Version 2 Make the user answer 10 questons and keep track of user’s performance. Output the final score. Here is a sample message after answering 10 questions: You got 7 correct and 3 wrong. Play again soon! 27

Ideas use for loop to repeat 10 times use loop variable as question # use 2 variables to keep track of correct/incorrect – increment as needed print final stats (# correct, # incorrect) 28

Problem: Math Practice - Version 3 Same as Version 2, but uses additional method for playing the game. See the code for details. 29

For advanced level students only Let us say we want to control the distribution of questions per operator. For example, let us say we want addition problems for ~35% of the time, subtraction problems for another ~35% of the time, multiplication problems for ~20% of the time, and integer division problems for remaining ~10%. We can even make it more generic: We can prompt & get those % values from the user, then we can try to setup the distribution of questions accordingly. I will be happy to discuss your ideas in the class after each session is over (after 12 noon). 30

Problem: Country Store Version 3 Change the input mechanism for the store – list all 5 products every time, let the user select a product, then enter the weight. Keep adding the purchase to total, repeat the prompt until the user is done. 31

Country Store Version 3 : Prompt Available products: 1.Bananas ($ 0.44 / lb) 2.Apples ($ 0.99 / lb) 3.Cucumbers ($ 1.19 / lb) 4.Carrots ($ / lb) 5.Oranges ($ 0.79 / lb) Enter selection (0 to finish check-out) : 2 Enter weight:

Guessing game Pair up with your neighbor and play this game: Think of a number between 1 and 100. Ask your neighbor to guess that number. Repeat the following steps as many times as needed: Neighbor asks, “Is it NN?” You respond with “yes!” or “go lower” or “go higher” Goal is to ask minimum # of questions. 33

Guessing game – ideas? Ask about the middle value Based on the response, we can focus on one- half of the range. Repeat the top 2 steps until you say “yes!” 34

Let the computer find your number: Guessing game Think of a number between 1 and 100. Write a program so that the computer will ask you a series of questions and determine that number based on your answers. Repeat the following steps as many times as needed: Computer asks, “Is it NN?” User responds with 35

Guessing game : Sample runs Is it 50? < Is it 25? > Is it 37? > Is it 43? = Good game! Is it 50? < Is it 25? < Is it 12? > Is it 18? > Is it 21? < Is it 19? > Your number is 20. Good game! 36

Pseudocode Initialize range (low = 1, high = 100) while (true) – compute mid = (low + high) / 2 – ask the user – user responds with, = String input = keyboard.next(); – =  we are done! if (input.equals("<")) – <  high = mid-1 // go into first half. – >  low = mid+1 // go into second half. 37

Ideas for coding Get the user input as a String. String input = keyboard.next(); Since String is a complex data type, it needs to be compared like (input.equals("<")) You can also check the first character of the string alone: (input.charAt(0) == '<‘) 38

Reverse Guessing game Let the computer think of a number between 1 and 100 (In other words, generate a random number from 1 to 100 range). Write a program so that the computer will respond to your guesses until the number is guessed. Repeat the following steps as many times as needed: You say, “NN” Computer responds with “Yes! Good job!!”, “go lower!” or “go higher!” 39

Reverse Guessing game : Sample runs Enter your guess: 80 go higher! Enter your guess: 95 go lower! Enter your guess: 90 Yes! Good job!! Enter your guess: 20 go higher! Enter your guess: 60 go lower! Enter your guess: 40 go higher! Enter your guess: 45 go higher! Enter your guess: 50 Yes! Good job!! 40

Pseudocode Computer thinks of a number – uses random number generator – Random generator = new Random(); – int number = generator.nextInt(100) + 1 while (user has not guessed it correctly yet) – get user’s guess – compare and output appropriate message if (guess == number) if (guess < number) if (guess > number) 41

Reverse Guessing game Version 2 What is the point of playing a game if it does not output points? Let us enhance the reverse guessing game to output the # of points based on your performance. 42 # of guessesPoints and above16 - # of guesses, but do not go negative.

Ideas have a variable count to keep track # of guesses use switch() statement in the bottom to convert # of guesses to actual points. 43

Hangman Game 44

For more details Java language basics : official tutorial 45