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

1 Introduction To Programming in Java p3 v2 - 5

The document discusses good programming style in Java. It provides rules for naming variables, using indentation and whitespace, and avoiding duplicate tests. It also discusses using methods for different functions like displaying results or performing calculations.

Uploaded by

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

1 Introduction To Programming in Java p3 v2 - 5

The document discusses good programming style in Java. It provides rules for naming variables, using indentation and whitespace, and avoiding duplicate tests. It also discusses using methods for different functions like displaying results or performing calculations.

Uploaded by

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

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

3: Loops, Arrays

Frequent Issues (I)


The signature of the main method cannot be modified.
public static void main( String[] arguments ) {

...

} //end main method

Frequent Issues (II)


Return values: if you declare that the method is not void, then it has to return something!
public static int pay(double basePay, int hours) {

if (basePay < 8.0) return -1;

else if (hours > 60) return -1;

else {

int salary = 0;

...

return salary

} // end if’s

} //end of pay method

Frequent Issues (III)


Don't create duplicate variables with the same name
public static int pay(double basePay, int hours) {
int salary = 0; // OK

int salary = 0; // salary already defined!!

double salary = 0; //salary already defined!!

}

previous Assignment
Method to print pay based on base pay and hours worked

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


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

Overtime: More than 40 hours, paid 1.5 times base pay

Minimum Wage: $8.00/hour

Maximum Work: 60 hours a week

Assignment solution
public class WeeklyPay {
public static void pay( double basePay, int hours ) {
if (basePay < 8.0) {
System.out.println("You must be paid at least $8.00/hour");
} else if (hours > 60) {
System.out.println("You can't work more than 60 hours a week");
} else {
int overtimeHours = 0;
if (hours > 40) {
overtimeHours = hours – 40;
hours = 40;
} // end of successive if’s
double pay = basePay * hours;
pay = pay + overtimeHours * basePay * 1.5;
System.out.println("Pay this employee $" + pay);
} // end of successive if’s
} // end of pay method
public static void main( String[] arguments ) {
pay(7.5, 35);
pay(8.2, 47);
pay(10.0, 73);
} // end main method
} // end of class WeeklyPay

What we have learned so far


• Variables & types

• Operators

• Type conversions & casting

• Methods & parameters

• If statement

Today’s Topics
• Good programming style

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


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

• Loops, cycles,

• Arrays

Good programming style


The goal of good style is to make your code more readable.

By you and by others.

Applying KISS principle.

Rule #1: use good (meaningful) names


Some of the reasons for using explicit names are:

• Reduce the effort required to read and understand the source code.

• Improve the appearance of the source code, for example, by not allowing excessively long names or
unclear abbreviations.

String a1;

int a2;

double b;

A = b * h;

// all those are BAD!!

String firstName;

String lastName;

int temperature;

salary = hoursWorked * feePerHour;

// all those are GOOD

Rule #2: Use indentation


public static void main ( String[] arguments ) {
int x = 5;
x = x * x;
if (x > 20) {
System.out.println( x + “ is greater than 20.” );
}
double y = 3.4;
6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 3
OOP class notes Ene – Abr 2023 26/12/22
}

Have a demo with no indentation

Rule #3: Use whitespaces


Put whitespaces in complex expressions:

// BAD!!
double cel=fahr*42.0/(13.0-7.0);

// GOOD
double cel = fahr * 42.0 / ( 13.0 – 7.0 );

Rule #3: Use whitespaces


Put blank lines to improve readability:
public static void main ( String[] arguments ) {

int x = 5;
x = x * x;

if (x > 20) {
System.out.println(x + “ is > 20.”);
}

double y = 3.4;
}

Rule #4: Do not duplicate tests


if ( basePay < 8.0) {
...
} else if ( hours > 60 ) {
...
} else if ( basePay >= 8.0 && hours <= 60 ) {
...
}

BAD

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


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

Rule #4: Do not duplicate tests


if ( basePay < 8.0) {
...
} else if ( hours > 60 ) {
...
} else {
...
}

GOOD

More details? See next articles

https://www.thinkful.com/blog/coding-best-practices/

https://www.browserstack.com/guide/coding-standards-best-practices

Good programming style (summary). see document “Estilo de programación Java.odt”


• Use good names (meaningful) for variables and methods.

• Use indentation.

• Add whitespaces (spaces and white lines)

