Chapter 4: Functions

function

The meaning of existence function: The main function is to solve those repeat and code segments having individual functions, modularity is to function.

These codes can have independent functions again packaged. What it is called out of the package function, it has a clear advantage to reduce code redundancy multiplexing function reduces the code amount of the main function, the main function appropriately split, for memory optimization.

public class HHH {

	public static void main(String[] args) {
		sum (1,10);
		sum (15,20);
		sum (25,35);

	}
	public static void sum (int begin,int end) {
		int sum = 0;
		for (int i = begin;i <= end;i++) {
			sum += i;
		}
		System.out.println(begin + "到" + end +"之间的和为 : " + sum);
	}

}

1. Function Format

Function Format:
Access function type return value type function name (parameter list) {

public static void main
      body of the function
      return value return;
}

Access: refers to the use of functions (internal and external)

public (public), protected (protected), the default does not write, private (proprietary).

Function type: refers to the function of the type of classification. Say is a function of the specific usage scenarios and applications.

static (static function), the default does not write (member functions), abstract (abstract function), native (local functions), synchronized (synchronous function).

Function name: This is the section of code a programmer to customize the name (identifier).

Return Value: returns the data type of the value is (compatible).

 

Parameter List: list of parameters with a plurality of parameter type, parameter name, mainly for transmitting data to a number of receiving external function.

Function body: those that code segment having individual functions.

return: only indicates the end of the current function, if there is a return value, the function will return before the end of the value returned to the caller.

Return Value: This is an independent feature worth calculation results of code blocks, with the need to pass to the outside return.

2, the classification function

There return value parameter argument has no return value, the return value without parameters, no parameters no return value.

* Note: Functions that return values ​​involved in the assignment, operation and output. No return value of the function call only.

3, the reference transfer function

Actual parameters (arguments): that is, when the function call, the data transfer function (constant, variable) called arguments.

In the form of parameters (parameters): When the function definition is the data, among the parameter list, called parameter.

 

Argument passes the address constants in the constant pool, the address of the object to the heap memory parameter.

Local variables: Variables Whenever created in a function, called local variables. Scope of local variables only in the current function. Formal parameter must be a local variable.

4, function stack

Run function is stack-based memory.

After a stack is advanced out of the container structure (sequence 123456 by bullets into the stack, the stack according to the order of 654,321). Each function may be understood as a bullet (function frame / stack frame) at the top has the main function operation priority. The main function is definitely the first into the stack. return the end of the current function -> popped the current function.

Which represents Pictured:

5, overloaded function

Overloaded function refers to the function of the same name that appears in the same class. And authority, return type, parameter names are not related. Only parameter types and permutations relationship.

Benefits overloaded is that we can extend the functionality of the function (function same name, but different parameter types, content execution may not be the same).

Find the appropriate function of the process: ① see if there is an exact parameters defined int + int see if there is (int, int)

② see if there is a compatible parameter defines int + int see if there is (double, double)

③ If a plurality of parameters defined compatible int + int (double, int) or (int, double) given case, reference is not clear.

public class HHH {

	public static void main(String[] args) {
		System.out.println(add(3,4.5));
	}
	public static double add (double a,double b){
		System.out.println("double + double");
		return a+b;
	}
	
}

We can see that can be transferred directly int double double double.

public class int兼容 {

	public static void main(String[] args) {
		System.out.println(add(3,4));
	}
	public static double add (int a,double b){
		System.out.println("int + double");
		return a+b;
	}
	
}

int int can also convert int double.

public class int兼容 {

	public static void main(String[] args) {
		System.out.println(add(3,4));
	}
	public static double add (int a,double b){
		System.out.println("int + double");
		return a+b;
	}
	public static double add (double a,int b){
		System.out.println("double + int");
		return a+b;
	}
	
}

But not both with double int int double use, so it will error, the emergence of compatible types.

6, recursive function calls

Reflect recursive function calls itself is the function itself.

Recursive problem are:

① In general, anything that can be Iteration (loop) to solve, can be recursive. Problem solving recursive, iterative might not be.

② recursive divide and conquer is actually an implementation of (an implementation of ideas).

③ is a recursive function onto the stack, the stack into the number is bound to occupy more memory, which can not be avoided.

