Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Java Programing
Methods
Copyright 2008 by Pearson Education
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
Define a method
Invoke a method
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
2
Defining Methods
A method is a collection of statements that are
grouped together to perform an operation.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
3
Method Signature
Method signature is the combination of the method name and the
parameter list.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
4
Formal Parameters
The variables defined in the method header are known as
formal parameters.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
5
Actual Parameters
When a method is invoked, you pass a value to the parameter. This
value is referred to as actual parameter or argument.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
parameter list
method
signature
return value
}
6
Return Value Type
• A method may return a value.
• The returnValueType is the data type of the value the method
returns.
• If the method does not return a value, the returnValueType is the
keyword void. For example, the returnValueType in the main
method is void.
Define a method
modifier
method
header
return value
type
Invoke a method
method
name
formal
parameters
int z = max(x, y);
public static int max(int num1, int num2) {
actual parameters
(arguments)
int result;
method
body
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
7
parameter list
method
signature
return value
Calling Methods
Testing the max method
This program demonstrates calling a method max to return the largest of the int values
8
Calling Methods, cont.
pass the value of i
pass the value of j
9
Trace Method Invocation
i is now 5
10
Trace Method Invocation
j is now 2
11
Trace Method Invocation
invoke max(i, j)
12
Trace Method Invocation
invoke max(i, j)
Pass the value of i to
num1
Pass the value of j to
num2
13
Trace Method Invocation
declare variable result
14
Trace Method Invocation
(num1 > num2) is true
since num1 is 5 and
num2 is 2
15
Trace Method Invocation
result is now 5
16
Trace Method Invocation
return result, which is 5
17
Trace Method Invocation
return max(i, j) and
assign the return value
to k
18
Trace Method Invocation
Execute the print
statement
19
Returning a value
public static type name(parameters) {
statements;
...
return expression;
}
Example:
// Returns the slope
public static double
{
double dy = y2 double dx = x2 return dy / dx;
}
of the line between the given points.
slope(int x1, int y1, int x2, int y2)
y1;
x1;
Return examples
// Converts Fahrenheit to Celsius.
public static double fToC(double degreesF) {
double degreesC = 5.0 / 9.0 * (degreesF - 32);
return degreesC;
}
// Computes triangle hypotenuse length given its side lengths.
public static double hypotenuse(int a, int b) {
double c = Math.sqrt(a * a + b * b);
return c;
}
You can shorten the examples by returning an
expression:
public static double fToC(double degreesF) {
return 5.0 / 9.0 * (degreesF - 32);
}…,,,
Fixing the common error
Instead, returning sends the variable's value
back.
The returned value must be stored into a variable
or used in an expression to be useful to the caller.
public static void main(String[] args) {
double s = slope(0, 0, 6, 3);
System.out.println("The slope is " + s);
}
public static double slope(int x1, int x2, int y1, int y2) {
double dy = y2 - y1;
double dx = x2 - x1;
double result = dy / dx;
return result;
}
System.out.printf
an advanced command for printing formatted text
System.out.printf("format string", parameters);
A format string contains placeholders to insert parameters into it:
%d
%f
%s
an integer
a real number
a string
Example:
int x = 3;
int y = 2;
System.out.printf("(%d, %d)\n", x, y);
// (3, 2)
CAUTION
A return statement is required for a value-returning
method. The method shown below in (a) is logically
correct, but it has a compilation error because the
Java compiler thinks it possible that this method
does not return any value.
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else if (n < 0)
return –1;
}
Should be
public static int sign(int n) {
if (n > 0)
return 1;
else if (n == 0)
return 0;
else
return –1;
}
(a)
(b)
To fix this problem, delete if (n < 0) in (a), so that
the compiler will see a return statement to be
reached regardless of how the if statement is
evaluated.
24
Reuse Methods from Other
Classes
NOTE: One of the benefits of methods is for
reuse. The max method can be invoked from any
class besides TestMax. If you create a new class
Test, you can invoke the max method using
ClassName.methodName (e.g., TestMax.max).
25
Reuse Methods from Other Classes
The easiest way to call a method is to declare it as public static
In the same class call the method using its name
In another class , call the method as classname.methodName
class A
{
public static void m1()
{
System.out.println(“Hello 2”);
}
public static void main (String [ ]
arg )
{
System.out.println(“Hello 1”);
m1();
System.out.println(“Hello 3”);
}
}
class B
{
public static void main (String [
] arg )
{
System.out.println(“Hello 1”);
A.m1();
System.out.println(“Hello 3”);
}
}
26
Call Stacks
27
Method Overloading
Method overloading
Several methods of the same name
Different parameter set for each method
28
Number of parameters
Parameter types
Method Overloading
A class may define multiple methods with the
same name---this is called method overloading
usually perform the same task on different data types
Example: The PrintStream class defines multiple
println methods, i.e., println is overloaded:
println (String s)
println (int i)
println (double d)
…
The following lines use the System.out.print method
for different data types:
System.out.println ("The total is:");
double total = 0;
System.out.println (total);
29
Method Overloading
Version 1
Version 2
double tryMe (int x)
{
return x + .375;
}
double tryMe (int x, double y)
{
return x * y;
}
Invocation
result = tryMe (25, 4.32)
More Examples
double tryMe ( int x )
{
return x + 5;
}
Which tryMe will be called?
tryMe( 1 );
double tryMe ( double x )
{
return x * .375;
}
tryMe( 1.0 );
tryMe( 1.0, 2);
tryMe( 1, 2);
double tryMe (double x, int y)
{
return x + y;
}
tryMe( 1.0, 2.0);
Recursion
Recursive method
Calls itself (directly or indirectly) through another method
Method knows how to solve only a base case
Method divides problem
Base case
Simpler problem
Method now divides simpler problem until solvable
Recursive call
Recursive step
32
Example Using Recursion:
The Fibonacci Series
Fibonacci series
Each number in the series is sum of two previous numbers
e.g., 0, 1, 1, 2, 3, 5, 8, 13, 21…
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n - 1) + fibonacci( n – 1 )
fibonacci(0) and fibonacci(1) are base cases
Golden ratio (golden mean)
33
Passing Parameters
public static void nPrintln(String message, int n) {
for (int i = 0; i < n; i++)
System.out.println(message);
}
Suppose you invoke the method using
nPrintln(“Welcome to Java”, 5);
What is the output?
Suppose you invoke the method using
nPrintln(“Computer Science”, 15);
What is the output?
Can you invoke the method using
nPrintln(15, “Computer Science”);
34
Pass by Value
When you invoke a method with an argument, the value of
the argument is passed to the parameter.
This is referred to as pass-by-value. If the argument is a
variable rather than a literal value, the value of the variable
is passed to the parameter. The variable is not affected,
regardless of the changes made to the parameter inside the
method.
35
Pass by Value…
36
Array parameter example
public static void main(String[] args) {
int[] iq = {126, 84, 149, 167, 95};
double avg = average(iq);
System.out.println("Average = " + avg);
}
public static double average(int[] array) {
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
return (double) sum / array.length;
}
Output:
Average = 124.2
Arrays passed by reference
Arrays are objects.
When passed as parameters, they are passed by reference.
(Changes made in the method are also seen by the caller.)
Example:
public static void main(String[] args) {
int[] iq = {126, 167, 95};
doubleAll(iq);
System.out.println(Arrays.toString(iq));
}
public static void doubleAll(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] = a[i] * 2;
}
}
Output:
[252, 334, 190]
a
iq
index
0
1
2
value
126
252
167
334
190
95
Arrays as return (declaring)
public static type[] methodName(parameters) {
Example:
public static int[] countDigits(int n) {
int[] counts = new int[10];
while (n > 0) {
int digit = n % 10;
n = n / 10;
counts[digit]++;
}
return counts;
}
Arrays as return (calling)
type[] name = methodName(parameters);
Example:
public static void main(String[] args) {
int[] tally = countDigits(229231007);
System.out.println(Arrays.toString(tally));
}
Output:
[2, 1, 3, 1, 0, 0, 0, 1, 0, 1]
Array param/return question
Modify our previous Sections program to use static
methods that use arrays as parameters and returns.
Sections attended: [9, 6, 7, 4, 3]
Student scores: [20, 18, 20, 12, 9]
Student grades: [100.0, 90.0, 100.0, 60.0, 45.0]
Sections attended: [6, 7, 5, 6, 4]
Student scores: [18, 20, 15, 18, 12]
Student grades: [90.0, 100.0, 75.0, 90.0, 60.0]
Sections attended: [5, 6, 5, 7, 6]
Student scores: [15, 18, 15, 20, 18]
Student grades: [75.0, 90.0, 75.0, 100.0, 90.0]
Example
Create circle class that consists of the circle radius with
methods to initialize the radius, calculate the circumference
of the circle, and calculate the area of the circle.
Example
Create a class Time that contains data members, hour,
minute, second to store the time value, and sets hour,
minute, second to zero, provide three methods for
converting time to ( 24 hour ) and another one for
converting time to (12 hour) and a function that sets the
time to a certain value specified by three parameters
Example
Write a 12-hour clock program that declares a clock class
to store hours, minutes, seconds, A.M. and P.M. provide
methods to perform the following tasks:
Set hours, minutes, seconds to 00:00:00 by default
Initialize hours, minutes, seconds, A.M. and P.M. from user
entries
Allow the clock to tick by advancing the seconds by one and at
the same time correcting the hours and minutes for a 12-hour
clock value of AM or PM
Display the time in hours:minutes:seconds AM / PM format
44
Find the output
int i = 1, j = 1, val;
while (i < 25){
System.out.println(j + " ");
val = i + j;
j = i;
i = val;
}
45
Find the output
int val;
for (val = -5; val <= 5; val++)
{
switch (val)
{
case 0:
System.out.println ("India");
break;
}
if (val > 0)
System.out.println ("B");
else if (val < 0)
System.out.println("X");
}
46
Program
Create class account to save personal account for a bank
with interest.
The class has account# and balance data
The class has operations:
deposit, withdraw, interest_earned {2% interest will be
credited to account at end of each month if balance
exceeds $10,000} and display_data
47
Arrays
array: object that stores many values of the same
type.
element: One value in an array.
index: A 0-based integer to access an element from an array.
index
0
1
2
3
value 12 49 -2 26
element 0
4
5
element 4
5
6
7
8
17 -6 84 72
9
3
element 9
Array declaration
type[] name = new type[length];
Example:
int[] numbers = new int[10];
index
0
1
2
3
4
5
6
7
8
9
value
0
0
0
0
0
0
0
0
0
0
Array declaration, cont.
The length can be any integer expression.
int x = 2 * 3 + 1;
int[] data = new int[x % 5 + 2];
Each element initially gets a "zero-equivalent" value.
Type
Default value
int
0
double
0.0
boolean
false
String
null
or other object (means, "no object")
What happens if …
Valid code:
int k=7;
long[] primes = new long[k];
Invalid Code:
int k;
long[] primes =new long[k];
Compilation Output:
MorePrimes.java:6: variable k might not have
been initialized
long[] primes = new long[k];
^
Accessing elements
name[index]
name[index] = value;
// access
// modify
Example:
numbers[0] = 27;
numbers[3] = -6;
System.out.println(numbers[0]);
if (numbers[3] < 0) {
System.out.println("Element 3 is negative.");
}
index
0
value 27
0
1
2
3
4
5
6
7
8
9
0
0
-6
0
0
0
0
0
0
0
Arrays of other types
double[] results = new double[5];
results[2] = 3.4;
results[4] = -0.5;
index
0
1
2
3
4
value 0.0 0.0 3.4 0.0 -0.5
boolean[] tests = new boolean[6];
tests[3] = true;
index
0
1
2
3
4
5
value false false false true false false
Out-of-bounds
Legal indexes: between 0 and the array's length - 1.
Reading or writing any index outside this range will throw an
ArrayIndexOutOfBoundsException.
Example:
int[] data = new int[10];
System.out.println(data[0]);
System.out.println(data[9]);
System.out.println(data[-1]);
System.out.println(data[10]);
//
//
//
//
okay
okay
exception
exception
index
0
1
2
3
4
5
6
7
8
9
value
0
0
0
0
0
0
0
0
0
0
Accessing array elements
int[] numbers = new int[8];
numbers[1] = 3;
numbers[4] = 99;
numbers[6] = 2;
int x = numbers[1];
numbers[x] = 42;
numbers[numbers[6]] = 11; // use numbers[6] as index
x
numbers
3
index
0
1
value
0
4
2
3
4
11 42 99
5
6
7
8
9
0
2
0
0
0
Arrays and for loops
It is common to use for loops to access array elements.
for (int i = 0; i < 8; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println(); // output: 0 4 11 0 44 0 0 2
Sometimes we assign each element a value in a loop.
for (int i = 0; i < 8; i++) {
numbers[i] = 2 * i;
}
index
0
1
2
3
4
value
0
2
4
6
8
5
6
7
10 12 14
The length field
An array's length field stores its number of elements.
name.length
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
// output: 0 2 4 6 8 10 12 14
It does not use parentheses like a String's .length().
What expressions refer to:
The last element of any array?
The middle element?
Weather question
Use an array to solve the weather problem:
How many days' temperatures? 7
Day 1's high temp: 45
Day 2's high temp: 44
Day 3's high temp: 39
Day 4's high temp: 48
Day 5's high temp: 37
Day 6's high temp: 46
Day 7's high temp: 53
Average temp = 44.6
4 days were above average.
Weather answer
// Reads temperatures from the user, computes average and # days above average.
import java.util.*;
public class Weather {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How many days' temperatures? ");
int days = console.nextInt();
int[] temperatures = new int[days]; // array to store days' temperatures
int sum = 0;
for (int i = 0; i < days; i++) {
// read/store each day's temperature
System.out.print("Day " + (i + 1) + "'s high temp: ");
temperatures[i] = console.nextInt();
sum += temperatures[i];
}
double average = (double) sum / days;
int count = 0;
// see if each day is above average
for (int i = 0; i < days; i++) {
if (temperatures[i] > average) {
count++;
}
}
// report results
System.out.printf("Average temp = %.1f\n", average);
System.out.println(count + " days above average");
}
}
A multi-counter problem
Problem: Examine a large integer and count the number
of occurrences of every digit from 0 through 9.
Example: The number 229231007 contains:
two 0s, one 1, three 2s, one 7, and one 9.
We could declare 10 counter variables for this...
int counter0, counter1, counter2, counter3, counter4,
counter5, counter6, counter7, counter8, counter9;
Yuck!
A multi-counter problem
A better solution is to use an array of size 10.
The element at index i will store the counter for digit value i.
for integer value 229231007, our array should store:
index
0
1
2
3
4
5
6
7
8
9
value
2
1
3
0
0
0
0
1
0
1
The index at which a value is stored has meaning.
Sometimes it doesn't matter.
What about the weather case?
Creating an array of tallies
int num = 229231007;
int[] counts = new int[10];
while (num > 0) {
// pluck off a digit and add to proper counter
int digit = num % 10;
counts[digit]++;
num = num / 10;
}
index
0
1
2
3
4
5
6
7
8
9
value
2
1
3
0
0
0
0
1
0
1
Array histogram question
Given a file of integer exam scores, such as:
82
66
79
63
83
Write a program that will print a histogram of stars indicating
the number of students who earned each unique exam score.
85:
86:
87:
88:
91:
*****
************
***
*
****
Histogram variations
Curve the scores; add a fixed number to each score.
(But don't allow a curved score to exceed the max of
101.)
Chart the data with a DrawingPanel.
window is 100px tall
2px between each bar
10px tall bar for each student who earned that score
Array histogram answer
// Reads an input file of test scores (integers) and displays a
// graphical histogram of the score distribution.
import java.awt.*;
import java.io.*;
import java.util.*;
public class Histogram {
public static final int CURVE = 5;
// adjustment to each exam score
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("midterm.txt"));
int[] counts = new int[101];
// counters of test scores 0 - 100
while (input.hasNextInt()) {
// read file into counts array
int score = input.nextInt();
score = Math.min(score + CURVE, 100);
// curve the exam score
counts[score]++;
// if score is 87, then counts[87]++
}
for (int i = 0; i < counts.length; i++) {
// print star histogram
if (counts[i] > 0) {
System.out.print(i + ": ");
for (int j = 0; j < counts[i]; j++) {
System.out.print("*");
}
System.out.println();
}
}
...
Array histogram solution 2
...
// use a DrawingPanel to draw the histogram
DrawingPanel p = new DrawingPanel(counts.length * 3 + 6, 200);
Graphics g = p.getGraphics();
g.setColor(Color.BLACK);
for (int i = 0; i < counts.length; i++) {
g.drawLine(i * 3 + 3, 175, i * 3 + 3, 175 - 5 * counts[i]);
}
}
}
Arrays of Arrays
Two-Dimensional arrays
float[][] temperature=new float[10][365];
10 arrays each having 365 elements
First index: specifies array (row)
Second Index: specifies element in that array (column)
In JAVA float is 4 bytes, total Size=4*10*365=14,600 bytes
Initializing Array of Arrays
int[][] array2D = { {99, 42, 74, 83, 100}, {90, 91, 72, 88, 95}, {88, 61,
74, 89, 96}, {61, 89, 82, 98, 93}, {93, 73, 75, 78, 99}, {50, 65, 92, 87,
94}, {43, 98, 78, 56, 99} };
//5 arrays with 5 elements each
Arrays of Arrays of Varying
Length
All arrays do not have to be of the same length
float[][] samples;
samples=new float[6][];//defines # of arrays
samples[2]=new float[6];
samples[5]=new float[101];
Not required to define all arrays
Initializing Varying Size
Arrays
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } };
//Three arrays
//First array has 3 elements
//Second array has 2 elements
//Third array has 5 elements
SOME USEFUL ARRAY OPERATIONS
Finding the Average of the Values in a Numeric
Array
To find the average of the values in a numeric
array, first find the sum of the values in the
array. Then divide this sum by the number of
elements in the array.
71
Examples Using Arrays
Using arrays to analyze survey
results
40 students rate the quality of
food
1-10 Rating scale: 1 mean awful, 10
means excellent
Place 40 responses in array of
integers
Summarize results
Sorting Arrays
Sorting data
Attracted intense research in computer-science field
Bubble sort
Smaller values “bubble” their way to top of array
Larger values “sink” to bottom of array
Use nested loops to make several passes through array
Each pass compares successive pairs of elements
Pairs are left along if increasing order (or equal)
Pairs are swapped if decreasing order
Searching Arrays: Linear
Search and Binary Search
Searching
Finding elements in large amounts of data
Determine whether array contains value matching key value
Linear searching
Binary searching
Searching Arrays: Linear
Search and Binary Search
Linear search
Compare each array element with search key
If search key found, return element index
If search key not found, return –1 (invalid index)
Works best for small or unsorted arrays
Inefficient for larger arrays
Searching Arrays: Linear
Search and Binary Search
Binary search
Efficient for large, sorted arrays
Eliminates half of the elements in search through each pass
Compare middle array element to search key
If element equals key
Return array index
If element is less than key
Repeat search on first half of array
If element is greater then key
Repeat search on second half of array
Continue search until
element equals search key (success)
Search contains one element not equal to key (failure)
Multidimensional Arrays
A farmer has 10 farms of beans each in 5 countries, and
each farm has 30 fields!
Three-dimensional array
long[][][] beans=new long[5][10][30];
//beans[country][farm][fields]
Input/output (I/O)
import java.io.*;
Create a File object to get info about a file
on disk.
(This doesn't actually create a new file on the hard disk.)
File f = new File("example.txt");
if (f.exists() && f.length() > 1000) {
f.delete();
Method name
Description
}
canRead()
returns whether file is able to be read
delete()
removes file from disk
exists()
whether this file exists on disk
getName()
returns file's name
length()
returns number of bytes in file
renameTo(file)
changes name of file
Output to files
PrintStream: An object in the java.io package that lets
you print output to a destination such as a file.
Any methods you have used on System.out
(such as print, println) will work on a PrintStream.
Syntax:
PrintStream name = new PrintStream(new File("file name"));
Example:
PrintStream output = new PrintStream(new File("out.txt"));
output.println("Hello, file!");
output.println("This is a second line of output.");
Details about PrintStream
PrintStream name = new PrintStream(new File("file name"));
If the given file does not exist, it is created.
If the given file already exists, it is overwritten.
The output you print appears in a file, not on the console.
You will have to open the file with an editor to see it.
Do not open the same file for both reading (Scanner) and
writing (PrintStream) at the same time.
You will overwrite your input file with an empty file (0 bytes).
System.out and PrintStream
The console output object, System.out, is a PrintStream.
PrintStream out1 = System.out;
PrintStream out2 = new PrintStream(new File("data.txt"));
out1.println("Hello, console!");
// goes to console
out2.println("Hello, file!");
// goes to file
A reference to it can be stored in a PrintStream variable.
Printing to that variable causes console output to appear.
You can pass System.out as a parameter to a method
expecting a PrintStream.
Allows methods that can send output to the console or a file.
Reading files
To read a file, pass a File when constructing a Scanner.
Scanner name = new Scanner(new File("file name"));
Example:
File file = new File("mydata.txt");
Scanner input = new Scanner(file);
or, better yet:
Scanner input = new Scanner(new File("mydata.txt"));
Prompting for a file name
We can ask the user to tell us the file to read.
The file name might have spaces; use nextLine(), not next()
// prompt for input file name
Scanner console = new Scanner(System.in);
System.out.print("Type a file name to use: ");
String filename = console.nextLine();
Scanner input = new Scanner(new File(filename));
What if the user types a file name that does not exist?
Compiler error w/ files
The following program does not compile:
import java.io.*;
import java.util.*;
// for File
// for Scanner
public class ReadFile {
public static void main(String[] args) {
Scanner input = new Scanner(new File("data.txt"));
String text = input.next();
System.out.println(text);
}
}
The following error occurs:
ReadFile.java:6: unreported exception java.io.FileNotFoundException;
must be caught or declared to be thrown
Scanner input = new Scanner(new File("data.txt"));
^
Testing for valid input
Scanner methods to see what the next token will be:
Method
hasNext()
hasNextInt()
Description
returns true if there are any more tokens of
input to read (always true for console input)
returns true if there is a next token
and it can be read as an int
hasNextDouble( returns true if there is a next token
)
and it can be read as a double
These methods do not consume input;
they just give information about the next token.
Useful to see what input is coming, and to avoid crashes.
Using hasNext methods
To avoid exceptions:
Scanner console = new Scanner(System.in);
System.out.print("How old are you? ");
if (console.hasNextInt()) {
int age = console.nextInt();
// will not crash!
System.out.println("Wow, " + age + " is old!");
} else {
System.out.println("You didn't type an integer.");
}
To detect the end of a file:
Scanner input = new Scanner(new File("example.txt"));
while (input.hasNext()) {
String token = input.next();
// will not crash!
System.out.println("token: " + token);
}