• Don't duplicate tests.

Methods can be used for the following functions


• Show messages as results or to request data
◦ showResults( total, sumGrades, average ); getInData();

• perform some calculation and return values to the main method


◦ sum = toSum(num1, num2);

In next program highlights the sections for data request, calculations or data processing, and display of results.
Reading data is done in the main method.
9 omitted lines
10
11 // get input data
12 solicitaDatos();
13 nom = readThis.readLine();
14 cal1 = Integer.parseInt(readThis.readLine());
15 cal2 = Integer.parseInt(readThis.readLine());
16
6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 5
OOP class notes Ene – Abr 2023 26/12/22
17 // Process information through operations
18 prom = procesaDatos(cal1, cal2);
19
20 // Display results
21 muestraResulta2(nom, prom);
22
23 }// fin del main
24
25 public static void solicitaDatos() {
26 System.out.println(" Introduce los datos en el orden mostrado");
27 System.out.println(" Sepáralos mediante un intro/enter");
28 System.out.println(" 1. dame tu nombre");
29 System.out.println(" 2. dame tu primer calificacion");
30 System.out.println(" 3. dame tu segunda calificacion");
31 }
32
33 public static double procesaDatos(int x1, int x2) {
34 double ret_prom;
35 ret_prom = (x1+x2)/2.0;
36 return ret_prom;
37 }
38

39 public static void muestraResulta2(String x_nom, double x_prom) {


40 System.out.println(" "+x_nom+" te informo que");
41 System.out.println(" tu promedio es "+x_prom);
42 }
43
44 }//fin de la clase

In the following program, the data request section is highlighted, since for each variable there is a method.
Reading data is done in child methods or functionality.
9 omitted lines
10
11 // get input data
12 nom = solicitaNombre();
13 cal1 = solicitaCal1();
14 cal2 = solicitaCal2();

15 // Process information through operations


16 prom = procesaDatos(cal1, cal2);
17 // Display results
18 muestraResulta2(nom, prom);
19
20 }// fin del main
21

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


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

22 public static String solicitaNombre() {


23 Scanner readThis = new Scanner(System.in);
24 String ret_nom;
25 System.out.println(" dame tu nombre");
26 ret_nom = readThis.nextLine();
27 return ret_nom;
28 }
29
31 public static int solicitaCal1() {
32 Scanner readThis = new Scanner(System.in);
33 int ret_cal1;
34 System.out.println(" dame la 1er calificación");
35 ret_cal1 = readThis.nextInt();
36 return ret_cal1;
37 }
38
39 public static int solicitaCal2() {
40 Scanner readThis = new Scanner(System.in);
41 int ret_cal2;
42 System.out.println(" dame la 2da calificación");
43 ret_cal2 = readThis.nextInt();
44 return ret_cal2;
45 }
46
47 omitted lines

Remember that, for the moment, methods can return only one value
if you need to do some calculus, and every calculus have assigned a variable, for every calculus you need one
method.

11 omitted lines
12
17 sum = toSum( num1, num2 );
18 subt = toSubtract( num1, num2 );
19 multip = toMultiply( num1, num2 );
20
21 omitted lines

continue below

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


OOP class notes Ene – Abr 2023 26/12/22
27
28 public static int toSum (int num1, int num2 ){
29 int resul;
30 resul = num1 + num2;
31 return resul;
32 }// fin del método sumar
33
34 public static int toSubtract (int num1, int num2 ){
35 int resul;
36 resul = num1 - num2;
37 return resul;
38 }// fin del método restar
39
40 public static int toMultiply (int num1, int num2 ){
41 int resul;
42 resul = num1 * num2;
43 return resul;
44 }// fin del método multiplicar

Proposed problems to practice


4. Make a program that allows you to enter three different integer values and that shows them ordered from
highest to lowest.
Clues. Try the following datasets

Set. num1 num2 num3 Highest is next lowest is


1 10 5 2 10 5 2
2 10 2 5 10 5 2
3 2 10 5 10 5 2
4 5 10 2 10 5 2
5 5 2 10 10 5 2
6 2 5 10 10 5 2

5. Make a program to determine if three different values representing sides can form a triangle. Suppose we
have variables A, B, and C, and each representing one side. Which of the following datasets allows us to
form a triangle and why?