④ on certain issues, and less than the recursive code written iterations; iterates on some issues can not be written, it can only use recursion.

⑤ divide and conquer algorithm is a kind of thinking, the main divide and conquer is a big issue to split, split into several small problems to solve, the solution will eventually be merged every little problem. In fact, divide and conquer is a kind of brute force method (exhaustive), but also a search for the optimal answer algorithms.

⑥ recursive: first recursive

Ⅰ forward segment: refers to the question from Dahua small.

End section Ⅱ: the problem can not continue to minor processing the current problem.

Ⅲ return segments: small After the issue is resolved, back up (no return of some of the problems).

Fibonacci number

20 prior to the evaluation and 11235813213455 ......

Recursive could write the following code:

public class HHH {

	public static void main(String[] args) {
		for (int i = 1;i <= 20;i++) {
			System.out.println(feibo(i));	
		}
	}
	public static int feibo (int n) {
		if (n == 2 || n == 1) {
			return 1;
		}
		return feibo(n - 2) + feibo(n - 1);
	}

}

We can see the results of the first term and the second term is 1, so we use a return1 it.

The basic frame recursively as follows:

Fibonacci iterative method of Number of:

public class HHH {

	public static void main(String[] args) {
		diedai(20);
	}
	public static void diedai (int n) {
		int a = 1;
		int b = 1;
		System.out.println(a);
		System.out.println(b);
		int c;
		for (int count = 2;count <= n;count++) {
			c = a + b;
			System.out.println(c);
			a = b;
			b = c;
			
		}
		
	}	
}

7, commonly used functions

7.1 Math class

(Value of Π) Math.E (value of e) Math.PI Math.abs (a) (absolute value)

                System.out.println(Math.E);//e的值
		System.out.println(Math.PI);//Π的值
		System.out.println(Math.abs(-2));//求绝对值

Math.ceil (a) (rounded up)

Math.floor (a) (rounded down)

Math.hypot (x, y) (the distance between two points)

                System.out.println(Math.ceil(1.8));//输出2
		System.out.println(Math.ceil(-1.8));//输出-1.0
		System.out.println(Math.floor(1.8));//输出1.0
		System.out.println(Math.hypot(3,4));//输出5.0
		

Math.max (a, b) (max)

Math.min (a, b) (min)

Math.pow (a, b) (a, b power)

 


		System.out.println(Math.max(1,8));//输出8
		System.out.println(Math.min(1,8));//输出1
		System.out.println(Math.pow(2,3));//输出2的3次方 8.0

Math.sqrt (a) (for prescribing a)

Math.random (to take a random number [0, 1))

Math.rint (a) (rounded (decimal))

Math.round (a) (rounded (integer))

                System.out.println(Math.sqrt(4));//输出2.0
		System.out.println(Math.random());//输出随机输出一个[0,1)的值
		System.out.println(Math.rint(1.5));//输出2.0
		System.out.println(Math.round(1.2));//输出1

7.2 String class

String basic data types but not a class, since it is a class, then certainly its associated functions.

7.2.1 relevant

char charAt (int index) (acquired character designation at a subscript, such as String s = "abcd" charAt (0) is the output from a 0,1,2,3 because he is to be assigned abcd.)

int (from left to right to find the location specified element in a string of the first occurrence) indexOf (int ch)

int lastIndexOf (int ch) (from left to right where to find the last occurrence of the specified element in a string)

int length () (length)

substring (int beginIndex, int endIndex) (first three values ​​taken)

                 String s="abcd";
	        /*
	        "abcd"
	         0123
	        */
	        //获取指定角标处的字符
	        System.out.println(s.charAt(0));//a
                //在字符串中从左到右查找指定元素第一次出现的位置   
	        System.out.println("abcccccd".indexOf('c'));//2
	        System.out.println("abcccccd".indexOf("cd"));//6
                //截取前三个值
		String s = "ababababaaa";
		System.out.println(s.substring(0,3));//[0,3)aba

7.2.2 determine the relevance

boolean contains (String s) (whether the specified substring contained in s)

boolean endsWith (String s) (whether the specified end of the substring s.)

boolean startsWith (String prefix) (determined at the beginning of the specified substring s) of 

