slides - Angus Forbes

Download Report

Transcript slides - Angus Forbes

CS 5JA Introduction to Java
Arrays
An array is simply an ordered list of elements.
All the elements are of the same data type.
Thus you can talk about an array of ints, or an array of Strings, or an array
of Accounts, etc.
Arrays are used to keep track of a group of similar information. For
instance, if I am a bank and I have a list of Accounts I can store these
Accounts in an array.
This way, when I want to check the balance of all of them, I don’t need to
get each Account one at a time. Instead I can iterate through the list
more easily.
CS 5JA Introduction to Java
Arrays
It’s kind of like taking a scattered pile of papers and putting them neatly in
a filing cabinent.
Here’s how you declare an array and initialize an array
int[] numberArray;
numberArray = new int[100];
In the declaration, the brackets next to the data type indicate that you are
creating an array of that type.
In the initialization of the array, the number in the brackets describe how
many elements are in the array.
Right now, you have an empty filing cabinet with room for 100 numbers.
But there is nothing in the filing cabinent.
CS 5JA Introduction to Java
Arrays
We can iterate through the array (the filing cabinet) and put number in
each position:
for (int i = 0; i < numberArray.length; i++)
{
numberArray[i] = (int) (Math.random() * 10);
}
Likewise, later on we can access the array and iterate through every
element in the array:
for (int i = 0; i < numberArray.length; i++)
{
System.out.println(“number at position “ + i + “ is “ + numberArray[i]);
}
CS 5JA Introduction to Java
Arrays
We get at the data in the array using the indexing notation:
int checkNumber = myNumbers[0];
int checkNumber = myNumbers[55];
etc...
CS 5JA Introduction to Java
Arrays
what’s going on in these code snippets?
int[] myIntArray = new int[3];
System.out.println(“num = “ + myIntArray[1]);
int[] myIntArray = new int[3];
myIntArray[0] = 99;
myIntArray[1] = 98;
myIntArray[2] = 97;
myIntArray[3] = 96;
double[] myDblArray = new double[2];
myDblArray[0] = 99.9;
myDblArray[1] = -100.0;
System.out.println(“num = “ + myIntArray[2]);
CS 5JA Introduction to Java
Arrays
int[] myIntArray = new int[3];
myIntArray[0] = 2;
myIntArray[1] = 0;
myIntArray[2] = 1;
myIntArray[3] = 17;
what does myIntArray[2] equal?
what does myIntArray[myIntArray[0]] equal?
what does myIntArray[myIntArray[0] – myIntArray[2]] equal?
CS 5JA Introduction to Java
Arrays
You can create, initialize, and fill an array all at the same time with this shortcut
syntax:
String[] myStrArray = {“Duck”, “Duck”, “Duck”, “Goose”};
boolean[] myBoolArray= {false, false, false, true};
what is myStrArray[1] contain?
what does x equal?
boolean x = myBoolArray[0];
what does x equal?
boolean x = myBoolArray[4];
what does str equal?
boolean str = myStrArray[3];
CS 5JA Introduction to Java
Arrays
String[] grades = {“A”, “A+”, “C”, “F”, “B+”};
How do I change the grade from a C to an A?
CS 5JA Introduction to Java
Arrays
String[] grades = {“A”, “A+”, “C”, “F”, “B+”};
How do I change the grade from a C to an A?
grades[2] = “A”;
Or something like:
String newGrade = “A”;
grades[2] = newGrade;
CS 5JA Introduction to Java
Arrays
What are arrays good for?
An array is a simple data structure. That is, you have a set of data and you
give it some structure.
I used the example of a pile of papers that you put into a filing cabinet.
The main things you can do with your filing cabinet:
storing information, sorting information and searching for information
[see example program, ArraysTest.java]
CS 5JA Introduction to Java
Arrays
You can also pass arrays to methods just like other data types: This
sample shows how to use one of the binarySearch methods in the
Arrays library.
public Test() {
int[] someArray = {2, 4, 1, -4, 5, 6};
boolean hasZero = doesListContainAZero(someArray);
}
public boolean doesListContainAZero(int[] intArray)
{
if (Arrays.binarySearch(intArray, 0) > -1)
{
return true;
}
return false;
}
CS 5JA Introduction to Java
Pass-by-value vs Pass-by-reference
In Java, when you pass a variable to a method it either
a) makes a new variable which is a copy of the original value, even if the
variable has the same name.
b) passes in the exact same data, even if the variable is given a different
name.
The first possibility is called “passing-by-value” and it is what happens for
any primitive data types (ints, booleans, doubles, etc).
Every other data type in Java uses “passing-by-reference”. This includes
every object and arrays.
CS 5JA Introduction to Java
Pass-by-value vs Pass-by-reference
When something is passed-by-reference, it means that any modification to
the data within a method will affect the data outside the method as well.
When something is passed-by-value, it means that any modification to the
data within the method has no affect whatsoever on the data outside
the method.
public void method1() {
int x = 5;
method2(x);
System.out.println(“x = “ + x); //what is x?
}
public void method2(int x) {
x = 6;
}
CS 5JA Introduction to Java
Pass-by-value vs Pass-by-reference
Arrays are passed-by-reference
public void method1() {
int[] arr = {5, 6, 7};
method2(arr);
//what is arr[0]?
System.out.println(“arr[0] = “ + arr[0]);
}
public void method2(int[] aNewArray) //not really new!
{
aNewArray[0] = 1001;
}
CS 5JA Introduction to Java
Pass-by-value vs Pass-by-reference
Primitive values in arrays are still passed-by-value
public void method1() {
int[] arr = {5, 6, 7};
method2(arr[0]); //just an int!
//what is arr[0]?
System.out.println(“arr[0] = “ + arr[0]);
}
public void method2(int aNewInt) //it really is new!
{
aNewInt = 1001;
}
CS 5JA Introduction to Java
Multi-dimensional Arrays
You can also make an array of arrays, also called a Multi-dimensional
array.
For instance, to declare a two-dimensional int array, you can do this:
int[][] da = new int[2][];
da[0] = new int[] {5,4,3,2,1};
da[1] = new int[2];
da[1][0] = 100;
da[1][1] = 99;
So what’s in da[0]? What’s in da[1]? What value is da[0][2]?
What value is da[1][3]? What value is da[1][1]?
What happens if you print d[0] or d[1]?
CS 5JA Introduction to Java
Multi-dimensional Arrays
You can also use the shortcut method for multidimensional arrays:
int da[][] = { {1, 2, 3}, {10, 11, 12} };
[see ArraysTest.java]
You can have as high a dimension as you want...
[see ArraysTest.java]
CS 5JA Introduction to Java
Multi-dimensional Arrays
Main issue with arrays...
You have to know their size before you work with them. You can’t arbitrarily
add extra data into them without recreating them from scratch.
The more flexible way is to use the List interface... which we’ll talk about
another time.
CS 5JA Introduction to Java
Quick note about debugging...
If your program doesn’t compile, then you have a syntax error.
The compiler will provide you with a list of errors and line numbers for where each
error occurs.
Sometimes it’s a little off. The error might be that you forgot a semi-colon on a line,
but the line that shows up as an error is the line below. To the compiler, the
error doesn’t really happen until it runs into something it can’t handle, which in
this case is when all of sudden there is something unexpected.
System.out.print(“hello”)
System.out.print(“again”);
The compiler removes all whitespace (except within quotes) so it sees something
like this...
System.out.print(“hello”)System.out.print(“again”);
So it finds the error at the capital S at the beginning of line 2.
CS 5JA Introduction to Java
Quick note about debugging...
If your program compiles but gives you unexpected results, then you have
a logical error.
You will have no information about why it isn’t doing what you wanted it to!
There are tools called debuggers which you can attach to your program
and step through code so you can tell what’s going on at every point.
But usually the simplest solution is to break things into small steps and
make sure that each of those steps work.
For instance, you can take a complicated piece of code and break it up into
smaller methods, and then write test cases to make sure that the
individual methods are doing what they are supposed to.
CS 5JA Introduction to Java
Quick note about debugging...
The main thing though to remember is that System.out.println is your
friend.
You can use it to make sure that your code has gotten to a certain place.
You can use it to make sure that you have the right values at particular
variables
public void myMethod(int a, int b)
{
System.out.println(“in myMethod, int a = “ + a);
System.out.println(“int b = “ + b);
int c = complicatedFunction(a, b);
System.out.println(“ok, c = “ + c);
}
CS 5JA Introduction to Java
Passing in arguments from the command line
We’ve talked about the main mathod signature:
public static void main (String args[])
What does the String args[] part do?
It says that the method expects an array of type String. Built in to Java is
the ability to pass Strings in from the command line, like so:
java MyProgram str0 str1 str2
In the main method you can access these Strings:
CS 5JA Introduction to Java
Passing in arguments from the command line
public static void main (String args[])
{
for (int i = 0; i < args.length; i++)
{
System.out.println(“args[“+i+”] = “ + args[i]);
}
}
You can use these arguments to pass in parameters, filenames, numbers,
etc.
But as you can see, by default they are Strings, so you need to convert
them to other data types if necessary.
CS 5JA Introduction to Java
Parsing data from a String
Commonly, you’ll want to get a number out of a String. If a user passes in
the string “5”, you will want to convert it to an int so that you can do
something with it.
There are different ways to do this. Because it is so common, there is a
built-in utility method in the Integer class which lets you parse out a
number:
int num = Integer.parseInt(“5”);
String numApples = “I have 5 apples”;
int num = Integer.parseInt(numApples);
CS 5JA Introduction to Java
Parsing data from a String
For more complex parsing, you can use the Scanner as we have already
done.
String numApples(“I have 10 apples!”);
Scanner s = new Scanner(numApples);
while(s.hasNext())
{
if(s.hasNextInt())
{
int num = s.nextInt();
}
}
If you try to scan for a data type that isn’t there you will get an Exception,
in this case a InputMismatchException.
CS 5JA Introduction to Java
Exceptions
Exception handling is the term used for dealing with errors. So far, we
have assumed that if there are any errors then they are “fatal”. We
either explicitly exit the program immediately, or we let the Java exit the
program when it discovers a run-time error.
However there are many cases when we might not want to exit the
program when there is an error, or make sure that we haven’t left any
resources open (ie databases, files, usb devices, etc), or at the very
least print the reason why there is a problem before exiting.
We can do this by using the exception handler to “catch” the error.
CS 5JA Introduction to Java
Exceptions
Certain objects will throw errors when something inappropriate happens.
So we can wrap code in a try-catch block to try and make sure the code
works, and if not, catch the error and then decide what to do.
Scanner s = new Scanner(System.in);
while(s.hasNext())
{
int num = s.nextInt();
}
If a user types letters instead of number, the Scanner method will throw a
run-time error, and the program will exit and print an error message to
the screen.
CS 5JA Introduction to Java
Exceptions
But if we wrap it in a try-catch block, then we can stop the code from exiting and
decide if it’s really a problem or not.
Scanner s = new Scanner(System.in);
try
{
while(s.hasNext())
{
int num = s.nextInt();
}
}
catch (InputMismatchException ime)
{
System.out.println(“hey– you did something wrong! But no worries!”);
}
You can look to see what errors might be thrown by a method by looking at the
JavaDocs
CS 5JA Introduction to Java
Exceptions
public int nextInt()
 Scans
