2008年12月7日 星期日

simple java(十)---methods(functions)(2)

用functions來寫的比較大小.

例一.

import javax.swing.*;
public class Maximum {
public static void main(String args[]) {
String s1 = JOptionPane.showInputDialog("Enter first value");
String s2 = JOptionPane.showInputDialog("Enter second value");
int number1 = Integer.parseInt(s1);
int number2 = Integer.parseInt(s2);
int maxvalue = max(number1, number2);
System.out.println("The max value is: " + maxvalue);}
public static int max(int x, int y){
return (x > y) ? x : y;}}
*****************************
例二.
class PassByValue {
public static void main(String s[]) {
int a=1, b=2;
System.out.println("a=" + a + " b=" + b);
swap(a, b);
System.out.println("a=" + a + " b=" + b);}
public static void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}}
執行結果:
a=1 b=2
a=1 b=2
*********************
Scope Rules Example
class PassByValue {
public static void main(String s[]) {
int a=1, b=2, temp=0;
swap(a, b);
System.out.println("a=" + a + " b=" + b);
System.out.println("temp=" + temp);}public static void swap(int x, int y) {int temp= x;x = y;y = temp;}}
執行結果..
a=1 b=2
temp=0

沒有留言: