Topics:

  • class Math
    • PI, E
    • sin(), cos(), exp()
    • random()
    • abs(), floating point equality comparisons
  • class String
    • String objects and return values
    • concatenation
    • reference types, comparison, equals()
    • length(), substring()

Assignment

HelloMath.java

public class HelloMath
{
    public static void testSin(double input, double expected)
    {
        double result = Math.sin(input);

        System.out.print("input: " + input + " expected: " + expected +
                " result: " + result + " ");

        if (Math.abs(result - expected) < 1e-6)
        {
            System.out.println("Awesome!");
        }
        else
        {
            System.out.println("Bogus!");
        }
    }

    public static void hello()
    {
        System.out.println(Math.PI);
        System.out.println(Math.E);

        System.out.println(Math.cos(0));
        System.out.println(Math.cos(Math.PI/2));
        System.out.println(Math.sin(Math.PI));
    }

    public static void main(String[] args)
    {
        System.out.println("Hello, world!");
        hello();
        testSin(Math.PI, 0);
    }
}

HelloString.java

public class HelloString
{
    public static void hello()
    {
        String s = "Hello, world!";
        System.out.println(s);

        String t = new String("Hello, world!"); // create a new object of type String
        System.out.println(t);

        System.out.println("s == t: " + (s == t));
        System.out.println("s.equals(t): " + s.equals(t));
    }

    public static String greet(String name)
    {
        return "Hello, there, " + name + "!"; // + is string concatenation
    }

    public static boolean isPolite(String sentence)
    {
        if (sentence.substring(0, 6).equals("Please"))
            return true;
        else
            return false;
    }

    public static void main(String[] args)
    {
        hello();

        System.out.println(greet("Sydney"));
        System.out.println(greet("Riley"));
        System.out.println(greet("Ashley"));
        
        String s1 = "Please pass the sugar.";
        System.out.println(s1 + ": " + isPolite(s1));
        String s2 = "Please pass the salt.";
        System.out.println(s2 + ": " + isPolite(s2));
        String s3 = "Give me a good grade.";
        System.out.println(s3 + ": " + isPolite(s3));

        System.out.println("length of s1: " + s1.length());
    }
}

HelloRandom.java

public class HelloRandom
{
    public static int random1to10()
    {
        double x = Math.random() * 10 + 1;
        return (int) x;
    }

    public static float randomFloat()
    {
        return (float)Math.random() * 100.0f;
    }

    public static void main(String[] args)
    {
        for (int i=0; i<5; i++)
            System.out.println(random1to10());

        System.out.println();
        for (int i=0; i<5; i++)
            System.out.println(randomFloat());
    }
}

notes

pdf