int compareTo(String anotherString) 

     (The latter after the former is positive the ASCII
        System.out.println ( "ABC" .compareTo ( "ABD"));)

boolean equals(String anotherString)   

         Compares two strings are equal (the content ratio)
        System.out.println ( "ABC" .equals ( "ABC"));

boolean equalsIgnoreCase(String anotherString)  

        IgnoreCase Ignore case
        System.out.println ( "ABC" .equalsIgnoreCase ( " abc"));

boolean isEmpty () (determines whether or not the empty string)

7.2.3 amend the relevant

Modification of the string is never modify them itself of
the string itself is immutable!
Modify strings are often new string will modify the contents of the assignment and returns a new string

String replace(char oldChar, char newChar)  

         s="abababab";
        System.out.println(s.replace('a','c'));

         It will be converted to a c, but the number itself s not changed

String toUpperCase () (uppercase letters turn)

String toLowerCase () (the small letter)

String trim()      

       System.out.println("  abc abc abc   ".trim());

      When the output is automatically removed from the front space

s1 = 1231212316123123

s2 = 12

Determine how many times the string s2 occurs in s1 in?

Its code is expressed as:

public class HHH {

	public static void main(String[] args) {
		questions1 ();
	}
	public static void questions1() {
		int count = 0;
		String s1 = "1231212316123123";
		String s2 = "12";
		for (int i = 0;i < s1.length() - s2.length() + 1;i++) {
			String sub = s1.substring(i,i + s2.length());
			if(sub.equals(s2)){
				count ++;
			}
		}
		System.out.println("s2在s1中出现了" + count + "次");
		 
	}

}

I = 0 is defined as the string is counted from 0, then let i is smaller than these values ​​because it can not come to the end, when taken, but will come to the first string s2. Then we intercept the string s1, s2, taken in sequence starting from the string 0, and finally to determine whether it is equal.

 Question 2: Determine whether the string is a palindrome s
        s = "Shanghai water from the sea."

public class question2 {

	public static void main(String[] args) {
	String s = "上海自来水来自海上";
	int left = 0;
	int right = s.length() - 1;
	boolean flag = true;
	while (true) {
		if (s.charAt(left) == s.charAt(right)) {
			left++;
			right--;
			if (left >= right) {
				break;
			}
		}else {
			flag = false;
			break;
		}
	}
	
	System.out.println("这个是否是回文?" + flag);
	}

}

It is the first and last string a sequence comparison of the intermediate, until the number is greater than or equal to the right of the left, and can determine whether the palindromic

 Question 3: analog trim function, custom implementation s = "~ to Amway"

public class question3 {

	public static void main(String[] args) {
		String s = "     ashaj    ";
		int left = 0;
		int right = s.length() - 1;
		while (s.charAt(left) == ' ') {//左边向右走
			left++;
		}
		while (s.charAt(right) == ' ') {//右边向左走
			right--;
		}
		String res = s.substring(left,right+1);//走完所有的空格(rhght+1是右边取不到)
		System.out.println("[" + res + "]");
	}

}

Question 4: Find the largest s1 and s2 same substring (s1.length ()> s2.length ())
        s1 = "A Program Language But the Python IS IS SLOW";
        s2 = "But the Java Language Program IS IS A FAST "
        " But IS IS A Language Program "

public class questions4 {

	public static void main(String[] args) {
		 String s1="Python is a program language but is slow";
	     String s2="Java is a program language but is fast";
	     boolean flag = true;
	    for (int length = s2.length();length >= 1;length--) {//遍历
	    	
	    	for (int i = 0,j = length - 1;j < s2.length();i++,j++) {
	    		String sub = s2.substring(i,j+1);
	    		if (s1.contains(sub)) {
	    			flag = false;
	    			System.out.println("结果是[" + sub + "]");
	    			break;
	    		}
	    	}
	    	if (!flag) {
	    		break;
	    	}
	    }
	}

}

i = 0 because each time a string is taken from 0 to
j = length - 1 is the last one taken

j <s2.length () j can only reach the length s2 of
             

 

Exercises

Which code is represented as follows:

import java.util.Scanner;

