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

1 Introduction To Programming in Java p2 v4

This document contains class notes on object-oriented programming in Java. It covers several topics: - Data types in Java including primitives like int, double, char and non-primitives like String. It shows the size and range of primitive types. - Variables, operators, and how to perform basic math operations in Java. - Methods for getting input from the keyboard using the Scanner class. - Conditionals and examples of if/else statements. - Assignments for students to create programs that perform various math operations on numbers entered from the keyboard and save them with their student ID.

Uploaded by

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

1 Introduction To Programming in Java p2 v4

This document contains class notes on object-oriented programming in Java. It covers several topics: - Data types in Java including primitives like int, double, char and non-primitives like String. It shows the size and range of primitive types. - Variables, operators, and how to perform basic math operations in Java. - Methods for getting input from the keyboard using the Scanner class. - Conditionals and examples of if/else statements. - Assignments for students to create programs that perform various math operations on numbers entered from the keyboard and save them with their student ID.

Uploaded by

Trouble Tonagu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

OOP class notes Ene – Abr 2023 26/12/22

2: More types, Methods, Conditionals


Outline

• Lecture 1 Review

• More types

• Methods

• Conditionals

Data Types
Kinds of values that can be stored and manipulated.

More usuals:

boolean: Truth value (true or false).

int: Integer (0, 1, -47).

double: Real number (3.14, 1.0, -2.1).

String: Text (“hello”, “example”).

More about data types

Primitives:

byte, short, int, long, float, double, char, boolean

Type size Range to remember

Byte integer 8 bits -128 a 127 28 / 2

Short integer 16 bits -32,768 a 32767 216 / 2

Int integer 32 bits -2,147,483,648 a 2,147,483,647 232 / 2

Long integer 64 bits -(2^63) a (2^63)-1 264 / 2

Float Float point, 32 bits ±10^(-45) a ±10^38

Double Float point, 64 bits ±10^(-324) a ±10^308

Char Unicode Character 16 bits 0 a 65535

boolean Boolean True & False

//Console program that shows the size of some data types


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

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 1


OOP class notes Ene – Abr 2023 26/12/22

/* in the following block of code the variables are declared


the syntax is data_type variable_name */
byte numPeq1;
short numPeq2;
int Number;
long bigInteger;
float integer1Decimals;
double integer2Decimals;
char symbol;
String str1ng;

//in the following block values are assigned to the variables


numPeq1 = 127;
numPeq2 = 32767;
Number = 2147483647;
bigInteger = 1234567890111213l; // the last character is l lowercase
integer1Decimals = 250.456f;
integer2Decimals = 360.789d;
symbol = '*';
str1ng = "hi chav@";

/*
numPeq1 = numPeq1 + 1;
numPeq2 = numPeq2 + 1;
Number = Number + 1;
//remove multiline comments and recompile
// and run the program
*/

//in the next block the values are displayed on the screen
System.out.println( "integer is " + numPeq1 );
System.out.println( "the integer is " + numPeq2 );
System.out.println( "integer is " + Number );
System.out.println( "bigInteger is " + bigInteger );
System.out.println( "integer1 with decimals is " + integer1Decimals );
System.out.println( "integer2 with decimals is " + integer2Decimals );
System.out.println( "the symbol is " + symbol );
System.out.println( "string is " + str1ng );

} //end of main method

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 2


OOP class notes Ene – Abr 2023 26/12/22
} //end of class SizeSomeTypes

Variables
Named location that stores a value

Example:
String a = “a”;
String b = “letter b”;
a = “letter a”;
String c = a + “ and ” + b;

Operators
Symbols that perform simple computations

Assignment: =

Addition: +

Subtraction: –

Multiplication: *

Division: /

Modular Division: % (obtain the division remainder)

all of them are binary operators. Need 2 operands to make computations.

Assignment solution
public class GravityCalculator {
public static void main(String[] args) { // begin main method
double gravity = -9.81;
double initialVelocity = 0.0;
double fallingTime = 10.0;
double initialPosition = 0.0;
double finalPosition = 0.5 * gravity * fallingTime * fallingTime;
finalPosition = finalPosition + initialVelocity * fallingTime;
finalPosition = finalPosition + initialPosition;
System.out.println("An object's position after " + fallingTime + " seconds is " +
finalPosition + " m." );
} // end main method
} // end of class GravityCalculator

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 3


