Monday, January 28, 2019

Java Variables, Conditionals, Loops, Functions, just a bit.

Java Data Types
import java.awt.*;

Public class example {

    boolean abool = true;
    char letter = 'A';
    byte abyte;
    short ashort;
    int aint = 0;
    long along = 123456000;
    Long anotherL = 123456000 ; // Unsigned 64 bits
    float afloat = 33.55f;
    double adouble = Math.PI;

    String astring = "This is a string.";
    Color acolor = Color.RED;

}
Conditionals
# Example conditionals
public class howold {
    public static void main (String[] args) {

        String name;
        int age;
        Scanner in = new Scanner(System.in);
        System.out.println ("Hello, Please enter your name and age.");
        name = in.nextLine();
        age = in.nextInt();
        System.out.println ("Hello, " + name + ", \n\tyou are " + age + " years old.");

        if (age < 3) {
            System.out.println ("Are you sure?");
        }
    }
}

# more examples
public class howold {
    public static void main (String[] args) {

        String s = "";
        if ( s == "string" ) {
            System.out.println ("This is a string.");
        } else if ( s == "not a string" ) {
            System.out.println ("This is not a string.");
        } else {
            System.out.println ("What is this?");
        }
    }
}
Exercise: Print different greetings for people at different ages.

Loops
# Example loops
class example {
    public static void main (String[] args) {
        for (String s : args ) {
            System.out.println ( s );
        }
    }
    String s = "";
    for (int i = 0; i <10; i++) {
        s += 'A';
    }
}

class testloops {
    // Do/whil (post-test) 
    // While (pre-test)
    // for (pre-test)

    public void loopwhile () {
        int loop_count = 3;
        while ( loop_count > 0 ) {
            System.out.println ( loop_count );
            loop_count--;
        }
    }
    
    public void loopdowhile () {
        int loop_count = 3;
        do {
            System.out.println ( loop_count );
            loop_count--;
        } while ( loop_count > 0 );
    }
}
Functions
# Example functions
    public static void main (String[] args) {
        thisfunc ( 3, "testfunc" );
    }

    public static void thisfunc ( int i, String s) {
        System.out.println ( i );
        System.out.println ( s );
    }
Exceptions
# Example exceptions
    public static void main (String[] args) {
        int first;
        if (args.length > 3) {
            try {
                first = Integer.parseInt (args[0]);
            }
            catch (NumberFormatException e) {
                System.err.println ("Error: too many arguments.");
                System.exit(1);
            }
        }
    }
}

No comments:

Post a Comment