public class Day41 {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.print("请输入一个数字: ");
		int num = in.nextInt();
		int sum = sumDigits(num);
		System.out.println(sum);
	}
	public static int sumDigits (int n) {
		int sum = 0;
		while (n != 0) {
			sum = sum + n % 10;
			n = n / 10;
		}
		return sum;
	}

}

import java.util.Scanner;

public class Day42 {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.print("请输入一个数字 : ");
		int num = in.nextInt();
		if (huiwen(num) ) {
			System.out.print("是回文");
		}else {
			System.out.print("不是回文");
		}
	}
	public static boolean huiwen (int num) {
		return reverse (num) == num;
	}
	public static int reverse (int num) {
		int sum = 0;
		while (num != 0) {
			sum = sum * 10 + num % 10;
			num /= 10;
		}
		return sum;
	}

}

import java.util.Scanner;

public class Day43 {

	public static void main(String[] args) {
		Scanner in  = new Scanner(System.in);
		System.out.print("请输入一个数字:");
		int line = in.nextInt();
		display (line);
	}
	public static void display (int line) {
		for (int i = 1;i <= line;i++) {
			for (int k=1;k<=line-i;k++ ) {
				System.out.print("  ");
			}
			for (int j=i;j>=1;j--) {
				System.out.print(j + " ");
			}
			System.out.println();
		}
	}

}

public class Day45 {

	public static void main(String[] args) {
		System.out.print(sqrt(16));

	}
	public static double sqrt (long n) {
		double lastGuess = 1;
		double nextGuess = (lastGuess + n / lastGuess) / 2;
		while (true) {
			if (Math.abs(nextGuess - lastGuess) < 0.00001) {
				return nextGuess;
			}
			lastGuess = nextGuess;
			nextGuess = (lastGuess + n / lastGuess) / 2;
		}
	}

}

Its code is expressed as:

public class Day46 {

	public static void main(String[] args) {
		int count = 0;
		int num = 2;
		while (true) {
			if (huisu(num)) {
				count ++;
				System.out.print(num + " ");
			}
			if (count % 10 == 0) {
				System.out.println();
			}
			if (count == 100) {
				break;
			}
			num ++;
		}
		
	}
	public static boolean huisu(int num) {
		return hui(num) && su (num);
	}
	public static boolean hui(int num){
        return reverse(num)==num;
    }
    public static int reverse(int num){
        int sum=0;
        while(num != 0){
            sum=sum*10+num%10;
            num/=10;
            
		}
        return sum;
	}
	public static boolean su (int num) {
		for (int i = 2;i < num;i++) {
			if (num % i == 0) {
				return false;
			}
		}
		return true;
	}

}

class Day47{
    public static void main(String[] args){
        int count=0;
        int num=2;
        while(true){
            if(isFanZhuanSuShu(num)){
                count++;
                System.out.print(num+" ");
                if(count%10==0){
                    System.out.println();
                }
            }
            if(count==100){
                return; //结束当前函数
            }
            num++;
        }
    }
   
    public static boolean isFanZhuanSuShu(int num){
        return isSuShu(num)&&isSuShu(reverse(num))&&!isHuiWen(num);
    }
    //回文功能
    public static boolean isHuiWen(int num){
        return reverse(num)==num;
    }
    //素数功能
    public static boolean isSuShu(int num){
        for(int i=2;i<=num/2;i++){
            if(num%i==0){
                return false;
            }
        }
        return true;
    }
    //反转功能
    public static int reverse(int num){
        int sum=0;
        while(true){
            sum=sum*10+num%10;
            num/=10;
            if(num==0){
                return sum;
            }
        }
    }
}

Tower of Hanoi: Recursive

/*
 前两个 x->y
 	前一个 x->z
 	前两个 x->y
 	前一个z->y
 第三个x->z
 前两个y->z
 	前一个y->x
 	前二个y->z
 	前一个x->z
 
 */
public class Hannuo {
	public static void main (String[] args) {
		hannuo (3,"X","Y","Z"); 
	}
public static void hannuo (int n,String begin,String mid,String end) {
	if (n == 1) {
		System.out.println(begin + " -> " + end);
	}else {
		hannuo (n - 1,begin ,end ,mid);
			System.out.println(begin + " -> " +end);
			hannuo (n-1,mid,begin,end);
		
	}
}	
}

Which code is represented as follows:

import java.util.Scanner;

