90 likes | 189 Views
IDS 201 Introduction to Business Programming (Fall 2013). Week2. s tatic class method. p ublic class ExampleClass { public static void main(String[] args ){ int x = 5; int y = 10; int sum; sum = add( x,y );// can also use sum = ExampleClass. add (x, y);
E N D
IDS 201Introduction to Business Programming (Fall 2013) Week2
static class method public class ExampleClass{ public static void main(String[] args){ int x = 5; int y = 10; int sum; sum = add(x,y);// can also use sum = ExampleClass.add(x, y); System.out.printf(“%d + %d = %d”, x, y, sum); } public static int add(intfirst_num, intsecond_num){ int result = 0; result = first_num + second_num; return result; } }
System.out.printf • Copy everything except the format specifiers in the first parameter out to the output (process escape sequences). System.out.printf(“the\tresult:\n%s\ndone”,10); the result: 10 done • The number of format specifiers in the first parameter MUST be equal to the number of variables/values you want to output in the second parameter.
Scanner • Add the following statement before your class definition import java.util.Scanner; • Define a Scanner object variable Scannerobj_name= newScanner( System.in); • obj_name.nextInt() reads one value of type int from the user and returns it. int x = obj_name.nextInt(); // the value you typed is stored into x. • nextLong(), nextDouble(), nextBoolean(), nextLine(), next()
Example import java.util.Scanner; public class ScannerClassExample{ public static void main(String args[]) { Scanner sc = new Scanner(System.in); //define a Scanner object variable System.out.println("please enter your name"); String name = sc.nextLine(); // get a string from user System.out.println(“Hello " + name); System.out.println("please enter an integer"); intnum = sc.nextInt(); // get an integer from user System.out.println(“the integer you entered is " + num); } }
Comments • Use comments to provide overview or summaries of chunks of codes. • Use commenting for your debugging. • Three types of comments in Java • /* text */: the compiler ignores everything from /* to */. • // text : the compiler ignores everything from // to the end of the line. • /** text */: this is a documentation comment (doc comment for short).
Example /** * It is implemented by @author: Alice; * Last modified on @date: 2013-08-01; * no input parameters @param: null; */ public class HelloWorldApp { /* The main purpose of the HelloWorld Class is to display “Hello World”. */ // subroutine main(); public static void main(String[] args) { System.out.println("Hello World!"); //Display the string. } }
/* text */ is usually for methods and classes. • // text is for remarks inside method bodies. • Do NOT nest comments.