OOP class notes Ene – Abr 2023 26/12/22

finalPosition = finalPosition + initialVelocity * fallingTime;


finalPosition = finalPosition + initialPosition;
OR with asignation operators
finalPosition += initialVelocity * fallingTime;
finalPosition += initialPosition;

Questions from last lecture?

Intro data from keyboard


To introduce data to the program we can use the console and a few instructions.

• You need to import a package that contains a particular class, the Scanner class.

• Create a new object.

• Use the object to collect data from the keyboard.

//console program that adds two integers and displays the result
//The java.util package is needed
import java.util.Scanner; //and use the Scanner class

public class AddTwoNums {


public static void main(String[] args) { // begin main method

//declaration of variables
int num1; //first number to add
int num2; //second number to add
int result; //result of the sum

// object that collects the characters that we press on the keyboard


Scanner read = new Scanner(System.in);

//Request input data


System.out.print( "Give me the addend 1: " );
num1 = read.nextInt(); // the data is assigned to the variable
System.out.print( "Give me the addend 2: " );
num2 = read.nextInt(); // the data is assigned to the variable

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 4


OOP class notes Ene – Abr 2023 26/12/22
//sum of the two numbers
result = num1 + num2;

//Show result on screen


System.out.println( "The sum of " + num1 + " + " + num2 + " = " + result );

read.close();
} //end main method
} //end of class AddTwoNums
fuente: http://lineadecodigo.com/java/sumar-dos-numeros-con-java/

If you don't close the read object after you've finished using it, there may be some negative implications for your
program. Proper closing of the Scanner object is a good practice to ensure proper resource management and
prevent potential problems.
Memory leaks: If you don't close the Scanner class object, the underlying resources might not be freed, which could cause a memory leak.
Every time you create a new Scanner object, a memory buffer is reserved to store the input. If these resources are not freed properly, your
program could run out of memory over time.

Input stream blocking: In some cases, not closing the Scanner object could cause the input stream to become blocked, meaning that you
won't be able to receive any more input from the user or from other input streams (such as files). This could result in unexpected behavior
of your program.

Potential Conflicts: If your program tries to create another Scanner object in the same input stream without closing the previous one, it
could cause conflicts and errors when reading data.

Assignment.

Tomando como base el programa AddTwoNums.java haga otro programa que: a) En lugar de sumar los dos
números ahora los reste y los multiplique; b) muestre ambos resultados; c) guarde el programa y la clase
principal como DosNumsOperaciones1_suMatricula.

Tomando como base el programa AddTwoNums.java haga otro programa que: a) Ahora divida el primero entre
el segundo y luego divida el segundo entre el primero; b) muestre ambos resultados; c) guarde el programa y la
clase principal como DosNumsOperaciones2_suMatricula.

Tomando como base el programa AddTwoNums.java haga otro programa que obtenga la división modular (resto
de la división o residuo de la división) a) del primero entre el segundo; b) del segundo entre el primero; c)
muestre ambos resultados; c) guarde el programa y la clase principal como DosNumsOperaciones3_suMatricula.

Tomando como base el programa AddTwoNums.java haga otro programa que: a) permita la entrada de un tercer
número; b) sume el resultado de la primera suma con el tercer número; c) La variable de la tercera suma se
llame resul_final; d) muestre los resultados de las dos sumas; e) guarde el programa y la clase principal como
SumaTresNums_suMatricula.

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 5


OOP class notes Ene – Abr 2023 26/12/22

Assignment.

Find instructions for entering values from the console for the data types char, short, long, float, double, and String
object.

Conversion between different data types in Java.

See next links


• https://www.w3schools.com/java/java_type_casting.asp
• https://www.aprenderaprogramar.com/index.php?option=com_content&view=article&id=636:conversion-de-
tipos-de-datos-en-java-tipado-ejemplos-metodo-valueof-error-inconvertible-types-
cu00670b&catid=68&Itemid=188
• https://javadesdecero.es/basico/conversion-tipo-ejemplos-casting/

//console program that adds three integers and displays the result
//The java.util package is needed
import java.util.Scanner; //and use the Scanner class

