Transcript Looping
Simple Arrays
Arrays of primitives and Strings
Sections 7.1, 7.2
Problem
Write a program to read six integers...
...& print them out in reverse order
For example:
Enter the six numbers below:
5 3 7 2 99 41
In reverse order they are:
41, 99, 2, 7, 3, and 5
Can’t use a single-variable loop
need to remember all 6 numbers
Reverse6.java
Solution
int n1, n2, n3, n4, n5, n6;
S.o.p(“Enter the six numbers
n1 = kbd.nextInt();
n2 = kbd.nextInt();
n3 = kbd.nextInt();
n4 = kbd.nextInt();
n5 = kbd.nextInt();
n6 = kbd.nextInt();
kbd.nextLine();
S.o.p(“In reverse order they
+ n6 + “, ” + n5 + “, ” +
+ n3 + “, ” + n2 + “, and
below:\n”);
are:\n”
n4 + “, ”
” + n1);
Related Problem
Write a program to read six HUNDRED
integers & print them out in reverse order
Need 600 ints: declare, input, & output
Individually named:
Reverse600HardWay.java
int n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12, n13,
n14, n15, n16, n17, n18, n19, n20, n21, n22, n23, n24,
n25, n26, n27, n28, n29, n30, n31, n32, n33, n34, n35,
n36, n37, n38, n39, n40, n41, n42, n43, n44, n45, n46,
n47, n48, n49, n50, n51, n52, n53, n54, n55, n56, n57,
n58, n59, n60, n61, n62, n63, n64, n65, n66, n67, n68,
n69, n70, n71, n72, n73, n74, n75, n76, n77, n78, n79,
A Better Way: Arrays
int[] n = new int[600]; // creates 600 ints
n is called an array (of ints)
n has 600 components or elements
Their names are:
each one is an int variable
n[0], n[1], n[2], n[3], n[4], ... , n[599]
Number in [brackets] is called the index
Multiple Variables vs. Array
int n0, n1, n2, n3, n4, n5, n6, n7, n8, n9;
int[] n = new int[10];
n0
n
n[0]
n[1]
n[2]
n[3]
n[4]
n[5]
n[6]
n[7]
n[8]
n[9]
n1
n2
n3
n4
n5
n6
n7
n8
n9
Thinking of Array Elements
n[0], n[1], n[2], ... are just better ways to
write n0, n1, n2, ...
Why?
because you can say n[i] for the ith n…
…and then you can put it in a loop
for (int i = 0; i < 600; i++) { Remember this!
… n[i] …
You’ll see it a LOT!
}
Using Arrays
Reading and printing those 600 ints?
n[0] = kbd.nextInt();
n[1] = kbd.nextInt();
n[2] = ...
System.out.print(n[599] + ‘ ’ + n[598] + ‘ ’ …);
No—use loops
for (int i = 0; i < 600; i++)
n[i] = kbd.nextInt();
for (int i = 599; i >= 0; i--)
System.out.print(n[i] + ‘ ’);
Reverse600EasyWay.java
Notes on Array Indices
We declare int[] n = new int[10]; but there is no
element called n[10]
elements go from 0 to 9
any other number is out of bounds
» crash with ArrayIndexOutOfBoundsException
» crash message says what the wrong index was
Low numbers are at front or top of the array
High numbers are at back or bottom
Notes on Array Indices
Index will usually be a simple variable
the loop control variable:
for (int i = 0; i < MAX; i++) {
... num[i] ...
}
Index can be any int-valued expression
... num[i + 1] ...
... num[i – 1] ...
... num[10*r + c] ...
in an i loop
in an i loop
in nested r & c loops
See, for example, StudentNames.java
Array Base Types
Arrays can be of any base type, any size
int[] score = new int[600];
double[] weight = new double[70];
boolean[] answers = new boolean[10];
String[] words = new String[5000];
…any type at all
Scanner[] scanners = new Scanner[2];
Student[] myStudents = new Student[10];
The text recommends singular names.
I tend to use plural.
Array Sizes
Remember to declare constants for numbers
you use in multiple places
like in array declaration and loop!
int[] nums = new int[NUM_ITEMS];
for (int i = 0; i < NUM_ITEMS; i++)
nums[i] = kbd.nextInt();
Makes it easy to change the number later
// # elements – change to 600 when debugged!
public static final int NUM_ITEMS = 6;
Arrays Know Their Own Length
Instance variable length
public static final int MAX_WORDS = 200;
…
String[] word = new String[MAX_WORDS];
if (word.length != MAX_WORDS) {
System.err.println(“Your computer is broken!”);
}
NOTE: it’s not a method; it’s a public instance variable
Creating Arrays with Values
Create an array object by listing elements
int[] arr = new int[]{2, 3, 5, 7, 11};
It knows its own length!
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + “ ”);
}
2 3 5 7 11
Can change the array later
arr = new int[]{13, 17, 19, 23};
Initialize.java
What Do We Use Arrays For?
Lists, mostly
when we need to remember the earlier values
after we’ve read the later ones
» otherwise we can just use one variable in a loop
Example:
read a list of numbers, calculate its average,
then say how different each number is from the
average
Average and Differences
// read and sum the numbers
int[] num = new int[NUM_ITEMS];
int sum = 0;
S.o.p(“Enter the ” + NUM_ITEMS + “ items below”);
for (int i = 0; i < NUM_ITEMS; i++) {
num[i] = kbd.nextInt();
// remember the #
sum += num[i];
// add it to sum
}
// calculate the average
double ave = (double)sum / (double)NUM_ITEMS;
// print the difference from the average of each
for (int i = 0; i < NUM_ITEMS; i++) {
S.o.p((num[i] – ave));
}
WeeklyTemps.java
Exercise
Declare this array of Strings:
word
“to”
“be”
“or”
“not”
“to”
“be”
print it out on one line (with spaces between)
DON’T COUNT THE WORDS!
Java Arrays Created at Run Time
Can ask the user how big to make an array
» can’t do that in C++
System.out.print(“How many students? ”);
int numStu = kbd.nextInt();
kbd.nextLine();
String[] name = new String[numStu];
System.out.println(“What are their names?”);
for (int s = 0; s < numStu; s++) {
name[s] = kbd.nextLine();
}
StudentNames.java
Array Lengths are Final
Can’t change the size of an array after you
create it(*)
int[] n = new int[10];
System.err.println(“Oops! Need it bigger!”);
n.length = 20;
// illegal
(*) But you can change the variable to point
to a new (larger) array!
int[] n = new int[10];
System.err.println(“Oops! Need it bigger!”);
n = new int[20];
// OK!
Bigger.java
But What About…
New, larger array is all zeroes!
If you want to keep the old values, you need
to copy them into the new array
int[] num = new int[]{1,2,3,4,5};
int[] bigger = new int[2 * num.length];
for (int i = 0; i < num.length; i++) {
bigger[i] = num[i];
}
num = bigger; bigger
num
1 2 3 4 5
01 02 03 04 05 0 0 0 0 0
BetterBigger.java
Command Line Arguments
Remember how we declare main?
public static void main(String[] args)
never really explained String[] args
it’s an array of Strings...
...passed into your program...
...from the “command line”
prompt] java PrintArgs command line arguments
My 3 command line arguments were:
0: “command”
1: “line”
2: “arguments”
Command Line Arguments
Add words after the name of the class
prompt] java PrintArgs command line
My 2 command line arguments were:
0: “command”
1: “line”
They get passed to the program
» (unless they start with < or >, or ...)
Appear in the String[] parameter of main
each word is a separate array element
NetBeans & the Command Line
File > Project Properties…
or right-click on project name in Projects pane
Command Line Arguments
You can use args like any other array
ask it its length
loop thru its elements
ask for some element
System.out.println(“My ” + args.length + “ arguments:”);
for (int i = 0; i < args.length; i++) {
System.out.println(i + “:\t\"” + args[i] + “\"”);
args }
My 2 arguments:
“command”
0: "command"
“line”
1: "line"
args is a String[]
OK to have a String[]
can have an array of anything (pretty much)
Even if you type in numbers!
prompt] java PrintArgs 5 10
My 2 command line arguments were:
0: “5”
1: “10”
» you can use Integer.parseInt(args[i]) to get the
integer value of args[i]
see AddArgs.java
Arrays as Parameters
args is a String[] parameter for main
Other methods can have [] parameters, too
just declare the parameter to be an array!
public static int sumArray(int[] arr)
It’s just like any other parameter
gets its value from the method call
It’s just like any other array
it knows how long it is
Method to Sum an Array
Array comes from caller
int[] n = new int[]{2, 3, 5, 7, 11};
int addedUp = sumArray(n);
Method adds up its elements
public static int sumArray(int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
ArrayMethod.java
Exercise
Write a method that receives an array of
words and prints them out one per line.
Write a method that receives an array of
doubles and returns the largest value in it
Returning Arrays
Methods can return arrays
return type is an array type
public int[] dice(int howMany) { … }
public String[] wordsFrom(String line) { … }
Like any other object-returning method, the
object/array to be returned is new
int[] result = new int[howMany];
…
return result;
ArrayReturn.java
Exercise
Make a method that returns a specified
number of copies of a word in an array
for example:
String[] items = copies(6, "Hello");
items
“hello”
“hello”
“hello”
“hello”
“hello”
“hello”
Questions