An Introduction to Programming in Java: Arrays. Last delivered in 2012. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Array
Introduction
One-dimensional array
Multidimensional array
Advantage of Array
Write a C program using arrays that produces the multiplication of two matrices.
Array
Introduction
One-dimensional array
Multidimensional array
Advantage of Array
Write a C program using arrays that produces the multiplication of two matrices.
2D array in C++ language ,define the concept of c++ Two-Dimensional array .with example .and also Accessing Array Components concept.and Processing Two-Dimensional Arrays.
Collections Framework is a unified architecture for managing collections, Main Parts of Collections Framework
1. Interfaces :- Core interfaces defining common functionality exhibited by collections
2. Implementations :- Concrete classes of the core interfaces providing data structures
3. Operations :- Methods that perform various operations on collections
Programming in Java: Arrays. Last delivered in 2016. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Java abstract class & abstract methods,Abstract class in java
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
2D array in C++ language ,define the concept of c++ Two-Dimensional array .with example .and also Accessing Array Components concept.and Processing Two-Dimensional Arrays.
Collections Framework is a unified architecture for managing collections, Main Parts of Collections Framework
1. Interfaces :- Core interfaces defining common functionality exhibited by collections
2. Implementations :- Concrete classes of the core interfaces providing data structures
3. Operations :- Methods that perform various operations on collections
Programming in Java: Arrays. Last delivered in 2016. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Java abstract class & abstract methods,Abstract class in java
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
Getting StartedCreate a class called Lab8. Use the same setup for .pdfinfo309708
Getting Started
Create a class called Lab8. Use the same setup for setting up your class and main method as you
did for the previous assignments. Be sure to name your file Lab8.java. Additionally, make
another file called Arrays.java. This file will be an object, so simply start it off by declaring an
Arrays class. You can copy the following skeleton and fill in the appropriate code below each of
the comments:
public class Arrays {
/ Instance Variables
// Constructors
// findMin 1
// findMax
// calcSum
// calcAverage
// toString
}
Task Overview
Your task for this lab is to create a class called Arrays with some array processing methods. This
class will maintain an array and the number of elements present in it. Additionally, methods will
be available to display the current min and max elements along with the average of all of them.
Finally, a toString() method will be available to cleanly display all the array elements. Finally,
you will write a simple driver class to test out the above Arrays class.
Part 1: Instance Variables for Arrays
The first thing to do for the Arrays class is to set up its instance variables. Declare the following
(private) instance variables:
• An int array called array ? this will be the array we will be writing methods for.
• An int called count - this represents the number of valid elements in the array.
Part 2:
Constructors for Arrays The Arrays class will have two constructors. The first constructor takes
the maximum size of the array as input as a parameter and initializes the array instance variable
appropriately. It also sets count to size. Finally, it will initialize all of the array elements to some
values between 0 and 10, inclusive. To create this constructor, follow these steps:
• Import java.util.Random to make use of the random number generator.
• Create a constructor with the following header: public Arrays(int size)
• Initialize your array variable and set its size to size (see the chart on page 252 for reference on
initializing arrays). Be very careful that you are setting the value of your array instance variable,
as opposed to creating a new variable called array.
• Set the value of the count variable to size because we will be populating the entire array.
• Copy the following code to the constructor in order to generate random values between 0 and
10, inclusive:
Random rand = new Random();
for (int i = 0; i < count; i++)
{
array[i] = (rand.nextInt(10));
}
Next, create another constructor with the following header: public Arrays(int[] arr). This
constructor will initialize the class by using the passed arr argument in order to fill its instance
variables. The following things need to be done inside of this constructor:
• Set the array variable equal to arr.
• Set the count variable equal to the length of the array.
Part 3: Displaying the Output findMin()
The first method of this class will search the array for the minimum element. Copy the following
code for the findMin method. Note how the count i.
I need help with this program for java.The program you are given t.pdffonecomp
I need help with this program for java.
The program you are given to start with: Lab4.java
The input file of ints:10,000ints.txt
The input file of words:172,822words.txt
Execute your program like this: C:\\> java Lab4 10000ints.txt 172822words.txt
Be sure to put the ints filename before the words filename. The starter file will be expecting them
in that order.
Lab#4\'s main method is completely written. Do not modify main. Just fill in the methods. Main
will load a large arrays of int, and then load a large array of Strings. As usual the read loops for
each file will be calling a resize method as needed. Once the arrays are loaded, each array will be
tested for the presence of duplicates via calls to indexOfFirstDuplicate(). Do not do any trim
operation.
Here are the rules:
In your methods that look for the first occurrence of a duplicate in each array, you must sort the
arrays before looking for the dupe. Do not search the array for the dupe until it is sorted. We
require this because an unsorted array would require a quadratic algorithm (N squared via nested
loops). If you sort you array first you will only incur an O(n*Log2n) cost for the sort with an
additional O(n) for the search. This is the best that can be done without using a technology such
as hashing which you will use for your next lab.
Inside your method to find the dupe you must sort the array first.
Do not define/use any new type or data structure that we have not covered yet.
Your traversal of the array looking for the dupe should require no more than one pass.
Be as efficient as you can without breaking rule #2.
Assuming the array below, the 1st occurrence of a duplicate is at index 4, not 3, since the
element at [4] is the first index position where that value was seen for a second time. Be sure you
understand this. Do not report the index of the first occurrence of a value as being the index
where the duplicate occurred.
Your job will be to fill in the definitions of these methods below main
static int[] upSizeArr( int[] fullArray ); // incoming array is FULL. It needs it\'s capacity doubled
static String[] upSizeArr( String[] fullArray ); // incoming array is FULL. It needs it\'s capacity
doubled
static int indexOfFirstDupe( int[] arr, int count ); // returns ind of 1st occurrence of duplicate
value
static int indexOfFirstDupe( String[] arr, int count ); // returns ind of 1st occurrence of duplicate
value
Here is the starting file!
Solution
HI, Please find my implementation of all required methods.
Please let me know in case of any issue.
/* Lab4.java Reads two files into two arrays then checks both arrays for dupes */
import java.io.*;
import java.util.*;
public class Lab4
{
static final int INITIAL_CAPACITY = 10;
static final int NOT_FOUND = -1; // indexOfFirstDupe returns this value if no dupes found
public static void main (String[] args) throws Exception
{
// ALWAYS TEST FIRST TO VERIFY USER PUT REQUIRED INPUT FILE NAME ON
THE COMMAND LINE
if (args.length < 1 )
{
Syst.
Principles of Health Informatics: Artificial intelligence and machine learningMartin Chapman
Principles of Health Informatics: Artificial intelligence and machine learning. Last delivered in 2024. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Clinical decision support systemsMartin Chapman
Principles of Health Informatics: Clinical decision support systems. Last delivered in 2024. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Evaluating medical softwareMartin Chapman
Principles of Health Informatics: Evaluating medical software. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Usability of medical softwareMartin Chapman
Principles of Health Informatics: Usability of medical software. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Social networks, telehealth, and mobile healthMartin Chapman
Principles of Health Informatics: Social networks, telehealth, and mobile health. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Communication systems in healthcareMartin Chapman
Principles of Health Informatics: Communication systems in healthcare. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Terminologies and classification systemsMartin Chapman
Principles of Health Informatics: Terminologies and classification systems. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Representing medical knowledgeMartin Chapman
Principles of Health Informatics: Representing medical knowledge. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Informatics skills - searching and making d...Martin Chapman
Principles of Health Informatics: Informatics skills - searching and making decisions. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Informatics skills - communicating, structu...Martin Chapman
Principles of Health Informatics: Informatics skills - communicating, structuring, and questioning. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Principles of Health Informatics: Models, information, and information systemsMartin Chapman
Principles of Health Informatics: Models, information, and information systems. Last delivered in 2023. All educational material listed or linked to on these pages in relation to King's College London may be provided for reference only, and therefore does not necessarily reflect the current course content.
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdfTechSoup
In this webinar you will learn how your organization can access TechSoup's wide variety of product discount and donation programs. From hardware to software, we'll give you a tour of the tools available to help your nonprofit with productivity, collaboration, financial management, donor tracking, security, and more.
Ethnobotany and Ethnopharmacology:
Ethnobotany in herbal drug evaluation,
Impact of Ethnobotany in traditional medicine,
New development in herbals,
Bio-prospecting tools for drug discovery,
Role of Ethnopharmacology in drug evaluation,
Reverse Pharmacology.
How to Create Map Views in the Odoo 17 ERPCeline George
The map views are useful for providing a geographical representation of data. They allow users to visualize and analyze the data in a more intuitive manner.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
How to Split Bills in the Odoo 17 POS ModuleCeline George
Bills have a main role in point of sale procedure. It will help to track sales, handling payments and giving receipts to customers. Bill splitting also has an important role in POS. For example, If some friends come together for dinner and if they want to divide the bill then it is possible by POS bill splitting. This slide will show how to split bills in odoo 17 POS.
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
Students, digital devices and success - Andreas Schleicher - 27 May 2024..pptxEduSkills OECD
Andreas Schleicher presents at the OECD webinar ‘Digital devices in schools: detrimental distraction or secret to success?’ on 27 May 2024. The presentation was based on findings from PISA 2022 results and the webinar helped launch the PISA in Focus ‘Managing screen time: How to protect and equip students against distraction’ https://www.oecd-ilibrary.org/education/managing-screen-time_7c225af4-en and the OECD Education Policy Perspective ‘Students, digital devices and success’ can be found here - https://oe.cd/il/5yV
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
2. Contents
Arrays
The Enhanced for Loop
Common Array Algorithms
Using Arrays with Methods
Two-Dimensional Arrays
Array Lists
3. Chapter Goals
To become familiar with using arrays and
array lists to collect values
To use the enhanced for loop for traversing
arrays and array lists
To learn about common algorithms for
processing arrays and array lists
To learn how to use two-dimensional arrays
In this chapter, you will learn about
arrays, array lists, and common
algorithms for processing them.
5. Sequences of Values
‣ A Computer Program often needs to
store a list of values and then process
them.
‣ For example, to find the highest.
‣ Say you had this list of values, how
many variables would you need?
‣ double input1, input2, input3….
‣ Impractical for manipulation;
unnecessary code replication.
7. An Example
if ( Carlsberg.alcoholPercentage is >= 5 )
then
My head hurts
otherwise
In for work at 9am
end
if ( Guinness.alcoholPercentage is >= 5 )
then
My head hurts
otherwise
In for work at 9am
end
if ( Budweiser.alcoholPercentage is >= 5 )
then
...
Only a ‘pseudocode’ example
beer Carlsberg, Guinness, Budweiser
8. Arrays
‣ Are the answer!
An array collects sequences of values of the
same type.
10. Declaring an Array
Declaring an array is a two step process.
1) double[] data; // declare array variable
2) data = new double[10]; // initialise size
You cannot use the array
until you tell the compiler
the size of the array in
step 2.
11. Declaring an Array (Step 1)
Make a named ‘list’ with the following parts:
Type Square Braces Array name semicolon
double
[ ] data ;
You are declaring that
• There is an array named data
• The elements inside are of type double
• You have not (YET) declared how many elements
are in inside
Other Rules:
Arrays can be declared anywhere you can declare a
variable
Do not use ‘reserved’ words or already used names
12. Declaring an Array (Step 2)
data
[0] [1] [2] [3] [4] … [9]
double double double double double double
Reserve memory for all of the elements:
Array name Keyword Type Size semicolon
data = new double [10] ;
You are reserving memory for:
• The array named data
• Needs storage for [10]
• Elements the size of type double
You are also setting up the array variable
Now the compiler knows how many elements there are
13. Common Error 1
double[] data;
...
data[0] = 29.95; // Error—data not initialised
Uninitialised Arrays
Don’t forget to allocate the array contents!
The compiler will catch this error data
0
1
2
3
4
5
6
7
8
9
double[] data;
data = new double[10];
data[0] = 29.95; // No error
Error: D:JavaUnitialised.java:7:
variable data might not have been initialized
14. One Step Array Declaration
Declare and Create at the same time:
Type Braces Array name Keyword Type Size semi
double [] data = new double [10] ;
You are declaring that
• There is an array named data
• The elements inside are of type double
You are reserving memory for the array
• Needs storage for [10]
• Elements the size of type double
You are also setting up the array variable
15. Declaring and Initialising an Array
You can declare and set the initial contents of all
elements by:
Type Braces Array name contents list semi
int
[ ] primes = { 2, 3, 5, 7} ;
You are declaring that
There is an array named primes
The elements inside are of type int
Reserve space for four elements
• No need for ‘new’ keyword, the compiler counts
them for you.
Set initial values to 2, 3, 5, and 7
Note the curly braces around the contents list
17. Accessing Array Elements
Each element is numbered
We call this the ‘index’
Access an element by:
• Name of the array
• Index number
data[i]
public static void main(String[] args)
{
double data[];
data = new double[10];
data[4] = 35;
System.out.println(data[4]);
}
Elements in the array data are
accessed by an integer index i,
using the notation data[i].
18. The last element is at index 9:
Array Index Numbers
Array index numbers start at 0
The rest are positive integers
A 10 element array has indexes 0 through 9
There is NO element 10!
public static void main(String[] args)
{
double data[];
data = new double[10];
}
The first element is at index 0:
19. Problem: Common Error 2
Array Bounds Errors
Accessing a nonexistent element is very common error
Array indexing starts at 0
Your program will stop at run time
public class OutOfBounds
{
public static void main(String[] args)
{
double data[];
data = new double[10];
data[10] = 100;
}
}
java.lang.ArrayIndexOutOfBoundsException: 10
at OutOfBounds.main(OutOfBounds.java:7)
The is no element 10:
20. Solution: Array Bounds Checking
An array knows how many elements it can hold
data.length is the size of the array named data
It is an integer value (index of the last element + 1)
Use this to range check and prevent bounds errors
public static void main(String[] args)
{
int i = 10, value = 34;
double data[];
data = new double[10];
if (0 <= i && i < data.length) // value is 10
{
data[i] = value;
}
}
21. Visiting Array Elements
An array knows how many elements it can hold
data.length is the size of the array named data
It is an integer value (index of the last element + 1)
Similarly, use this to visit all the elements in an array.
public static void main(String[] args)
{
int[ ] data = { 1 , 2 , 3 , 4 , 5 };
for ( int i = 0; i < data.length; i++ )
{
System.out.println( data[ i ] );
}
}
22. The benefits of using an array:
Back to Beer...
beer array = { Carlsberg, Guinness, Budweiser }
Set variable i = 0;
Loop until i == length of beer array
if element at i alcoholContent is > 5
then
My head hurts
otherwise
In for work at 9am
end
increase i by 1.
Next Loop.
A significant decrease in code.
30. Partially-Filled Arrays
An array cannot change size at run time
The programmer may need to guess at the maximum
number of elements required
It is a good idea to use a constant for the size chosen
A partial solution?
Use a variable to track how many elements are filled
31. Partially-Filled Arrays
final int LENGTH = 100;
double[] data = new double[LENGTH];
int currentSize = 0;
Scanner in = new Scanner(System.in);
while (in.hasNextDouble())
{
if (currentSize < data.length)
{
data[currentSize] = in.nextDouble();
currentSize++;
}
}
Use the .length value
and currentSize
variable to prevent
over-filling the array
32. ‘Walking’ a Partially Filled Array
for (int i = 0; i < currentSize; i++)
{
System.out.println(data[i]);
}
A for loop is a natural choice
to walk through an array
‣ Use currentSize, not data.length for the last element
33. Using for loops to ‘walk’ arrays is very common
The enhanced for loop simplifies the process
Also called the “for each” loop
Read this code as:
• “For each element in data”
double[] data = . . .;
double sum = 0;
for (double element : data)
{
sum = sum + element;
}
A shortcut: The Enhanced for Loop
34. As the loop proceeds, it will:
Access each element in order (0 to length -1)
Copy it to the element variable
Execute loop body
Not possible to:
Change elements
Get bounds error
double[] data = . . .;
double sum = 0;
for (double element : data)
{
sum = sum + element;
}
A shortcut: The Enhanced for Loop
35. Syntax: The “for each” loop
Use the “for each” loop when:
You need to access every element in the array
You do not need to change any elements of the array
36. Common Array Algorithms
Practical array implementations:
Filling an Array
Sum and Average Values
Maximum and Minimum
Output Elements with Separators
Linear Search
Removing an Element
Inserting an Element
Copying Arrays
Reading Input
37. Common Algorithms 1:
1) Filling an Array
Initialise an array to a set of calculated values
Example: Fill an array with squares of 0 through 10
int[] squares = new int[11];
for (int i = 0; i < squares.length; i++)
{
squares[i] = i * i;
}
38. Common Algorithms 2:
2) Sum and Average
Use ‘for each’ loop, and make sure not to divide by zero
double total = 0, average = 0;
for (double element : data)
{
total = total + element;
}
if (data.length > 0) { average = total / data.length; }
39. Common Algorithms 3:
double largest = data[0];
for (int i = 1; i < data.length; i++)
{
if (data[i] > largest)
{
largest = data[i];
}
}
double largest = data[0];
for (double element : data)
{
if (element > largest)
largest = element;
}
Maximum and Minimum
Set largest to first element
Use for or a ‘for each’ loop
Use the same logic for minimum
double smallest = data[0];
for (double element : data)
{
if (element < smallest)
smallest = element;
}
Typical for loop to find maximum
‘for each’ to find maximum ‘for each’ to find minimum
40. Element Separators
Output all elements with separators between them
No separator before the first or after the last element
Handy Array method: Arrays.toString()
Useful for debugging!
Common Algorithms 4:
for (int i = 0; i < data.length; i++)
{
if (i > 0)
{
System.out.print(" | ");
}
System.out.print(data[i]);
}
import java.util.*;
System.out.println(Arrays.toString(data));
41. Common Algorithms 5:
Linear Search
Search for a specific value in an array
Start from the beginning (left), stop if/when it is found
Uses a boolean ‘found’ flag to stop loop if found
int searchedValue = 100;
int pos = 0;
boolean found = false;
while (pos < data.length && !found)
{
if (data[pos] == searchedValue) {
found = true; }
else {
pos++; }
if (found) {
System.out.println(“Found at position: ” + pos); }
else {
System.out.println(“Not found”); }
}
Compound condition to prevent
bounds error if value not found.
42. Common Algorithms 6:
Removing an element (at a given position)
Requires tracking the ‘current size’ (# of valid elements)
But don’t leave a ‘hole’ in the array!
Solution depends on if you have to maintain ‘order’
• If not, find the last valid element, copy over position, update size
data[pos] = data[currentSize – 1];
currentSize--;
43. Common Algorithms 6:
Removing an element (at a given position)
Requires tracking the ‘current size’ (# of valid elements)
But don’t leave a ‘hole’ in the array!
Solution depends on if you have to maintain ‘order’
• If so, move all of the valid elements after ‘pos’ up one spot,
update size
for (int i = pos; i < currentSize - 1; i++)
{
data[i] = data[i + 1];
}
currentSize--;
44. Common Algorithms 7:
Inserting an Element
Solution depends on if you have to maintain ‘order’
• If so, find the right spot for the new element, move all of the
valid elements after ‘pos’ down one spot, insert the new
element, and update size
• If not, just add it to the end and update the size
if (currentSize < data.length)
{
for (int i = currentSize; i > pos; i--)
{
data[i] = data[i - 1];
}
data[pos] = newElement;
currentSize++;
}
45. Note: Array References
Make sure you see the difference between the:
Array variable: The named ‘handle’ to the array
Array contents: Memory where the values are stored
int[] scores = { 10, 9, 7, 4, 5 };
An array variable contains a reference to the
array contents. The reference is the location
of the array contents (in memory).
Array variable Array contents
Reference
Values
46. Note: Array Aliases
You can make one array reference refer to the
same contents of another:
int[] scores = { 10, 9, 7, 4, 5 };
Int[] values = scores; // Copying the array reference
An array variable specifies the location of
an array. Copying the reference yields a
second reference to the same array.
Array contents
References
47. Common Algorithms 8:
Copying Arrays
Not the same as copying only the reference
• Only have one actual set of contents!
48. Common Algorithms 8:
double[] data = new double[6];
. . . // Fill array
double[] prices = data; // Only a reference so far
double[] prices = Arrays.copyOf(data, data.length);
// copyOf creates the new copy, returns a reference
Want to copy the contents of one array to another
Use the Arrays.copyOf method
49. Common Algorithms 8:
Growing an array
Copy the contents of one array to a larger one
Change the reference of the original to the larger one
Example: Double the size of an existing array
Use the Arrays.copyOf method
Use ‘2 *’ in the second parameter
double[] values = new double[6];
. . . // Fill array
double[] newValues = Arrays.copyOf(values, 2 * values.length);
values = newValues;
Arrays.copyOf second parameter is
the length of the new array
50. Increasing the Size of an Array - Step 1
Copy all elements of values to newValues
double[] newValues = Arrays.copyOf(values, 2 * values.length);
51. Increasing the Size of an Array - Step 2
Then copy newValues reference over values
reference
values = newValues;
52. Common Algorithms 9:
Reading Input
Solution depends on if know how many values to expect
• If so, make an array of that size and fill it one-by-one
•
double[] inputs = new double[NUMBER_OF_INPUTS];
for (i = 0; i < inputs.length; i++)
{
inputs[i] = in.nextDouble();
}
53. Common Algorithms 9:
Reading Input
Solution depends on if know how many values to expect
• If so, make an array of that size and fill it one-by-one
• If not, make an array large enough for the maximum, and add
values to the end until no more are available.
double[] inputs = new double[NUMBER_OF_INPUTS];
for (i = 0; i < inputs.length; i++)
{
inputs[i] = in.nextDouble();
}
double[] inputs = new double[MAX_INPUTS];
int currentSize = 0;
while (in.hasNextDouble() && currentSize < inputs.length)
{
inputs[currentSize] = in.nextDouble();
currentSize++;
}
54. Common Algorithms 9:
double[] inputs = new double[INITIAL_SIZE];
int currentSize = 0;
while (in.hasNextDouble())
{
if (currentSize >= inputs.length)
{
inputs = Arrays.copyOf(inputs, 2 * inputs.length);
}
inputs[currentSize] = in.nextDouble();
currentSize++;
}
Reading Input
A better solution: double the array when it is full.
Able to handle input of arbitrary length
57. Common Error 3
Underestimating the Size of the Data Set
The programmer cannot know how someone might want
to use a program!
Make sure that you write code that will politely reject
excess input if you used fixed size limits
Sorry, the number of lines of text is
higher than expected, and some could not be
processed. Please break your input into
smaller size segments (1000 lines maximum)
and run the program again.