Java Variables, Types, and Math Getting Started

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Primitive Data Types and Operations. Introducing Programming with an Example public class ComputeArea { /** Main method */ public static void main(String[]
Some basic I/O.
Computer Science A 2: 6/2. Course plan Introduction to programming Basic concepts of typical programming languages. Tools: compiler, editor, integrated.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Computer Programming Lab(5).
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 2 Elementary Programming.
 2005 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
1 Number Types  Every value in Java is either: 1.a reference to an object or 2.one of the eight primitive types  eight primitive types: a.four integer.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Primitive Types, Strings, and Console I/O Chapter 2.1 Variables and Values Declaration of Variables Primitive Types Assignment Statement Arithmetic Operators.
Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 2 Elementary Programming
C++ Programming: Basic Elements of C++.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Variables, Arithmetic, etc.)
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
CHAPTER 5 GC 101 Input & Output 1. INTERACTIVE PROGRAMS  We have written programs that print console output, but it is also possible to read input from.
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
Java Variables, Types, and Math Getting Started Complete and Turn in Address/Poem.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
1 Chapter 2: Java Fundamentals cont’d Spring Lory Al Moakar.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Java Methods 11/10/2015. Learning Objectives  Be able to read a program that uses methods.  Be able to write a write a program that uses methods.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Variables and Constants Chapter 4 Review. Declaring Variables A variable is a name for a value stored in memory. Variables and constants are used in programs.
import java.util.Scanner; class myCode { public static void main(String[] args) { Scanner input= new Scanner(System.in); int num1; System.out.println(“Enter.
1 1 Chapter 2 Elementary Programming. 2 2 Motivations In the preceding chapter, you learned how to create, compile, and run a Java program. Starting from.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Fundamentals 2 1. Programs and Data Most programs require the temporary storage of data. The data to be processed is stored in a temporary storage in.
CompSci 230 S Programming Techniques
Topic 2 Elementary Programming
Introduction to Java Applications
Chapter 2 Basic Computation
Elementary Programming
Chapter Goals To understand integer and floating-point numbers
Yanal Alahmad Java Workshop Yanal Alahmad
Goals Understand how to create and compare Strings.
Data types, Expressions and assignment, Input from User
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 2 Basic Computation
INPUT STATEMENTS GC 201.
Java Methods Making Subprograms.
IDENTIFIERS CSC 111.
Java Fix a program that has if Online time for Monday’s Program
Goals Understand how to create and compare Strings.
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2 Edited by JJ Shepherd
Goals Understand how to create and compare Strings.
Chapter 2: Basic Elements of Java
Java Methods Making Subprograms.
Java so far Week 7.
MSIS 655 Advanced Business Applications Programming
Fundamentals 2.
AP Java Review If else.
Chapter 2: Java Fundamentals
Java Fix a program that has if Online time for Monday’s Program
Java Methods Making Subprograms.
Lecture Notes - Week 2 Lecture-1. Lecture Notes - Week 2 Lecture-1.
Introduction to Java Applications
AP Java Review If else.
Unit 3: Variables in Java
Chapter 2 Primitive Data Types and Operations
Presentation transcript:

Java Variables, Types, and Math Getting Started Complete and Turn in Address/Poem

Learning Objectives Understand how to declare and use primitives variables. Be able to read a simple Java program. Be able to incorporate math expressions into a Java program Be able to find and use JavaDocs

Review // public static void main (String [] args) { } System.out.println(“Hello world”); System.out.print(“Hello world”); int num; num = 30; double num2; num = input.nextInt(); double num2 = input.nextDouble(); System.out.printf( “The second number is %5.2f\n", num2 ); }

Primitive Types (Not objects) byte short int (4 bytes) -2,147,483,648 to 2,1147,483,647 long +/-9,223,372,036,854,775,808 float double (8 bytes) 10 e +/-308 with 15 significant digits char boolean true or false

The variables exist while main is running. public class Interest { public static void main(String[] args) { /* Declare the variables. */ double principal=0; // The value of the investment. double rate, interest; // The annual interest rate. // Interest earned in one year. /* Do the computations. */ principal = 17000; rate = 0.07; interest = principal * rate; // Compute the interest. principal = principal + interest; // Compute value of investment after one year, with interest. // (Note: The new value replaces the old value of principal.) /* Output the results. */ System.out.print("The interest earned is $"); System.out.println(interest); // Can also use //System.out.print("The interest earned is $“ + interest); System.out.print("The value of the investment after one year is $"); System.out.println(principal); } // end of main() } // end of class Interest The variables exist while main is running.

Sort of primitive type, but it’s an object String A sequence of characters. The type declarations does start with an uppercase letter.

Variables in Programs Declare the variables inside the main subroutine. (For now) You can also declare variables where you need them. (Declare a looping variable at the loop) int numberOfStudents; String name; double x,y; boolean isFinished;

Use input.nextDouble(); for getting a double value Simple input and math import java.util.Scanner; // program uses class Scanner public class Addition { // main method begins execution of Java application public static void main( String args[] ) // create Scanner to obtain input from command window Scanner input = new Scanner( System.in ); int number1; // first number to add int number2, sum; // second number to add String name; System.out.print( "Enter first integer: " ); // prompt number1 = input.nextInt(); // read first number from user System.out.print( "Enter second integer: " ); // prompt number2 = input.nextInt(); // read second number from user System.out.print("Enter your name "); name = input.nextLine(); sum = number1 + number2; // add numbers System.out.printf( "Sum is %d\n", sum ); // display sum System.out.println("Thanks " + name);// Note: Uses the + for concatenating } // end method main } // end class Addition Use input.nextDouble(); for getting a double value

Displays the file name and a brief description of the program // Addition.java // Addition program that displays the sum of two numbers. Displays the file name and a brief description of the program

import java.util.Scanner; Import declaration This is a predefined class this program will use Package: A collection of classes. Java Class Library or Java Application Programming Interface (API): Collection of Packages This will use the Scanner class from the java.util package Note: All import declarations MUST appear before the first class declaration in the file. Placing an import declaration inside a class declaration’s body or after a class declaration is a syntax error. Note: “cannot resolve symbol” error->Forgetting to include an import declaration for a class used in your program.

public class Addition Begins the declaration of the Addition class. The file name must be Addition.java (case sensitive)

Scanner input = new Scanner( System.in ); Variable declaration Declares the variable (object) input is of type Scanner. Scanner enables the program to read data (numbers) for use in the program. = Declares that the Scanner variable input should be initialized in its declaration with the result of the expression newScanner(System.in) to the right side of the =. Creates a Scanner Object that can be used to read data entered through the keyboard.

int number1; // first number to add int number2; // second number to add int sum; // sum of number1 and number2 Declares three integer variables. -2,147,483,648 to 2, 147, 483, 647 Other types float like real numbers char: characters Primitive or built in types Variables follow identifier rules Start the variables with a lowercase letter. (Style)

System.out.print( "Enter first integer: " ); The prompt for user input Need to include a prompt for every value input

number1 = input.nextInt(); Uses the Scanner object input.nextInt() method to obtain an integer from the user at the keyboard. At this point the program waits for the user to type the number and press enter. This line is read “number1 is assigned the value of input.nextInt().”

Other common Scanner Methods for input Entering an Integer integerVariable = input.nextInt(); Entering a double doubleNumber = input.nextDouble(); Entering a String. Reads the entire line. stringVariable = input.nextLine(); Entering a String. Reads until it gets to a space stringVariable = input.next();

sum = number1 + number2; Calculates the sum of number1 and number2 and places the result in the integer variable sum.

System.out.printf( "Sum is %d\n", sum ); Displays the sum. Could also use System.out.printf( "Sum is %d\n", number1+number2 ); Or System.out.println(“Sum is “ + sum); But this will give a result you might not expect. System.out.println(“Sum is “ + number1 + number2);

Simple Integer Math Operations () * Multiply / Integer Division % MOD, The remainder of integer division. +, - Order of Operation *, /, %

Evaluate the following 5/2 24 / 15 15 / 24 5 % 2 24 % 15 17 % 12 140 / 25 140 % 25

Show javadocs On the left lists the different classes. Use the button on the class website to get to Javadocs Find the Math class and look up the following methods. PI sqrt pow To use these in a program you need to use the form ClassName.methodName(arguments if any) Math.method(arguments)

Examples ans = Math.sqrt(9); ans = Math.sqrt(16); ans = Math.pow(3); ans = Math.sqrt(Math.pow(3,2) + Math.pow(2,2));

Translate to Java Math Java 2(a+c) Ans=2*(a+c); 3x + 5y (1/2)bh πr2

Dry Run the Following int a, b, c = 20; double d = 1.0; a = c + 10; public class DryRun9_15_09 { public static void main(String[] args) int a, b, c = 20; double d = 1.0; a = c + 10; b = a + c; System.out.println("Numbers " + a +" " + b + " " + c); System.out.println(a+b+c); c = a % 7; b = a / 7; a = a + 2*b + c % 3; d = 1.0/3; System.out.println(d); System.out.printf("%5.2f \n", d); d = Math.sqrt(a-b); } Dry Run the Following

First Input Programs Mile to inch: YourNameMileToInch Input: The number of miles traveled Output: The equivalent distance converted to inches 5280 feet per mile, 12 inches per foot Change: YourNameChange Input: The amount of change in pennies Output: The least amount of coins it takes to make the change. Example: Input: 66 cents Output: To get 66 cents you need: 2 Quarters 1 Dime(s) 1 Nickel(s) 1 Cent(s)

Complete additional programs as pushes. Second Input Program Complete one of the following Quadratic formula Input: a, b and c (of type double) Output: The positive root (-b + sqrt(b2 – 4ac))/(2a) Distance formula Input: The x and y coordinates for two points Output the distance between the points: Distance = sqrt((y1-y2)2 + (x1-x2)2) Push: Calculate the distance between two points that are on a 3-D grid. That is they have an x, y, and z value. Given the lengths of three sides of a triangle, find the area of the triangle. Find a way to calculate this even if it is not a right triangle. (Do a little research) Complete additional programs as pushes.