Java 2012-02-09

Материал из SEWiki
Перейти к: навигация, поиск

Примеры с лекции

1. Привет, Мир!

//HelloWorld.java

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, world!");
    }
}

2. Привет, Человек!

//HelloWorld.java

public class HelloWorld {
	public static void main(String[] args) {
		if (args.length > 0) {
			System.out.println("Hello World, " + args[0] + "!");
		} else {
			System.out.println("Error");			
		}
	}
}

3. Привет, люди!

//HelloWorld.java

public class HelloWorld {
	public static void main(String[] args) {
		for (int i = 0; i < args.length; i++) {
			System.out.println("Hello World, " + args[i] + "!");
		}
	}
}

4. Привет, люди-2!

//HelloWorld.java

public class HelloWorld {
	public static void main(String[] args) {
		for (String str : args) {
			System.out.println("Hello World, " + str + "!");
		}
	}
}

5. Исключения

//ExceptionTest.java

class MyException extends Exception {
		public MyException(String msg) {
			super(msg);			
		}
}

public class ExeptionTest {
	public void foo() throws MyException {
		System.out.println("Testing exceptions...");
		throw new MyException("Kernel panic!!!");
	}
	
	public static void main(String[] args) {
		try {
			ExeptionTest t = new ExeptionTest();
			t.foo();
		} catch (MyException e) {
			e.printStackTrace(System.err);
		}
	}

}

6. Калькулятор

//Parser.java


public class Parser {
	public static int parseInt(String str) {
		int result = 0;
		for (int i = 0; i < str.length(); i++) {
			result = result*10 + str.charAt(i)-'0';			
		}
		return result;
	}
}
//AdvancedParser.java

public class AdvancedParser extends Parser {
	public static int parseInt(String str) {
		int result = Parser.parseInt(str);
		return result*2;
	}
}
//Calc.java

public class Calc {
	public static void main(String[] args) {
		if (args.length < 2) {
			System.out.println("Error");			
		} else {
			System.out.println(Parser.parseInt(args[0])+Parser.parseInt(args[1]));			
		}
	}

}