You are on page 1of 2

import java.util.

*;
// A method is a named block of code. We can call a method instead of redefining
// an operation each time we need to perform that operation.
// The method header consists of the return type, the method name, and the paren
thesized
// parameter list. The body is just the stuff to execute when the method is call
ed.
public class MethodPractice {
// For now, all of our methods must be declared "static", so that we can
call them
// from main(). When we talk about classes later in h semester, we will
fix this.
// This method returns nothing, and takes no input
static void message ()
{
// Side effect only
System.out.println("Hello, world!");
}
// This method takes no input, but returns an integer value
static int rollDice ()
{
Random r = new Random();
int die1 = r.nextInt(6) + 1;
int die2 = r.nextInt(6) + 1;
return die1 + die2;
}
public static void main (String [] args)
{
message();
int roll = rollDice();
System.out.println("You rolled: " + roll);
rollDice();
line(5);
line(10);
line(3);
System.out.println( getUsername("foo@bar.com") );
}
static void line (int n)
{
// side effect: print out n * characters
while (n > 0)
{
System.out.print("*");
n = n - 1;
}
System.out.println();
}

static String getUsername (String address)


{
// Extract characters before the @ sign
int at = address.indexOf("@");
return address.substring(0, at);
}
}

You might also like