the next token of the input as an int.
Returns:

the int scanned from the input
 Throws:
InputMismatchException - if the next token does not
match the Integer regular expression, or is out of
range
 NoSuchElementException - if input is exhausted
 IllegalStateException - if this scanner is closed

CS 5JA Introduction to Java
Exceptions
Some methods require that you catch the errors.
Someone asked about pausing the program. Since pausing the program
basically creates a new temporary process which can potentially be
interrupted (we don’t need to get into the details of threading right now),
we are required to wrap it in a try-catch block.
try
{
Thread.sleep(1000); //pause for 1000 milliseconds, or 1 second
}
catch(InterruptedException ie)
{
System.out.println(“just to let you know, we didn’t actually sleep for 1
second because we were interrupted!”);
}
CS 5JA Introduction to Java
Exceptions
Another example: if you try to use a file ten you are required to wrap it in a try-catch
block in order to handle the possibility that the file doesn’t actually exist.
File file = new File(“text.txt”);
Scanner scanner = null;
try {
// Create a scanner to read the file
scanner = new Scanner (file);
} catch (FileNotFoundException e) {
System.out.println ("File not found!");
// Stop program if no file found
System.exit (0);
// or we could force the user to entire a new filename, or browse for the file, etc
}
And this is the main reason I’m introducing this now, because your homework will
require that you read from and write to a file.
CS 5JA Introduction to Java
Reading from a file
There are different ways to read from a file. But this one makes it
especially easy to read text from a file. Others are better for images,
etc.
We’ve used the Scanner to read text from the command prompt, but it can
also be used to read from a file.
First, create a File object with a filename:
File file = new File(“myTextFile.txt”);
Then make a Scanner that scans from that file:
Scanner fileScanner = new Scanner(file);
CS 5JA Introduction to Java
Exceptions
Since this particular constructor explicitly throws an exception, we just
need to wrap it in the appropriate try-catch block
Scanner fileScanner;
try
{
fileScanner = new Scanner(file);
}
catch (FileNotFoundException e)
{
//handle error in some way...
}
CS 5JA Introduction to Java
Parsing text from a file
Now we can use the normal Scanner operations to put the contents of the
file into variables that we can use in our program.
Here’s a file called “grades.txt”:
87
99
12
80
100
CS 5JA Introduction to Java
Parsing text from a file
Scanner fileScanner;
try
{
fileScanner = new Scanner(“grades.txt”);
}
catch (FileNotFoundException e)
{ System.out.exit(0); }
int[] grades = new int[5];
for(int i = 0; i < 5; i++)
{
grades[i] = fileScanner.nextInt();
}
CS 5JA Introduction to Java
Writing text to a file
The opposite of reading text to a file is writing text to a file. Java has a
simple method for formatting data to a String, the terminal, or to a file. It
uses the same conventions as the “printf” command you may have
seen in the textbook.
It interprets special codes as particular data types, these are the only ones
we’ll be concerned with
%d = number (int or long)
%s = string
%f = decimal (float or double)
int temperature = 55;
System.out.printf(“It is %d degrees out today\n”, temperature);
CS 5JA Introduction to Java
Writing text to a file
File file = new File(filename);
Formatter formatter = null;
try {
formatter = new Formatter (file);
}
catch (FileNotFoundException e) {
//not a problem because we are about to create the file!!!
}
for(int i = 0; i < grades.length; i++)
{
formatter.format (“Grade for student %d is %d\n”, i, grades[i]);
}
//need to “flush” the data to the file, then close the file.
formatter.flush ();
formatter.close ();