public class Day44 {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		//1.提示用户输入密码   (answer为密码)
		System.out.print("请输入您的密码");
		String answer = in.nextLine();
		//2.用户看到的结果  判断密码是否通过
		if (success(answer)) {
			System.out.println("验证通过");
		}else {
			System.out.println("验证失败");
		}
	}
	//3.密码组合起来是否成功
	public static boolean success (String s) {
		return zifu(s) && letternum (s) && num (s);
	}
	//4.至少八字符
	public static boolean zifu (String s) {
		return s.length() >= 8;
	}
	//5.仅字母和数字
	public static boolean letternum (String s) {
		char c = ' ';
		//对字符进行遍历
		for (int i = 0;i < s.length();i++) {
			c = s.charAt(i);//将查找出来的字符赋值给c
			if (!number(c) && !letter(c)) {
				return false;
			}
		}
		return true;
	}
	//6.至少两个数字
	public static boolean num (String s) {
		char c = ' ';
		int count = 0;
		for (int i = 0;i < s.length();i++) {
			c = s.charAt(i);
			if (number(c)) {
				count++;
			}
		}
		return count >= 2;
	}
	//7.是否是字母
	//'a'<= c <= z ||'A' <= c <='Z'
	public static boolean letter(char c) {
		return c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'; 
	}
	//8.是否是数字
	//'0'<= c <= '9'
	public static boolean number (char c) {
		return c >= '0' && c <= '9';
	}

}

Its code is:

public class Day48 {

	public static void main(String[] args) {
		String s = "abaaggkgkga";
		System.out.print(count(s,'a'));
	}
	  public static int count(String s,char c){
	        int count=0;
	        for(int i=0;i<s.length();i++){
	            if(s.charAt(i)==c){
	                count++;
	            }
	        }
	        return count;
	    }
	}

import java.util.Scanner;

public class Day49 {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.print("请输入一个字符串");
		String s = in.nextLine();
		System.out.print(reverse(s));
	}
	public static String reverse(String s){
		String res = "";
		for (int i = s.length() - 1;i >= 0;i--) {
			res += s.charAt(i);
		}
		return res;
	}

}

import java.util.Scanner;

public class Day410 {

	public static void main(String[] args) {
		Scanner in = new Scanner(System .in);
		System.out.print("请输入一个字符串");
		String s = in.nextLine();
		System.out.print(upper(s));
	}
	public static int upper (String s) {
		int count = 0;
		for (int i = 0;i < s.length();i++) {
			if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z') {
				count++;
			}
		}
		return count;
	}
	

}

4.11

import java.util.Scanner;

public class Day411 {

	public static void main(String[] args) {
		//提示用户输入两个字符串
		Scanner in = new Scanner(System.in);
		System.out.print("Enter the first string :");
		String s1 = in.nextLine();
		System.out.print("Enter the secong string :");
		String s2 = in.nextLine();
		System.out.println(com(s1,s2));

	}
	public static String com (String s1,String s2) {
		//将长的字符串赋值给maxstring 短的赋值给minstring
		String maxString = "";
		String minString = "";
		if (s1.length() <= s2.length()) {
			minString = s1;
			maxString = s2;
		}else {
			minString = s2;
			maxString = s1;
		}
		//遍历字符串,直到找到不相同的为止退出循环
		for (int i = 0;i < minString.length();i++) {
			if (s1.charAt(i) != s2.charAt(i)) {
				return minString .substring(0,i);
			}
		}
		//如果两个字串相等时
		return minString;
	}

}

class Day0412{
    public static void main(String[] args){
        String s="AB8C";
        System.out.println(hexToDeimal(s));
    }
    public static int hexToDeimal(String s){
        int num=0;
        char c=' ';
        for(int i=0;i<s.length();i++){
            c=s.charAt(s.length()-1-i);
           
            if(isLetter(c)){
                num+=(c-'A'+10)*Math.pow(16,i);
            }else{
                num+=(c-'0')*Math.pow(16,i);
            }
        }
        return num;
    }
    public static boolean isLetter(char c){
        return c>='A'&&c<='F';
    }
}

 

Published 11 original articles · won praise 0 · Views 254

Guess you like

Origin blog.csdn.net/yihjh/article/details/104259972
Recommended