public class SumThreeNums {


public static void main(String[] args) {

//declaration of variables
int num1; //first number to add
float num2; // second number to add
double num3; //third number to add
int result; //result of the sum

// object that collects the characters that we press on the keyboard


Scanner read = new Scanner(System.in);

//Request input data


System.out.print( "Give me the addend 1 (Integers and decimals): " );
num1 = read.nextInt();
System.out.print( "Give me the addend 2 (Integers and decimals): " );
num2 = read.nextFloat();
System.out.print( "Give me the addend 3 (Integers and decimals): " );
num3 = read.nextDouble();

//sum of the three numbers


result = num1 + num2 + num3;

/* this exercise allows you to test the importance of data types

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 6


OOP class notes Ene – Abr 2023 26/12/22
remember that int is 32 bits, float is 32 bits and double is 64 bits
The operands must be of equal or smaller representation than the variable.
which will receive the result, that is...
result can be int if the operands are int
result can be float if the operands are int or float
result can be double if the operands are int, float, or double
if result is int and any of the operands are float or double, you must
cast them (convert them to int) with (int) before of variable.
if result is float and any of the operands are double, you must
cast them with (float) before of variable.
*/
//Show result on screen
System.out.println( "The sum of " + num1 + " + " + num2 + " + " + num3 +
" = " + result );

read.close();

} //end of main method


} //end of the class SumThreeNums

Outline
• Lecture 1 Review

• More types

• Methods

• Conditionals

Division
Division (“/”) operates differently on integers and on doubles!

Example:
double a = 5.0/2.0; // result a = 2.5
double d = 5/2; // d = 2.0
int b = 4/2; // b = 2
int c = 5/2; // c = 2

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 7


OOP class notes Ene – Abr 2023 26/12/22

Order of Operations
Precedence like math, left to right Right hand side of = evaluated first.

Parenthesis increase precedence.


double x = 3 / 2 + 1; // x = 2.0
double y = 4 / (2 + 1); // y = 1.0

Mismatched Data Types


Java verifies that data types always match:
String five = 5; // ERROR!

test.java.2: incompatible types: int cannot be converted to String


String five = 5;
^
test.java.2: incompatible types: int cannot be converted to String

file name . line # with error : type error : bug detail

Conversion by casting
int a = 2; // a = 2
double a = 2; // a = 2.0 (Implicit)
double a = 3.5f; // a = 3.5 (Implicit)

int a = 18.7; // ERROR


int a = (int)18.7; // a = 18

double a = 2/3; // a = 0.0


double a = (double)2/3; // a = 0.6666…

Outline
• Lecture 1 Review

• More types

• Methods

• Conditionals

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 8


OOP class notes Ene – Abr 2023 26/12/22

Methods
public static void main( String[ ] arguments )

System.out.println( ”hi” );