Conj. A B C
1 5 10 3
2 5 10 5
3 5 10 7
What is it about that set (which allows us to form a triangle) that the other two don't have?

6. Make a program that calculates and displays on screen the daily wage of a worker who receives $ 11.00
for each hour of work and $ 19.55 for each overtime. The normal working day consists of 8 hours, above
that it is considered as overtime. If the working day exceeds 13 hours of work, 10% will be withheld as
savings. Use printf to limit decimals.

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


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

Clues. Review next data sets. For 7 worked hours, the daily wage is $77.00
For 12 worked hours, the daily wage is $166.20
For 15 horked hours, the daily wage is $202.365
7. Make a program that allows students of a university to calculate the payment of their monthly payments
based on the following criteria: a) when advancing monthly payments, a 10% discount will be applied. b) In
late monthly payments, an extra charge of 10% will be applied. c) The payment of the monthly payment of
the current month does not carry a discount but there is no extra charge. The amount of the monthly
payment is $ 650.00. Use printf to limit decimals.

Clues. Payment of an advance monthly payment and that of the current month, the total is $1,235.00.
Payment of a late monthly payment and that of the current month, the total is $1,365.00.
Payment of two late monthly payments and one for the current month and one in advance, the
total is $2,665.00
8. En una empresa se usa el salario mínimo diario ($207.5) como base para calcular el pago a sus
empleados. Se considera que una jornada normal de trabajo consta de 8 hrs diarias de trabajo. Para
obtener la tarifa por hora se toma el salario mínimo diario y la jornada normal de trabajo. El pago por hora
trabajada es 4 veces la tarifa por hora. La cantidad de horas trabajadas para jornadas normales de trabajo
es de 40 horas a la semana, arriba de esa cantidad se consideran como tiempo extra. Las horas extras se
pagan a 1.35 veces el pago por hora trabajada. Los impuestos se calculan en base a lo siguiente:

Salario neto hasta $3,200 es libre de impuestos.

Los siguientes $1,700 pesos causan un 22.5% de impuestos

y el resto causa un 27.3% de impuestos

El salario neto se calcula restando los impuestos al salario bruto.

La cantidad mínima de horas trabajadas es de 8 y la máxima es de 60 horas a la semana. Hacer


validaciones para ambas condiciones.

Usar Métodos. Dos y tres métodos, 60 de calif. Cuatro y cinco métodos, 75 de calif. 6 y 7 métodos, 100 de calif

Pistas:
Con 20 horas de trabajo el salario bruto es de $2,075, los impuestos son de $0.0 y el salario neto es de $2,075.

Con 40 horas trabajadas el salario bruto es de $4,150, los impuestos son de $ 213.75 y el salario neto es de $3,936.25.

Con 52 horas trabajadas el salario bruto es de $5,830.75, los impuestos son de $ 636.59 y el salario neto es de $5,194.16.

Con 7 horas de trabajo el programa no puede continuar y todos los resultados están en cero.

Con 63 horas trabajadas el programa no puede continuar y todos los resultados están en cero.

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


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

Loops

Counter and accumulator


Counter variable

When working with repetitive loops, we are often interested in knowing in which repetition we are in. To count
repetitions, we use a variable called counter.

The technique is:

1. Initialize a variable to zero or one, before the repeating cycle.

2. Within the repetitive cycle, we increase the variable in one or other number that be convenient

Accumulator variable

It is similar to the counter. It is initialized to zero and is incremented in each repetition with different values.

The result is that the variable accumulates the sum of the values added in each repetition:

Supouse that you have


