[an ordinary day to learn java] java basic grammar 1 (with homework)

Posted by EOS on Mon, 03 Jan 2022 16:28:38 +0100

Part I HelloWorld

1. The name of the java file must be consistent with the name of the public class

2. A java file can contain multiple classes, but only one public class

3.public static void main(String[] args) is the entry point for all java programs

4. The parameter list in the main method supports multiple writing methods: String[] args, String[] args, String args []

5. The parameter name in the main method doesn't matter, but it is generally written as args

Part II identifier

Identifier naming conventions:

  • Mandatory provisions
    1. The identifier must start with a letter, underscore or dollar sign
    2. Other parts must be letters, numbers, underscores or dollar symbols, but special symbols cannot appear
    3. Identifier case sensitive
    4. It cannot be a java keyword or reserved word (a string reserved for the system to represent special meaning)

  • General recommendations
    Hump identification
    1. Class name and interface name shall be capitalized when naming
    2. Method, variable naming should be lowercase
    3. When multiple words are spliced to represent an identifier, each letter shall be capitalized
    See the name and know the meaning
    1. The meaning of the representative can be known through the name of the identifier
    2. Never write pinyin

Part III constants and variables

Within the class, variables defined outside the method are called member variables, and there will be default values
In the method, the defined variable must be initialized, and there will be no default value
Variables modified with the final keyword are called constants, indicating that they cannot be modified

public class ConstantAndVar{
	
	static int d;  //The default is 0
	public static void main(String[] args){
		int a; //If initialization is not performed, an error will be reported!
	}
}

Part IV data types

data type
java is a strongly typed language

Strongly typed: what declaration types must be displayed when variables are defined
Weak type: the variable will infer by itself according to the value, and there is no need to specify the type

java data type
Basic data types (4 types and 8 types) (different types represent different lengths)

Integer type: byte (range: - 128 - + 127), short (range: - 32768 - + 32767), int (plus or minus 2.1 billion), long (∞)

be careful:
1. When integer types are used, they are all int types by default
2. If you need to use long type, you must add L after the number. It is recommended to use uppercase. Lowercase is easy to be confused with "1"

Floating point type: float (single precision), double (double precision)

Note: 1 The default floating point type is double
2. When using float, add f after the number
3. Floating point type cannot represent an exact value, which will lose precision

Character type: char

boolean type: boolean (there are only two values: true and false, accounting for 1 bit during storage)

Reference data type:
class
Interface
array

public class DataTypeDemo{
	public static void main(String[] args){
		char a = 'A';  //Represents a character
		String a = "A";  //Represents a string
	}
}

Part V branch structure

Branching structure

Single branch structure: only make a single conditional judgment. If yes, do something. Double branch structure: when making a conditional judgment, there are only two choices
Multi branch structure: multiple conditions can be judged, and different nested branch structures can be selected for each matching item: nested branch structures in branch structures
switch branch structure: generally used for equivalence judgment

be careful:
1. Add break in each case module to prevent multiple matches
2. If the functions of logical code blocks processed in multiple case s are consistent, it can be considered to add processing only once at the end
3.default indicates the default option. This option will be executed when all case conditions do not match
4.default can have or not

Basic knowledge of scanner input:

import java.util.Scanner;

public class Demo {
    public static  void main(String[] args){
		//Scanner
		//Create a file scanner object, system In represents standard input, and data can be read from the console (decorator mode)
        Scanner sc = new Scanner(System.in);
		System.out.println("Please enter data");
        String str = sc.nextLine();
        System.out.println(str);
    }
}

Example of switch branch

public class Demo {
    public static  void main(String[] args){
        int random = (int)(Math.random()*26);
        char ch = (char)('a'+random);
        switch(ch){
            case 'a':
                System.out.println("vowel"+ch);
                break;
            case 'e':
                System.out.println("vowel"+ch);
                break;
            case 'i':
                System.out.println("vowel"+ch);
                break;
            case 'o':
                System.out.println("vowel"+ch);
                break;
            case 'u':
                System.out.println("vowel"+ch);
                break;
            default:
                System.out.println("consonant"+ch);
                break;
        }
    }
}

Homework after class

1. Enter a number to judge whether it is odd or even

import java.util.Scanner;

public class Demo {
    public static  void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        if(num%2==0){
            System.out.println("ou");
        }
        else {
            System.out.println("ji");
        }
    }
}

2. Output the corresponding grade according to the score, and use if multi branch and switch statements to realize it respectively

public class TestGrade1 {
	public static void main(String[] args) {
		// Give a score
		Scanner  input  = new Scanner(System.in);
		System.out.println("Please enter a score");
		double score = input.nextDouble();
		// According to the score, give the grade
		String grade;
		if (score >= 90) {
			grade = "A";
		} else if (score >= 80) {
			grade = "B";
		} else if (score >= 70) {
			grade = "C";
		} else if (score >= 60) {
			grade = "D";
		} else {
			grade = "E";
		}
		// Output level
		System.out.println("score=" + score + ",grade=" + grade);
	}
}
public class TestGrade2 {
	public static void main(String[] args) {
		// Give a score
		Scanner  input  = new Scanner(System.in);
		System.out.println("Please enter a score");
		int score = input.nextInt();			
		//According to the score, give the grade
		String grade="E";
		switch(score/10){
			case 10:
			case 9:grade="A";break;
			case 8:grade="B";break;
			case 7:grade="C";break;
			case 6:grade="D";break;
			default :grade="E";				
		}
		//Output level
		System.out.println("score="+score+",grade="+grade);
	}
}

3. Output the corresponding season according to the month, and output at least two idioms and activities describing the season.

public class TestSeason {
	public static void main(String[] args) {
		// Enter month
		Scanner  input  = new Scanner(System.in);
		System.out.println("Please enter month:");
		int month = input.nextInt();
		//Output season according to month
		switch(month){
			case 1:
			case 2:
			case 3: System.out.println("spring-Flowers bloom in spring-Tree planting outing");break;
			case 4:
			case 5:
			case 6: System.out.println("summer-Summer is hot and rainy-Swimming and eating ice cream");break;
			case 7:
			case 8:
			case 9: System.out.println("autumn-Autumn is clear and crisp, autumn wind and fallen leaves- Autumn harvest send autumn eyes ");break;
			case 10:
			case 11:
			case 12: System.out.println("winter-It's snowy in the cold winter -Skiing and skating");break;
			default: System.out.println("Your input is incorrect");
		}
	}
}

4. Judge whether a number is prime.

public class TestPrime {
	public static void main(String[] args) {
		// Enter a number
		Scanner input = new Scanner(System.in);
		System.out.println("Please enter a number:");
		int n = input.nextInt();
		// Judge whether it is prime
		boolean flag = true;
		if (n == 1)
			flag = false;
		else {
			for (int i = 2; i < n; i++) {
				if (n % i== 0) {
					flag = false;
					break;
				}
			}
		}
		// Output results
		if (flag) {
			System.out.println(n + "It's a prime");
		} else {
			System.out.println(n + "Not prime");
		}
	}
}

5. Input the scores of 5 students in a class from the keyboard, sum and output.

public class TestSum {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		//Enter the total score and sum
		double sum = 0;
		for (int i = 0; i < 5; i++) {
			System.out.println("Please enter page"+(i+1)+"A student's grade");			
			double  d = input.nextDouble();
			sum += d;
		}
		//Total output score
		System.out.println("The total score is"+sum);
	}
}

Topics: Java Back-end