Adding Methods
public static void NAME_Method() {

STATEMENTS

To call a method: NAME_Method();

A method in Java is a block of code that, when called, performs specific actions mentioned in it. For instance, if
you have written instructions to draw a circle in the method, it will do that task. You can insert values or
parameters into methods, and they will only be executed when called. Source.

public class NewLine {

public static void newLine() {

System.out.println( " * " );

} // end method newLine()

public static void threeLines() {

newLine(); newLine(); newLine();

} // end method threeLines()

public static void main( String[ ] arguments ) {

System.out.println( "Line 1" ); first executable statement

threeLines();

System.out.println( "Line 2" );

} // end method main()

} // end class NewLine

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 9


OOP class notes Ene – Abr 2023 26/12/22

public class NewLine {

public static void newLine() {

System.out.println( " * " );

} // end method newLine()

public static void threeLines() {

newLine(); newLine(); newLine();

} // end method threeLines()

public static void main(String[ ] arguments) {

System.out.println( "Line 1" );

threeLines(); method call, it calls to...

System.out.println( "Line 2" );

} // end method main()

} // end class NewLine

public class NewLine {

public static void newLine() {

System.out.println( " * " );

} // end method newLine()

public static void threeLines() {

newLine(); newLine(); newLine();

} // end method threeLines()

public static void main(String[ ] arguments) {

System.out.println( "Line 1" );

threeLines();

System.out.println( "Line 2" );

} // end method main()

} // end class NewLine

Parameters

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 10


OOP class notes Ene – Abr 2023 26/12/22

public static void NAME_Method ( DATA_TYPE NAME ) {

STATEMENTS

To call: NAME_Method( EXPRESSION );

public class Square {

public static void printSquare( int x ) {

System.out.println( x*x );

} // end method printSquare()

public static void main( String[ ] arguments ) {

int value = 2;

printSquare( value );

printSquare( 3 );

printSquare( value*2 );

} // end method main()

} // end of class Square

public class Square2 {

public static void printSquare( int x ) {

System.out.println( x*x );

} // end method printSquare()


public static void main( String[ ] arguments ) {

printSquare( "hello" );

printSquare( 5.5 );

} // end method main()

} // end of class Square

What’s wrong here?

public class Square3 {

public static void printSquare( float x ) {

System.out.println( x*x );

} // end method printSquare()

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 11


OOP class notes Ene – Abr 2023 26/12/22

public static void main( String[ ] arguments ) {

printSquare( (double) 5 );

} // end method main()

} // end of class Square3

What’s wrong here?

Multiple Parameters
[…] NAME_Method( DATA_TYPE NAME1 , DATA_TYPE NAME2 ) {

STATEMENTS

To call: NAME_Method ( arg1, arg2 );

public class Multiply {

public static void times ( double a, double b ) {

System.out.println( “1er valor: ” + a + “ 2do valor: ” + b ); System.out.println( a * b );

} // end times method

public static void main( String[ ] arguments ) {

times ( 2, 2 );

times ( 3, 4 );
} // end main method

} // end of class Multiply

Return Values
public static DATA_TYPE NAME_Method() {

STATEMENTS

return EXPRESSION;

void means “no type” and does not have a return expression, like the previous examples.

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 12


OOP class notes Ene – Abr 2023 26/12/22

public class Square3_v2 {

public static double calcSquare( double x ) {

double squa_re;

squa_re = x*x;

return squa_re;

} // end of method calcSquare

public static void main( String[ ] arguments ) {

System.out.println( calcSquare( 5 ) );

} // end main method

} // end of class Square3_v2

public class Square4 {

public static double square( double x ) {

return x*x;

} // end of method square

public static void main( String[ ] arguments ) {

System.out.println( square( 5 ) );

System.out.println( square( 2 ) );

} // end main method

} // end of class Square4

Classroom Exercises
Make a program that calculates the value of “y” in the following equation, y = Ax2 + Bx + C. Use the following
integer values, A = 2, B = -3, C = 5, x = 2. Use a method to do the calculation and return to return the result to the
main method. The expected value of y = 7.

Make a program that calculates the average of 3 whole degrees, which are 85, 93 and 65. The average
calculation must be done in a method, use return to return the result to the main method. The expected value of

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 13


OOP class notes Ene – Abr 2023 26/12/22

the average is 81.

Once completed, try the program with the values 85, 93 and 66; 85, 93 and 67. Why is the average the same if
the last grade was modified twice?

Variable Scope
Variables live in the block “{ }” where they are defined (scope)

Method parameters are like defining a new variable in the method

public class SquareChange {

public static void printSquare( int x ) {

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

x = x * x;

System.out.println( "Square x = " + x );

} // end of printSquare method

public static void main( String[ ] arguments ) {

int x = 5;

System.out.println( "main x = " + x );

printSquare( x );

System.out.println( "main x = " + x );

} // end main method

} // end of class SquareChange

public class Scope {

public static void newValues( int x, int y ) {

if ( x == 5 ) {

x = 18;

y = 72;

System.out.println( "x = " + x + " y = " + y );

} // end if

} // end of newValues method

public static void main( String[ ] arguments ) {


6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 14
OOP class notes Ene – Abr 2023 26/12/22

int x = 5; int y = 10; //change values of x and y in each run

newValues( x, y );

System.out.println( "x = " + x + " y = " + y );

} // end main method

} // end of class Scope

Methods: Building Blocks


• Big programs are built out of small methods

• Methods can be individually developed, tested and reused

• User of method does not need to know how it works

• In Computer Science, this is called “abstraction”

Assignment.

To practice the subject of methods with parameters, you are going to convert the 4 programs from the previous
homework to programs that use methods with parameters.

File names can be the same by adding an underscore, an M, a y and a P, m for methods and p for parameters.

For example: DosNumsOperaciones1_MyP.java

Mathematical Functions
Math.sin( x )
Math.cos( Math.PI / 2 )
Math.pow( 2, 3 )
Math.log( Math.log( x + y ) )

Classroom Exercises. Use function Math.pow()


• Make a program that allows you to find the area of any circle. Formula A = π r2.

• Using the formula y = ax2 + bx + c, write the program that calculates the value of "y" for any values of x, a,
b, and c.

Exercise 1
Secondary method
- Receive values with parameters method (Parameters)

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 15


OOP class notes Ene – Abr 2023 26/12/22

- Do calculations area_sc = ¿?
- Return results to main method return area_sc

Main method
- Send values using arguments method (arguments)
- Receives values (results) with the call to the method (arguments) // you can assign the call to a variable
secondary method
Use System.out to display results //use the variable of one step before
- Displays results on screen

Note: To distinguish the arguments from the parameters, add to the names _m
Clues: 3.1416 and 3.4 radio, area is 36.3168 u2 for main; _sc for secondary
3.1416 and 5.2 radio, area is 84.948 u2

Exercise 2
Secondary method
- Receive values with parameters method (Parameters)
- Do calculations y_sc = ¿?
- Return results to main method return y_sc

Main method
- Send values using arguments method (arguments)
- Receives values (results) with the call to the method (arguments) // you can assign the call to a variable
secondary method
Use System.out to display results //use the variable of one step before
- Displays results on screen

Note: To distinguish the arguments from the parameters, add to the names _m
Clues (a, b,c, x): 2.3, 3.2, 1.4, 1.8; y = 14.612 for main; _sc for secondary
(a, b,c, x): 3.5, 1.3, 2.8, 2.4; y = 26.08

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 16


OOP class notes Ene – Abr 2023 26/12/22

The notepad++ can be configured to allow us to compile and run the programs with a simple combination of keys
(shortcut).

The commands to use are:

Compile : cmd /c cd $(CURRENT_DIRECTORY) & javac $(FILE_NAME) & pause

Run : cmd /c cd $(CURRENT_DIRECTORY) & java $(NAME_PART) & pause

Menu “Ejecutar”

Copy command to compile – “Guardar” button

Type the name of the process and select a key combination to


call it when needed.

Suggestion: ALT + SHIFT + C

C for “compile” a program.

OK button

Close window “Run”.

Proceed in the same way to add the process of Run a program.

Suggestion: ALT + SHIFT + R key combination to run a program. R for “run” a program.

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 17


OOP class notes Ene – Abr 2023 26/12/22

Outline
• Lecture 1 Review

• More types

• Methods

• Conditionals

if statement
if ( CONDITION ) {

Instructions codeblock 1

//name this class First_if

public static void test( int x ) {

if ( x > 5 ) {

System.out.println( x + " is > 5" );

} // end if

} // end of test method

public static void main( String[ ] arguments ) {

test( 4 );

test( 5 );

test( 6 );

} // end main method

Comparison operators
x > y: x is greater than y

x < y: x is less than y

x >= y: x is greater than or equal to x

x <= y: x is less than or equal to y

x == y: x equals y

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 18


OOP class notes Ene – Abr 2023 26/12/22

( equality: ==, assignment: = )

Boolean operators
&& : logical AND

|| : logical OR

Truth table for logical operations and, or taking the input values as P and Q.

P Q AND OR
T T T T
T F F T
F T F T
F F F F

Example.

if (x > 6) { if ( x > 6 && x < 9 ) {

if (x < 9) { …

… }

else
if (CONDITION) {

Instructions codeblock 1

} else {

Instructions codeblock 2

//name this class Second_if

public static void test( int x ) {

if (x > 5) {

System.out.println( x + " is > 5" );

} else {

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 19


OOP class notes Ene – Abr 2023 26/12/22

System.out.println( x + " is not > 5" );

} // end if

} // end of test method

public static void main( String[ ] arguments ) {

test( 4 );

test( 5 );

test( 6 );

} // end main method

else if
if (CONDITION1) {

codeblock 1

} else if (CONDITION2) {

codeblock 2

} else if (CONDITION3) {

codeblock 3

} else {

codeblock 4

//name this class Third_if

public static void test( int x ) {

if ( x > 5 ) {

System.out.println( x + " is > 5" );

} else if ( x == 5 ) {

System.out.println( x + " equals 5" );

} else {

System.out.println( x + " is < 5" );

} // end of successive if’s

} // end of test method

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 20


OOP class notes Ene – Abr 2023 26/12/22

public static void main(String[ ] arguments) {

test( 6 );

test( 5 );

test( 4 );

}// end main method

Classroom Exercises
Make a program that allows you to enter (from keyboard) the name and age of two people and that shows on the
screen the name of the older of the two.

Clues: 1. Monica, 25; Oscar, 29. Older is Oscar. 2. Jorge, 36, Diana, 26. Older is Jorge.

3. Monica Lopez, 25; Oscar Gomez, 29. Older is Oscar Gomez.

4. Jorge Juarez, 36, Diana Perez, 26. Older is Jorge Juarez.

Develop a program in which according to a numerical grade shows its equivalent in letter according to the
following table. You could see this.

Grade Range of qualifications


A 100 a 90
B 89 a 80
C 79 a 70
D 69 a 60
F 59 a 0

Questions?

Assignment: FooCorporation
FooCorporation needs a program to calculate how much to pay their employees.

Pay is obtained by multiplying hours worked by hourly pay. The base pay must be no less than $8.00/hour. (Do a
validation). Overtime is more than 40 hours, and paid 1.5 times base pay. The maximum number of hours must be
no more than 60/week. (Do a validation).

Use a particular method to do calculations and to display results, use the if statement where necessary or
convenient. The main method will call to method and will send values to method. Arguments to send will be base
pay and hours worked.

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 21


OOP class notes Ene – Abr 2023 26/12/22

Reminder
• Write your own code

• Homework due past tomorrow 6pm on Teams.

Conversion by method
int to String:
String five = 5; // ERROR!
String five = Integer.toString (5);
String five = “ ” + 5; // five = “5”

String to int:
int foo = “18”; // ERROR!
int foo = Integer.parseInt ( “18” );

Comparison operators
Do NOT call == on doubles! EVER.
double a = Math.cos (Math.PI / 2);
double b = 0.0;

a = 6.123233995736766E-17

a == b will return FALSE!

Solved exercises
Make a program that allows you to enter the name and age of two people and that shows on the screen which of
the two is older.
import java.util.Scanner;
public class CadenaCaracteres1_v3 {
public static String edadMayor ( int edd_1, String nam_1, int edd_2, String nam_2) {
String nam_sc;
if (edd_1 > edd_2) {
nam_sc = nam_1;

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 22


OOP class notes Ene – Abr 2023 26/12/22
} else {
nam_sc = nam_2;
} //end if
return nam_sc;
}// end of edadMayor method

public static void main (String [ ] args) {


Scanner leer = new Scanner( System.in );

// variable declaration
String nombre1, nombre2;
int edad1, edad2;

// input data
System.out.print( "name 1st person " );
nombre1 = leer.next();
System.out.print( "age 1st person ");
edad1 = leer.nextInt();
System.out.print( "name 2nd person " );
nombre2 = leer.next();
System.out.print( "age 2nd person " );
edad2 = leer.nextInt();

// method call
String name;
name = edadMayor ( edad1, nombre1, edad2, nombre2 );

// display results
System.out.println( "la persona de mayor edad es " + name );

leer.close();

} // end main method


} // end of class CadenaCaracteres1_v3

import java.util.Scanner;
public class Calif_num_a_calif_letra {
public static String convNum2Letra ( int cal) {

String cal_let = " ";

if (cal >= 90 && cal <= 100) {


cal_let = " La calif es A ";}
else if (cal >= 80 && cal <= 89) {
cal_let = " La calif es B "; }

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 23


OOP class notes Ene – Abr 2023 26/12/22
else if (cal >= 70 && cal <= 79) {
cal_let = " La calif es C "; }
else if (cal >= 60 && cal <= 69) {
cal_let = " La calif es D "; }
else if (cal >= 0 && cal <= 59) {
cal_let = " La calif es F "; }

return cal_let;
} // end of convNum2Letra method

public static void main (String [] args) {


Scanner leer = new Scanner( System.in );

// variable declaration
int cal_num;
// input data
System.out.print( "give me the calif from 0 to 100 " );
cal_num = leer.nextInt();

// method call
String cal_letra;
cal_letra = convNum2Letra (cal_num);

System.out.println( "La calif con letra es " + cal_letra );

leer.close();

} // end main method


} // end of class Calif_num_a_calif_letra

Proposed problems to practice


1. Make a program that allows calculating, and showing on screen, the average having as data 3 grades of a
student, in addition to showing on the screen if the student is approved or not. The minimum pass is 75.

2. Make a program that identifies whether a number is even or odd by displaying a message on the screen

3. Make a program that determines which is the largest of three different numbers integers. This exercise can
be done in several ways, the most obvious is the one in which successive comparisons are made.

Set num1 num2 num3 largest is


1 10 5 2 num1
2 10 2 5 num1
3 2 10 5 num2

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 24


OOP class notes Ene – Abr 2023 26/12/22

4 5 10 2 num2
5 5 2 10 num3
6 2 5 10 num3

4. Make a program that identifies if a number is divisible by 3 exactly (it means that the remainder is zero) by
displaying a message on the screen

5. Make a program that identifies if a number is divisible by 3 exactly (it means that the remainder is zero) by
displaying a message on the screen; is divisible by 9 exactly, and if is divisible by 3 and 9 at the same
time.

Exercise 1 OPTION1
Secondary method Since the methods we have seen can only return one value, we will have to use
two methods, one to return the average and other to return the status.
- Receive values with parameters
- calculate Average
method1 (Parameters)
- Based on the minimum passing rate,
determine the student status (pass or fail) Prom = ( cal1 + cal2 + cal3 ) / 3
- Return results to main method return Prom

Main method method2 (Parameters)


- Send values using arguments Prom = ( cal1 + cal2 + cal3 ) / 3
- Receives values (results) with the call to the if ( Prom >= 75 )
secondary method
True? status = “Pass” False? status = “Fail”
- Displays results on screen
return status

Clues: 75, 62, 58, Prom is 65, “Fail”


main method (arguments)
85, 70, 79, Prom is 78, “Pass”
declaration of variables
request input data
call each method (arguments)
assign method1 to average variable
assign method2 to the status variable
display results on screen

OPTION2
method1 (Parameters the califs)
Prom = ( cal1 + cal2 + cal3 ) / 3
return Prom

method2 (Parameters only Prom)


if ( Prom >= 75 )
True? status = “Pass” False? status = “Fail”
return status

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 25


OOP class notes Ene – Abr 2023 26/12/22

main method (arguments)


declaration of variables
request input data
// call each method
Prom = method1 (arguments the califs)
status (arguments only Prom)
display results on screen

Exercise 2 Since the methods we have seen can only return one value, we will have to use
two methods, one to return the remainder and other to return the type of
Secondary method
number.
- Receive values with parameters
method1 (Parameters the number)
- calculate the remainder
rem = num % 2
- Determine if the number is even or odd based
return rem
on the remainder of the division.
- Return results to main method
method2 (Parameters only rem)
if ( rem == 0 )
Main method
True? type = “Even” False? type = “odd”
- Send values using arguments
return type
- Receives values (results) with the call to the
secondary method
- Displays results on screen main method (arguments)
declaration of variables
Clues: 11 is odd; 14 is even request input data
// call each method
Rem = method1 (argument the number)
Type = method2 (arguments only Rem)
display results on screen

Exercise 3 method1 (Parameters the three numbers)


Secondary method make successive comparisons of each number with the other two
- Receive values with parameters return largest
- identify the largest number of the three
- Return results to main method main method (arguments)
declaration of variables
Main method request input data
- Send values using arguments // call each method
- Receives values (results) with the call to the Largest = method1 (argument the number)
secondary method
display results on screen
- Displays results on screen

Clues: 10, 5, 2; the largest is 10


10, 2, 5; the largest is 10
5, 10, 2; the largest is 10

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 26


OOP class notes Ene – Abr 2023 26/12/22

2, 10, 5; the largest is 10


2, 5, 10; the largest is 10
5, 2, 10; the largest is 10

This teaching material is based on 6.092 Introduction to Programming in Java, January (IAP) 2010, which is available at MIT OpenCourseWare:
http://ocw.mit.edu, therefore has the Creative Commons license mentioned in https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode

For information about citing 6.092 Introduction to Programming in Java or yours Terms of Use, visit: http://ocw.mit.edu/terms.

6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 27

You might also like