Java method (including calculator code)

method

What is the method

Java methods are collections of statements that together perform a function

  • Method is an ordered combination of steps to solve a class of problems
  • Method is contained in a class or object
  • Methods are created in the program and referenced elsewhere

Naming rules for methods

Initial small rear hump

Principles of design method

Atomicity: ensure that one method can only complete one function

In general, the main method requires brevity, so we need to use methods to simplify the operation in the main method

public static void main(String[] args) { //main method 
    int sum = add(4,5);     //Use this method
    int sum2= add(81,19);   //Use this method
    System.out.println(sum);
    System.out.println(sum2);
}


public static int  add(int a, int b){  //Method for creating add
//Modifier return value name v
    return a+b;
}

Definition and invocation

Format of method

For example, public static (modifier), void (return value) and main(){

}

 public static void main(String[] args) {
        int max = max(20,20);   //Use the following method:
        System.out.println(max); //Output which value is larger
    }

public static int max(int num1,int num2){ //Definition method
        int result = 0;    //Writing method body
        if (num1>num2){    
            result= num1;
        }else if (num1<num2){
            result = num2;
        }else{
            System.out.println("The results are equal");
        }
        return result; //If the return value is not empty, it must be returned
                    //return "can also be used to terminate the method" from beginning to end. "
}

Method overload

Method overloading is a function with the same function name but less formal parameters in a class

Rules for method overloading

Method names must be the same

The parameter list must be different (number, type or parameter arrangement order, etc.)

The return types of methods can be the same or different

It is not enough to overload a method simply because the return type is different

public static int  add(int a, int b){
//Modifier return value name
    return a+b;
}
public static int  add(int a, int b,int c){
    //Here, change the number of parameter lists to reach method overload ↑
    //Modifier return value name
    return a+b;
}

Command line parameter transfer

Sometimes you want to send a message to a program when it is running. You only need to give a warm command line parameter to the main() function

However, if you need to run the class file, the path should be the path of the package written from src

Variable parameters

When writing methods, if you are not sure that you need to add several parameters or need to be compatible with multiple parameters, you can use variable parameters (write benign substitution of N method overloads)

Service conditions:

Add an ellipsis (...) after the specified parameter type

At the same time, ensure that the ellipsis is added to the last parameter

recursion

Recursion means that method A calls method A, and I call myself

Recursion can transform some complex problems into relatively simple ones to solve. The code amount of the program is greatly reduced. The ability of recursion is to define an infinite set of objects with finite statements

Recursion consists of two parts:

Recursive header: when not to call its own method. If I don't have a head, I will fall into a dead circle.

Recursive body: when to call its own method

test

//Write a calculator, which is required to realize addition, subtraction, multiplication and division, and can receive new data cyclically, which is realized through user interaction
//Idea recommendation: write 4 methods of addition, subtraction, multiplication and division, use loop + switch to conduct user interaction, pass the two numbers to be operated, and output the results

package com.jiang.method;

import java.util.Scanner;

//Write a calculator, which is required to realize addition, subtraction, multiplication and division, and can receive new data cyclically, which is realized through user interaction
//Idea recommendation: write 4 methods of addition, subtraction, multiplication and division, use loop + switch to conduct user interaction, pass the two numbers to be operated, and output the results
public class TestDemo01 {
    public static void main(String[] args) {
        double a=0;
        double b=0;
        String c=null;
        String d="null";
        double result=0;
        System.out.println("Welcome to a vegetable chicken. I want to write a calculator, but I can only write a little calculator program");
        System.out.println("This calculator only supports four operations of two digits,therefore");


        for (int i = 0; i < 10; i++) {
            Scanner scanner1 = new Scanner(System.in);
            System.out.println("Please enter your first digit a");
            a = scanner1.nextDouble();

            Scanner scanner3 = new Scanner(System.in);
            System.out.println("Please enter the operator again(+,-,*,%)");
            c = scanner3.nextLine();

            Scanner scanner2 = new Scanner(System.in);
            System.out.println("Finally, please enter the second digit b");
            b = scanner2.nextDouble();

            switch (c){
                case "+":
                    result=plus(a,b);break;
                case "-":
                    result=subtract(a,b);break;
                case "*":
                    result=multiply(a,b);break;
                case "%":
                    result=divide(a,b);break;
                default:
                    System.out.println("Your input is wrong, please re-enter!");
            }   System.out.println("The result is::"+result);
            System.out.println("Do you still need to continue the operation(Yes, please enter('Y','y'),No, please enter('N','n'))");
            Scanner scanner4 = new Scanner(System.in);
            d = scanner4.nextLine();
            if (d.equals("y")||d.equals("Y")){
                System.out.println("Starting again...");
                continue; }
            else if (d.equals("n")||d.equals("N")){
                break ;//Here, if you want to receive a text class, remember to use equals!!!!!!!!!!
            }

            }

        }


    public static double plus(double a , double b){
        return a+b;
    }
    public static double subtract(double a , double b){
        return a-b;
    }
    public static double multiply(double a , double b){
        return a*b;
    }
    public static double divide(double a , double b){
        return a/b;
    }
}

Tags: Java jvm Algorithm

Posted by lucasmontan on Mon, 15 Aug 2022 02:35:28 +0930