Java学习 - 方法

Java 方法

Java语言没有成员函数,函数声明在类中,称为成员方法。有静态方法和实例方法两种。

方法声明

[修饰符] 返回值类型 方法([形式参数列表]) [throws 异常类列表]
{
	语句序列;
	[return [返回值]]
}

声明 main 方法

public static void main(String[] args){
	// insert code...
}

The method main cannot be declared static; static methods can only be declared in a static or top level type

被虚拟机调用的主函数必须声明为 public static void main(String args[]){ ... }

且声明在一级类中或静态类中

主函数不能直接调用非静态方法,必须先实例化对象,通过定义方法的对象来调用方法。对于静态方法,main函数可以直接通过classname.options()调用

举例:在类public class HelloWorld中声明main函数和方法public static int binary_search()

package hehe;

public class HelloWorld {
	public static void main(String ards[]) {
		java.util.Scanner sc = new java.util.Scanner(System.in);
		int arr[];
		int size = sc.nextInt();
		arr = new int[size];
		for(int i = 0; i < size; i++) {
			arr[i] = sc.nextInt();
		}
		
		while(true) {
			int cmd = sc.nextInt();
			if(cmd == -1) {
				break;
			}else {
				int val = sc.nextInt();
				int ans = HelloWorld.binary_search(arr,val,0,size-1);
				if(ans == -0x3fff) {
					System.out.println("不存在");
				}else {
					System.out.println("pos: " + ans);
				}
			}
		}
	}
	
	public static int binary_search(int[] arr,int val,int head,int tail) { // 对于一个有序的非递减数组查找元素val
		int ans = 0;
		while(head < tail) {
			int mid = (head + tail) >> 1;
			if(arr[mid] > val) {
				tail = mid - 1;
			}else if(arr[mid] < val) {
				head = mid + 1;
			}else {
				ans = mid;
				break;
			}
		}
		if(arr[ans] == val) {
			return ans;
		}else {
			return -0x3fff;
		}
	}
}	


常见的方法类型的注意事项

Java不存在默认参数表列,如果需要使用默认参数,应该采用函数重载的形式。

posted @ 2020-09-08 19:32  popozyl  阅读(171)  评论(0编辑  收藏  举报