static void main (String[] arguments) {

System.out.println( “Rule #1” );

System.out.println( “Rule #2” );

System.out.println( “Rule #3” );

What if you want to do it for 200 Rules?

Loop operators allow to loop through a block of code.

There are several loop operators in Java.

The while operator


while ( condition ) {
// code block to be executed
statements
} // end while
The while statement continually executes a block of statements while a particular condition is true.

public class WhileExample1 {


public static void main(String[] args) {
6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 10
OOP class notes Ene – Abr 2023 26/12/22
int i = 0;
while (i < 5) {
System.out.println(“Number is: ” + i);
i = i + 1;
} // end while
} // end main method
} // end class WhileExample1

Note: i = i + 1 may be replaced by i++

Count carefully.

Make sure that your loop has a chance to finish. Do not forget to increase the variable used in the condition,
otherwise the loop will never end!

The while operator


When you don't know exactly how many times you want to repeat a block of code, use the while loop this way
public class WhileExample2 {
public static void main(String[] args) {
Scanner read = new Scanner( System.in );
int resp = 1; // response
while ( resp == 1 ) {
System.out.println(“Print this” );
System.out.println(“Do you want repeat? 1=yes / other number = not” );
resp = read.nextInt();
} // end while
read.close();
} // end main method
} // end class WhileExample2

The do...while operator


do {
// code block to be executed
statements
} while ( condition ); // end do_while

The difference between do-while and while is that do-while evaluates its expression at the bottom of the loop
instead of the top. Therefore, the statements within the do block are always executed at least once.

public class Do_WhileExample1 {


public static void main(String[] args) {
int i = 0;
do {
System.out.println(“Number is: ” + i);
i = i + 1;
6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 11
OOP class notes Ene – Abr 2023 26/12/22
} while (i < 5); // end do_while
} // end main method
} // end class Do_WhileExample1

Note: i = i + 1 may be replaced by i++

Count carefully.

Make sure that your loop has a chance to finish. Do not forget to increase the variable used in the condition,
otherwise the loop will never end!

When you don't know exactly how many times you want to repeat a block of code, use the do-while loop this way
public class Do_WhileExample2 {
public static void main(String[] args) {
Scanner read = new Scanner( System.in );
int resp = 0; // response
do {
System.out.println(“Print this” );
System.out.println(“Do you want repeat? 1=yes / other number = not” );
resp = read.nextInt();
} while ( resp == 1 ); // end while
read.close();
} // end main method
} // end class Do_WhileExample2

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a
while loop or do-while loop.

The for operator


for ( initialization; condition; update ){

// code block to be executed


statements

} // end for

initialization is executed (only one time) before the execution of the code block.

condition is the condition that is evaluated to execute the code block.

update is executed (every time) after the code block has been executed.

The sequence is: 1. initialization, 2. condition, 3. statements, 4. update; and repeat steps 2, 3 and 4 until
condition is false.

The for operator


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 ForExample {
public static void main(String[] args) {
int i;
for ( i = 0; i < 3; i = i + 1 ) {
System.out.println( “Rule #” + i );
} // end for
} // end class ForExample

Note: i = i + 1 may be replaced by i++

Proposed problems to practice


Make programs that have been asked for homework to repeat using while, do-while, and for loops. To the file and
class names add at the end an underline and the letters wh, dowh and for, depending on the type of loop used.

Previous programs are: GravityCalculator, DosNumsOperaciones1, DosNumsOperaciones2,


DosNumsOperaciones3, SumaTresNums.

DosNumsOperaciones1_MyP, DosNumsOperaciones2_MyP, DosNumsOperaciones3_MyP,


SumaTresNums_MyP, FooCorporation

1. Develop the program that allows to calculate the sum of N different numbers and that shows the result of
the sum. Use loop while in one program and loop do-while in other program.

Clues: with numbers 65, 12, -15, 3, 25, -31, the sum of all is 59 and 6 numbers were added.

2. Develop the program that calculates the sum of the first N integer numbers and shows how many numbers
were added. The program must show the next number to add and the user will decide whether to add it or
not, if the user responds negatively, the program execution will end. Make a version with while loop and
another version with do-while loop.

Clues: with numbers 1, 2, 3, 4, 5, 6, 7, the sum of all them is 28 and 7 numbers were added.

3. Develop the program that allows you to enter N grades from a group of students and add them up to
calculate the average of the group. You should also determine and display on screen how many are
passed and how many are failed. The minimum pass is 70. Use loop for.

Clues: with grades 59, 78, 67, 91, 84, 77, the average is 76, and 4 passed and 2 failed.

4. Program for a grocery store. The program allows us to enter the prices of the items that a customer is
going to buy and shows the total to be paid and the number of items sold. At the end it must display the
total of all payments and the number of custumers of the day. Use loop while or do-while.

Clues: with prices 23.45, 35.80, 10.35, 59.10, the total to pay is 128.70

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


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

Branching Statements
break terminates a loop

public class dowhile_break public class while_break


{ {
public static void main (String [] args) public static void main (String [] args)
{ {
int i = 0; int i = 0;
do { while( i < 10 )
if( i == 5 ) { {
break; } if( i == 5 ) {
break; }
System.out.println(“Num ” + i );
i++; System.out.println(“Num ” + i );
i++;
}while( i < 10 );
} // fin del while
} // fin del main
} // fin de la clase } // fin del main
} // fin de la clase

public class for_break


{
public static void main (String [] args)
{
int i;
for( i = 0; i < 10; i++ )
{
if( i == 5 ) {
break; }

System.out.println(“Num ” + i );

} // fin del while

} // fin del main


} // fin de la clase

Branching Statements
continue skips the current iteration of a loop and proceeds directly to the next iteration

public class dowhile_continue public class while_continue


{ {
public static void main (String [] args) public static void main (String [] args)
{ {
int i = 1; int i = 1;
while( i < 10 )

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


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

do { {
if( i == 5 ) { if( i == 5 ) {
continue; } continue; }

System.out.println(“Num ” + i ); System.out.println(“Num ” + i );
i++; i++;

}while( i < 10 ); } // fin del while

} // fin del main } // fin del main


} // fin de la clase } // fin de la clase

public class for_continue


{
public static void main (String [] args)
{
int i;
for( i = 0; i < 10; i++ )
{
if( i == 5 ) {
continue; }

System.out.println(“Num ” + i );

} // fin del for

} // fin del main


} // fin de la clase

in the programs above change the condition from i == 5 to i % 5 == 0 and the limit from 10 to 100, what will the
programs do?

Now modify the programs so that only multiples of 4 are displayed

Embedded loops or nested loops


for (int i = 0; i < 3; i++) {
for ( int j = 5; j < 7; j++) {
System.out.println ( i + “ ” + j );
}
}

Scope of the variable defined in the initialization: respective for block

Proposed problems to practice


1. Make a java program that counts from 1 to 100 and stops when it reaches a certain value (user defined)
and ends the program. Use break to end the cycle.

2. Make a program for a tire store that allows you to enter an existing value of tires (suppose 250) and that
simulates sales through a count that decreases the number of tires one by one, and that when it reaches a
threshold or defined value (suppose 35), sends a message that the number of tires in stock is very low.
Use break to end the cycle.
6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 15
OOP class notes Ene – Abr 2023 26/12/22

3. Make a program that will display a countdown by one from 50, and numbers that are multiples of 7 will not
show. Use Continue to skip these numbers

4. Program that prints only the prime numbers from 1 to 100. Use Continue to skip numbers

5. Now don't print them. Use Continue to skip these numbers

6. Make a program that generates a random number from 1 to 100 and displays on the screen whether or not
it is even; whether or not it is a multiple of 5; whether or not it is a multiple of 11; whether or not is prime.
See this and this and this.

7. Write a program that displays numbers from 2 to 50. Using random numbers, generate three random
divisors from 2 to 12, and determine how many numbers are divisible (the quotient equals zero) with each
of those three divisors.

8. Select any program, edit it and remove the word “public” from the class and change the name of the class
to let's say “VerQuePasa”. compile. Is there an error because the file name and the class name are
different? what is the name of the .class file?

9. Make a program that displays the multiplication table of any number; example in case it is the one of 2
2* 1 = 2
2* 2 = 4
.
.
2* 10 = 20

8. Make the necessary changes to the above algorithm so that it displays the divide table; example in case it
is the one of 2
2/2=1
4/2=2
6/2=3
.
.
20 / 2 = 10

9. Carry out the desktop test of the following algorithm in Pseint and draw a conclusion in such a way that it
allows you to elaborate the wording of the problem that is solved with this algorithm. Finally, make the
corresponding java program

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


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

10. Carry out the desktop test of the following algorithm in Pseint and draw a conclusion in such a way that it
allows you to elaborate the wording of the problem that is solved with this algorithm. Finally, make the
corresponding java program

11. Write a program that prints the multiplication tables from 1 to 9 in the order shown.

tabla del 8 tabla del 9 tabla del 7


tabla del 5 tabla del 6 tabla del 4
tabla del 2 tabla del 3 tabla del 1

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


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

Arrays
An array is an indexed list of values. You can make an array of any type, may be int, double, String, etc.

All elements of an array must have the same type.

0 1 2 3 ... n-1

...

Example: double [ ]

0 1 2 3 ... n-1

10.2 -2.44 43.56 -25.0 ... 150.8

Arrays
The index starts at zero and ends at length-1.
Example:
int[] values = new int[5];
values[0] = 12; // CORRECT
values[4] = 12; // CORRECT
values[5] = 12; // WRONG!! compiles but
// throws an Exception at run-time

Have a demo with runtime exception

Arrays
An array is defined using TYPE [ ].

Arrays are just another type.


int[ ] values; // array of int elements

int[ ][ ] values; // int[ ] is a type

Arrays
To create an array of a given size, use the operator new :
int[ ] values = new int [5]; //values has 5 elements
or you may use a variable to specify the size:
int size = 12; int[ ] values = new int [size]; //values has 12 elements

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


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

Array Initialization
Curly braces can be used to initialize an array.

It can ONLY be used when you declare the variable.


int[ ] values = { 12, 24, -23, 47 }; //values has 4 elements

Quiz time!
Is there an error in this code?
int[ ] values = {1, 2.5, 3, 3.5, 4};

Accessing Arrays
To access the elements of an array, use the [ ] operator and the index number: values[index]

Example:
int[ ] values = { 12, 24, -23, 47 };
values[3] = 18; // it refers to element 3 which contains to 47 and will be changed by 18
int x = values[1] + 3; // refers to element 1, this is 24, and 3 will be added to it
// and x = 27 but values[1] still is 24

The length variable


Each array has a length variable built-in that contains the length of the array (number of elements)
int[ ] values = new int [12];
int size = values.length; // 12
int[ ] values2 = {1,2,3,4,5}
int size2 = values2.length; // 5

String arrays
A side note
public static void main (String[ ] arguments){
System.out.println(arguments.length);
System.out.println(arguments[0]);
System.out.println(arguments[1]);
}

Combining Loops and Arrays. Looping through an array


Example 1:
int[ ] values = new int[5];

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


OOP class notes Ene – Abr 2023 26/12/22
for (int i=0; i<values.length; i++) {
values[i] = i;
int y = values[i] * values[i];
System.out.println(y);
}

Looping through an array


Example 2:
int[ ] values = new int[5];
int i = 0;
while (i < values.length) {
values[i] = i;
int y = values[i] * values[i];
System.out.println(y);
i++;
}

We can fill an array with data of one value as a way to initialize it

a) int[ ] values1 = {-1, -1, -1, -1, -1, -1, -1};

b) int[ ] values2 = new int[7];


for (int i=0; i<values.length; i++) {
values[i] = -1;
}

c) import java.util.Arrays; 1

public class fillArray {


public static void main(String[] args){
int[ ] values3 = new int[7];
Arrays.fill(values3, -1);
System.out.println("Array filled with -1 \n" + Arrays.toString(values3));
}
}

1 import java.util.Scanner;
2
3 public class Ejemplo1Arreglos { //begin class
4 public static void main (String[]args) { //begin main
5 int i; // counter on each for loop
6
7 int [] valores1 = new int [5]; //array of size 5
8 valores1 [0] = 10;
9 valores1 [4] = 40;
10 valores1 [5] = 25; /*error! an array of length 5 its last element is 4,
11 so we can modify size to 6 (in line 7) or change the index to 1, 2, or 3 (in line 10) */
12

1 Taken for academic purposes of https://barcelonageeks.com/arrays-fill-en-java-con-ejemplos/


6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 20
OOP class notes Ene – Abr 2023 26/12/22
13 for( i = 0; i < valores1.length; i++) {
14 System.out.println (" Valor del elemento " + i + " es: " + valores1 [i]);
15 }//end for loop
16
17
18 int[] numeros = { 5, 10, 15, 20, 25, 30, 35};
19 for( i = 0; i < numeros.length-2; i++){
20 /* the two last elements it doesn't shows because -2 in condition. We can
21 make them display by removing -2 in condition */
22 System.out.println ("Valor del elemento " + i + " es: " + numeros [i]);
23 }//end for loop
24
25 System.out.println ("De cuantos elementos quieres el arreglo? Mínimo 5");
26 Scanner leer = new Scanner (System.in);
27 int size = leer.nextInt();
28 int [] values = new int [size];
29 values[0] = 100;
30 values [size - 2] = 400;
31 values [size - 1] = 500;
32 values [size] = 300; // last element is either lenght - 1 or size - 1, so index = size
33 values [size + 1] = 200; // doesn't exist, nor does exist index = size + 1
34 // we can modify the index in line 32 and 33 to size - 3 and size – 4 respectively
35 for ( i = 0; i < values.length; i++) {
36 System.out.println ("Valor del elemento " + i + " es: " + values[i]);
37 }//end for loop
38 leer.close();
39 }//end main method
40 }//end class

If you want more details, see https://www.w3schools.com/java/java_arrays.asp

and https://www.w3schools.com/java/java_arraylist.asp its a very interesting theme.

Proposed problems to practice


1. Write a program that allows you to input N integer numeric values to a one-dimensional array and display
them in the reverse order in which they were input (Top last entered and bottom first entered. This is a
stack).

2. Program that inserts random values from 0 to 99 into an array of size N, to then display the numbers on
the screen. See https://www.w3schools.com/java/java_math.asp

3. Program that inserts random values from 20 to 70 into an array of size N, to then display the numbers on
the screen. See https://carloszr.com/como-generar-numero-aleatorio-en-rango-de-valores-en-java/

4. Create a program that allows you to input integer numeric values to a one-dimensional array and average
them (it will serve as the basis for the variance and standard deviation).

5. Write a program that inserts random values from 0 to 99 into an array of size N, sort them lower to higher,
finally display values sorted. Use bubble sort. See
https://www.wikiwand.com/es/Ordenamiento_de_burbuja

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


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

6. Use arrays. There are the final grades of a school group, one grade per student; make a program that
calculates the group average and says how many grades are higher than the average and how many are
lower than the average.

7. Program that uses two arrays, in the first N grades from 0 to 100 are introduced, in the second the points
that each grade represents are stored (pts = grade *.35). At the end, it shows each grade and the points
obtained.

8. Write a program that allows you to input random integer values from 0 to 99 to two one-dimensional arrays
and add the values that are in the same positions in both arrays and store the sum in a third array and
display the values of all three arrangements.

9. Develop a program that allows you to calculate the variance and the sample standard deviation of a
i=n

∑ (x i− ̄x )2
2 i =1
population of a set of numbers; the variance formula is s= where ̄x is the arithmetic
n−1
mean or average of the set of numbers. Review procedure here.
Here you have to divide the entire process into parts. 1st. The mean or average will be calculated. 2nd.
Each of the subtractions of each data will be made with the average, and they are saved. 3rd. The square
of each subtraction is calculated and the results are saved. In that same step you can perform the sum of
all squares. 4th. Finally, the variance is calculated and then the standard deviation.

10. Program that in an mxn matrix, where m=n and 2 <= m <= 5, inserts random values from 10 to 99, to then
display the numbers on the screen in matrix form. Validate that the value of m complies with the restriction
of 2 <= m <= 5.
Matrix 3x3 Matrix 4x4 Matrix 5x5
00 01 02 00 01 02 03 00 01 02 03 04
10 11 12 10 11 12 13 10 11 12 13 14
20 21 22 20 21 22 23 20 21 22 23 24
30 31 32 33 30 31 32 33 34
40 41 42 43 44

The value of m will represent the maximum number of rows and since m=n, the matrix will have n
columns, making the number of rows and columns equal, and therefore, it is square; on the other hand, we
do the traversal of each of the positions of a matrix with the index i for the rows and j for the columns.
we will use the variable lim_i to identify the maximum number of rows (m) and the variable lim_j to identify
the maximum number of columns (n).

11. Write the program that allows you to input random values from 100 to 399 to a matrix of mxn, where m=n
and 3 <= m <= 9. Identify which numbers occupy each corner of the matrix. Validate that the value of m
complies with the restriction of 3 <= m <= 9.

12. Write the program that allows you to input random values from 0 to 99 to a matrix of mxn, where where
m=n and 3 <= m <= 9. Calculate the sum of the numbers that lie on the periphery of the matrix. Validate
that the value of m complies with the restriction of 3 <= m <= 9.

13. Write the program that allows you to input random values from 0 to 99 to a matrix of mxn, where m=n and
3 <= m <= 9 and that adds the numbers that are a) on the main diagonal and then b ) those of the minor
diagonal and showing each result
6.092 Introduction to Programming in Java: adapted by Valentin Belisario Dominguez Vera 22
OOP class notes Ene – Abr 2023 26/12/22

Assignment 3
A group of friends participate in the Boston Marathon.

Find the best performer.

Find the second-best performer.

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 23

You might also like