Methods and input
A method is a named piece of a program. You have used main and println; now write your own.
A method declares what it takes (its parameters) and what it gives back (its return type):
public class Squares {
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
for (int i = 1; i <= 4; i++) {
System.out.println(i + " squared is " + square(i));
}
}
}
static int square(int n) takes one int, called n inside the method, and returns an int. A method
that returns nothing has the return type void, like main.
Reading input
Scanner reads what the user types (the program's standard input). in.nextInt() reads the next
whole number; in.hasNextInt() tells whether there is one. In a lesson block the input can be given in
advance, as in the next exercise; in your own programs, type into the output area while the program
runs.
The input holds some numbers. Complete the method sum so that it reads every number and returns their
total; the program should then print Sum: 12.
import java.util.Scanner;
public class Sum {
static int sum(Scanner in) {
int total = 0;
// read every number: while (in.hasNextInt()) { … }
return total;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Sum: " + sum(in));
}
}
Two files
Bigger programs are split into several classes, one per file. Here Main uses a method of the class
Greeter, which lives in Greeter.java; javac compiles both. In this block you can also add files
(+), rename them (double-click a tab) and delete them (×).
public class Main {
public static void main(String[] args) {
System.out.println(Greeter.greet("Ada"));
System.out.println(Greeter.greet("Grace"));
}
}
That is the end of the first five lessons. Everything you wrote is in /home/student in this browser;
the Environment panel downloads it as a .zip.