Source: http://www.imooc.com/code/1634
For the small partners, please add the code in the Code editor, based on the knowledge you have learned, and refer to the comments. Write a Java program that allows you to output the maximum age of a student
Requirements:
1, required by the definition of the return value of the method to achieve, the return value is the maximum age
2, method will? The age of the student is kept in the array ages, and the array elements are sequentially, at
Operating effect:
Task
First, the definition of a non-parametric return value of the method to achieve the maximum output of the student age
Tips: 1. Define an array of ages, save the student's age, the array elements are 18, 23, 21, 19, 25, 29, 17 2, define a shaping variable max, save the student's maximum age, initially assume that the first element in the array is the maximum value 3, use the For loop Iterates over the elements in the array and compares them to the assumed maximum value, replacing the current maximum value of 4, using return to return the maximum value, if it is larger than the assumed maximum value
Second, complete the main method
Tips: 1, call the custom method, save the method return value in the variable maxscore 2, output variable result
1 Public classHelloWorld {2 3 //complete the Main method4 Public Static voidMain (string[] args) {5 6 //Create object, object named Hello7HelloWorld Hello =NewHelloWorld ();8 9 //calling a method and saving the return value in a variableTen intMaxscore =hello.getmaxage (); One A //Maximum output Age -System.out.println ("Max Age:" +Maxscore); - } the - /* - * Function: Output The maximum age of the student - * Defines an argument-free method that returns a value of the maximum age + * Reference steps: - * 1, define an array of ages, save the student's age, the array elements in order to be, at a total of + * 2, define a shaping variable max, save the student's maximum age, initially assuming that the first element in the array is the maximum value A * 3, use the For loop to iterate through the elements in the array, and compare with the assumed maximum value, if larger than the assumed maximum, replace the current maximum value at * 4, return the maximum value with return - */ - Public intGetmaxage () { - int[] ages= {18, 23, 21, 19, 25, 29, 17}; - intMax; - inmax = Ages[0]; - for(inti:ages) { to if(I >max) { +Max =i; - } the } * returnMax; $ }Panax Notoginseng}
Mu class net-java first season-7-4 programming exercises