Nesting of for loops
/*
(for loop)
"A hundred dollars for a hundred chickens" is a famous mathematical problem in ancient China. The title is described as follows: 3 articles
Money can buy a rooster, two Wen can buy a hen, and one Wen can buy three chicks. In 100 words
Money to buy 100 chickens, then how many cocks, hens and chicks are there?
Classic "exhaustive algorithm problem"
Analysis:
1) define the cock, hen and chick as X, y and Z respectively
2) use the for loop to enumerate 0,33 (3 words) for the rooster
Money can buy a rooster)
Get the number of cocks you can get
3) continue to enumerate hens, (2 Wen can buy a hen), for cycle 0,50
Obtain the number of hens that may be obtained
4)
The number of cocks and hens is determined,
z = 100 - x - y ;
5) current outer cycle - exhaustive for roosters
Inner circulation --- exhaustive for hens
z = 100 - x - y ;
Conditions that must be met:
100 Wen to buy roosters, hens and chicks
Condition 1 (3*x + 2*y + z/3 == 100)
At the same time, it is necessary to ensure that the chick can be divided by 3} z% 3 = = 0
Output the number of all roosters, hens and Chicks - the output is the list
*/
class ChickenTest{ public static void main(String[] args){ //Define rooster, hen and chick as X, y and Z respectively int z = 0 ; //Use the for loop to enumerate the rooster for(int x = 0 ; x <= 33 ; x ++){ //Continue to enumerate hens, (2 Wen can buy a hen), for cycle 0,50 for(int y = 0 ; y <=50 ; y ++){ //Number of chickens z = 100 - x - y ; //Conditions met //The number of 100 Wen chickens can be divided by 3 if((3*x+2*y+z/3 == 100) && (z % 3 == 0)){ System.out.println("The cock has:"+x+"only,Hens have:"+y+"only,Chicken has:"+z+"only") ; } } } } }
/*
Nesting of for loops
For (initialization statement 1; conditional expression 1; control body statement 1){
The loop body is a for loop
For (initialization statement 2; conditional expression 2; control body statement 2){
Circular style sentence 2
}
}
Requirements:
The * shape of 4 rows and 5 columns needs to be output on the console
*****
*****
*****
*****
*/
class ForForDemo{ public static void main(String[] args){ for(int x = 0 ; x <4; x++){//Number of outer control lines: 4 lines //Loop body: five columns* for(int y = 0; y <5 ; y ++){ //Number of inner control columns: 5* System.out.print("*") ; } System.out.println() ; } } }
/*
9 rows and 9 columns *, the number of columns is changing*
*
**
***
****
*****
******
*******
********
*********
Requirements: 99 multiplication table
1*1 = 1
1*2 = 2 2 * 2 = 4
1*3 = 3 2* 3 = 6 3....
...
...
...
*/
class ForForTest2{ public static void main(String[] args){ //9 rows and 9 columns *, the number of columns is changing* for(int x = 0 ; x <9; x++){ for(int y = 0 ; y <=x ; y++){ System.out.print("*") ; } System.out.println() ; } System.out.println("-------------------------------") ; //99 multiplication table: in order to ensure data, start from 1 for(int x = 1 ; x <= 9 ; x ++){//Number of rows //The number of columns is also changing for(int y = 1 ;y <=x ; y ++){ //Escape characters in Java // \X: X any character \ t -- "tab" System.out.print(y+"*"+x+"="+(y*x)+"\t" ) ; } System.out.println() ; } } }
/*
Please output five digits (10000 99999) that meet the following conditions on the console
One bit equals ten thousand bits
Ten is a thousand
One digit + ten digit + thousand digit + ten thousand digit = hundred digit
*/
class Test2{ public static void main(String[] args){ System.out.println("The five who meet the conditions are:") ; //Five digits, clear range for(int x = 10000; x <=99999; x ++){ //Determine the data itself on each bit int ge = x % 10 ; int shi = x /10 % 10; int bai = x /10 / 10 % 10 ; int qian = x/ 10/10/10 % 10; int wan = x /10/10/10/10 % 10 ; /* One bit equals ten thousand bits Ten is a thousand One digit + ten digit + thousand digit + ten thousand digit = hundred digit */ if((ge==wan) && (shi==qian) && ((ge+shi+qian+wan)==bai)){ System.out.println(x) ; } } } }
/*
The highest mountain in China is Mount Everest: 8848m,
I now have a large enough paper with a thickness of 0.01m.
How many times can I fold it to ensure that the thickness is not lower than the height of Mount Everest?
analysis:
0) define the statistical variable int count = 0;
1) initial thickness int start = 0.01; 1
Final thickness: int end = 8848; 884800
For ease of calculation, multiply by 100 and round
Ambiguous number of cycles
2) use while (start < end){
/ / statistical variables++
/ / initial folding thickness * = 2
start *=2 ;
/ / output, easy to see. For the count, what is its thickness start
}
3) output count times
*/
class WhileTest{ public static void main(String[] args){ //Defining statistical variables int count = 0 ; //Define starting thickness int start = 1 ; int end = 884800 ; //Meet the conditions while(start < end){ //count++ count ++ ; //The initial thickness is twice as thick as before start *=2 ; System.out.println("The first"+count+"second,The initial thickness is"+start) ; } System.out.println("Need to fold"+count+"second") ; } }
Jump control statement
/*
Jump control statement:
break
continue
return
break; Interrupt, end
break
Application scenario:
1) it cannot be used alone and an error is reported
2) can only be used in two scenarios
The switch statement comes with the break keyword
Loop structure statement
for/while loops can be used
In the early days of break, it was used in the nesting of for loops, using "label statements"
break tag name; Ends the specified cycle
Label name: outer loop / inner loop
wc:for(xxx;xx;xx){
nc:for(xx;xx;xx){
}
}
*/
class BreakDemo{ public static void main(String[] args){ //break ;// Interrupt outside switch or loop //Write for loop for(int x = 0 ; x <10 ; x ++){ if(x == 3){ break ;//End, interrupt } System.out.println(x) ;//0,1,2 } System.out.println("--------------------------") ; //Add tag name early (understand) wc:for(int x = 0 ; x < 4 ; x ++){//Number of rows nc:for(int y = 0 ; y < 5 ; y ++){//Number of columns /* if(x == 2){ break wc ; //The outer cycle is over } */ if(y == 2){ break nc ; } System.out.print("*") ; } System.out.println() ; } } }
/*
Continue: it belongs to one of jump control statements
Generally used in circular statements;
Indicates the end of the current cycle and immediately enters the next cycle
break: end interrupt
Interview question: the test site is break/continue
Look at the program, write the results and complete the code
for(int i =1 ; i <=10 ; i ++){
if(i % 3 == 0 ){
/ / complete the code here
}
System.out.println("I love Gao Yuanyuan");
}
1) you need to output "I love Gao Yuanyuan" break twice on the console;
2) you need to output "I love Gao Yuanyuan" continue 7 times on the console
3) you need to output "I love Gao Yuanyuan" 13 times on the console
System.out.println("I love Gao Yuanyuan");
*/
class ContinueDemo{ public static void main(String[] args){ //for loop for(int x =1 ; x <= 10 ; x ++){ //Join condition if(x ==3 ){ //break ; // end continue ;//End the current cycle and immediately enter the next cycle } System.out.println(x) ;// break ;1,2 //contine: 1,2,4,5,6,7,8,9,10 } } }
/*
return: returns the result (the end method is used, but rarely used alone)
General: return will not be used alone (rarely alone)
It is used in combination with methods with specific return value types in Java
In actual development,
As long as you see the return keyword, you must use it when there is a specific return value type in the current method!
*/
class ReturnDemo{ public static void main(String[] args){ System.out.println("The program begins...") ; for(int x = 1 ; x <= 10 ; x ++){ if(x == 3){ System.out.println("The conditions are established,get into if Yes") ; //break ;// When x=3, it is true, the interrupt cycle is over //continue ;// When x=3, it holds and immediately enters the next cycle return ; //The end method is rarely used alone; } System.out.println(x) ; } System.out.println("The program is over,over...") ; } }
method
Methods with specific return value types
/*
What is the method,
In Java,
The method is to wrap some business code with {} code block and name it "method name"
The method name, which needs to see the meaning of the name, meets the "identifier rules",
Later, we can call our own business method directly in main.
In Java, how to define a method with a specific return value type
Format: fixed writing
Definition method
Permission modifier static.. return value type method name (parameter type 1, variable name 1, parameter type 2, variable name 2.....) {
Complete the business logic of your code: complete the operation according to the requirements
return result;
}
Detailed explanation:
Permission modifier: now use public fixedly: the access permission is large enough
Now write method: you must bring static. The previous writing method: public static
Return value type: data type -- basic data type is studied
Method name: name the {} code block, see the meaning of the name, follow the "identifier rule" and the small hump naming method
add(), sum
sum(), sum
Parameter list:
Parameter type: data type. Now the basic data type is used
Variable name -----: name the current formal parameter, see the meaning of name, "small hump naming method"
return result: according to your business method,
What type is the return value type, and the specific results will be returned to you
Call method:
1) output call: not recommended
2) assignment call: Recommended
3) separate call: not available
Requirements:
Find the sum of two data (no prompt for data type, both int)
*/
class FunctionDemo{ public static void main(String[] args){ /* int a = 10 ; int b = 20 ; System.out.println(a+b) ; */ //Enter or directly give the specific value: actual parameter int a = 10 ; int b = 20 ; //Call method //Single call: No, it's calculated - but there's no result //add(a,b) ; //Output call: not recommended: hard coded //---Output the results directly. You may want to continue other requirements through the obtained results, which is useless //System.out.println("the sum of the two data is:" + add (a, b))// a=10,b=20 //Method calls with specific return value types - assignment calls are recommended //Assignment call: Recommended int result = add(a,b) ; System.out.println("The result of the two data is:"+result) ; } /* Formal parameters Permission modifier static.. return value type method name (parameter type 1, variable name 1, parameter type 2, variable name 2.....) { Complete the business logic of your code: complete the operation according to the requirements return result; } Define a function (method) to sum two data There must be two clear in mind 1)Specify the return value type - data type: now the basic data type is used int 2)Specify the parameter type and the number of parameters 2 Two parameters, all int */ public static int add(int x,int y ){//10,20: the actual parameter assigns the result to the formal parameter x,y //Assignment operation int result = x + y ; return result ;//Specific business results //return x+y ; } }
/*
Precautions for defining methods with specific return value types:
1) methods and methods are level relations and cannot be nested. They can only be called inside
2) when defining a method, two explicit methods are required
a) specify the return value type
b) specify the parameter type and the number of parameters (formal parameter type and several parameters)
3) when defining methods, formal parameters must carry data types because Java
Is a strongly typed language!
4) in actual parameter main, when the method is invoked, the actual parameters do not need to carry data type because
It has been entered and defined
5) for actual parameters and formal parameters, the data types need to correspond one by one when transferring parameters!
*/
class FunctionDemo2{ public static void main(String[] args){ //Define the summation method: two data summations /*public static int add(int a,int b){//Illegal expression start (method nesting: error)) int c = a + b ; return c ; } */ //Later keyboard entry int a = 10 ; int b = 20 ; //Assignment call //int result = add(int a,int b) ; // Cannot carry data type in int result = add( a, b) ; System.out.println("result:"+result) ; } //Method and method level relationship //Define the summation method: two data summations /* Two clear 1)Explicit return value type: int 2)Specify the parameter type and parameter format int Type, 2 Parameters */ public static int add(int a,int b){ //Form parameters do not affect //public static int add (a, b) / / no, not Java language, very strict syntax structure and format! int c = a + b ; return c ; } }
/*
No hint, int type
1) enter two data on the keyboard and compare whether the two data are equal, using the method with specific return value type
2) enter two data on the keyboard and obtain the larger value of the two data, which is completed by using the method with specific return value type
Today's focus
Master
The use of for loop nesting -- the classical algorithm title "exhaustive method"
The difference between break/continue:
What are methods and method definitions and calls with specific return value types (emphasis)
Two clear in mind
1) specify the return value type
2) specify the type and number of parameters
*/
//Guide Package import java.util.Scanner ; class FunctionTest{ public static void main(String[] args){ //Create keyboard entry object Scanner sc = new Scanner(System.in) ; //Prompt and enter data System.out.println("Please enter the first data:") ; int a = sc.nextInt() ; System.out.println("Please enter the second data:") ; int b = sc.nextInt() ; //Call method //Are the two data equal boolean result = compare(a,b) ; System.out.println("result:"+result) ; System.out.println("-------------------------------") ; //Prompt and enter data System.out.println("Please enter a data:") ; int m = sc.nextInt() ; System.out.println("Please input data one by one:") ; int n = sc.nextInt() ; //Call method int max = getMax(m,n) ; System.out.println("The maximum of the two data is:"+max) ; } /* Define a function: compare whether two data are equal Define two clear methods 1)Explicit return value type boolean 2)Specify the parameter type and the number of parameters int Type, two parameters Permission modifier static return value type method name (form type 1 variable name 1,...) { //Business logic return result; } */ public static boolean compare(int a , int b){ //Formal parameters to complete the business logic of the method //three yuan //boolean flag = (a==b)? true :false ; //optimization boolean flag = a==b ; return flag ; } /* Enter two data with the keyboard to obtain the larger value of the two data */ /* Define this method //Two clear 1)Explicit return value type int 2)Specify the parameter type and the number of parameters int 2 Parameters */ public static int getMax(int a,int b){ int max =0; //Result variable if(a != b){ //Nested judgment if(a > b){ max = a ; }else{ max = b ; } }else{ System.out.println("The two data are consistent") ; max = a ; } return max ; } }