Java zero Foundation Series tutorial 01 variables, types, operators, expressions

Supporting video tutorials

This article is a video tutorial for station B

constant

(1) The amount whose value does not change during program execution
(2) Literal constant
A: String constant "hello"
B: Integer constants 12,23
C: Decimal constant 12.345
D: Character constants' a','A','0 '
E: Boolean constant true,false
F: Null constant null (later)

/*
    Constant:
        The amount whose value does not change during program execution.
        
    Classification:
        A:literal constant 
        B:Custom constants (later)
        
    literal constant 
        A:The contents of a string constant enclosed in double quotes.
            Examples: "hello","world","HelloWorld"
        B:Integer constant all integers
            Example: 100200
        C:Decimal constant all decimals
            Example: 10.23110.11
        D:The content of a character constant enclosed in single quotes
            Example: 'a','A','0'
            Wrong: 'ab'
        E:Boolean constants are special
            Example: true,false
        F:Empty constants are described later
            Example: null
*/
class ConstantDemo {
    public static void main(String[] args) {
        //Output of string constants
        System.out.println("hello");
        
        //Output of integer constant
        System.out.println(100);
        
        //Output of decimal constant
        System.out.println(100.10);
        
        //Output of character constants
        System.out.println('a');
        System.out.println('A');
        System.out.println('0');
        //This is problematic. Character constants have single quotation marks and string constants use double quotation marks
        //System.out.println('ab');
        
        //Output of Boolean constant
        System.out.println(true);
        System.out.println(false);
    }
}

Three elements of variables

Type, variable name, saved value

Basic data type

  1. numerical value
  • Integer byte, short, int, long
    25,-987, 0
  • Decimal float,double
    5.23,3.14
  1. character string
  • String string
    "Hello", "capital of China"
  • Character char
    'a', '
  1. Boolean type
    boolean

To use a variable

  1. Define a variable
    Data type variable name;
    int money;

2. Assign values to variables
Variable name = value;
money = 1000 ;

The first and second steps can be combined
Data type variable name = value;
int money = 1000;

3. Use this variable
System.out.println(money );

    int age;//Define a variable
    age = 34; //Assign values to variables
    System.out.println(age); //Output the value of the variable on the screen
    
    String name="zhangsan";//Define a variable and assign a value to it immediately
    System.out.println(name); //Output the value of the variable on the screen

Define several variables

The brand of the mobile phone is Huawei, with a price of 2500 and a weight of 0.125kg,
Color red

String brand = "Huawei";
int price = 2500;
double weight = 0.125;
char color = 'red';

   System.out.println("Mobile phone brand:" + brand);
  System.out.println("Mobile phone price:" + price);

Get user input

Using the Scanner class

Scanner sc = new Scanner(System.in);

/*
 * Scanner:Used to receive keyboard input data.
 * 
 * In front:
 *         A:Guide Package
 *         B:create object
 *         C:Call method
 * 
 */
import java.util.Scanner;

public class ScannerDemo {
    public static void main(String[] args) {
        // create object
        Scanner sc = new Scanner(System.in);

        int x = sc.nextInt();
        
        System.out.println("x:" + x);
    }
}
        Scanner scanner = new Scanner(System.in);//Define a variable scanner that gets input information from the screen

        System.out.println("Please enter your age");
        int age = scanner.nextInt();//Getting an integer entered by the user from the screen has a blocking side effect. Generally speaking, the program card is here

        System.out.println("What is your age" + age);
        System.out.println("Please enter your name");
        String name = scanner.next();//Getting a string entered by the user from the screen has a blocking side effect. Generally speaking, the program card is here

        System.out.println("Welcome" + name);

hasNextInt() and nextInt() methods of Scanner class

import java.util.Scanner;

/*
 * Basic format:
 *         public boolean hasNextXxx():Determine whether it is a certain type of element
 *         public Xxx nextXxx():Get the element
 * 
 * Example: use the method of int type
 *         public boolean hasNextInt()
 *         public int nextInt()
 * 
 * be careful:
 *         InputMismatchException: The input does not match what you want
 */
public class ScannerDemo {
    public static void main(String[] args) {
        // create object
        Scanner sc = new Scanner(System.in);

        // get data
        if (sc.hasNextInt()) {
            int x = sc.nextInt();
            System.out.println("x:" + x);
        } else {
            System.out.println("The data you entered is incorrect");
        }
    }
}

Newline problem caused by nextLine() in Scanner class

import java.util.Scanner;

/*
 * Two common methods:
 *         public int nextInt():Gets a value of type int
 *         public String nextLine():Get a value of type String
 * 
 * Something went wrong:
 *         Get a value first. There will be a problem when getting a string.

 * How to solve it?
 *         A:After obtaining a value, create a new keyboard entry object to obtain the string.
 *         B:Get all the data according to the string first, and then what you want, you will convert it accordingly.
 */
public class ScannerDemo {
    public static void main(String[] args) {
        // create object
        Scanner sc = new Scanner(System.in);

        // Gets two values of type int
        // int a = sc.nextInt();
        // int b = sc.nextInt();
        // System.out.println("a:" + a + ",b:" + b);
        // System.out.println("-------------------");

        // Gets two values of type String
        // String s1 = sc.nextLine();
        // String s2 = sc.nextLine();
        // System.out.println("s1:" + s1 + ",s2:" + s2);
        // System.out.println("-------------------");

        // First get a string, and then get an int value
        // String s1 = sc.nextLine();
        // int b = sc.nextInt();
        // System.out.println("s1:" + s1 + ",b:" + b);
        // System.out.println("-------------------");

        // Get an int value first. When you get a string, there will be a problem
        // int a = sc.nextInt();
        // String s2 = sc.nextLine();
        // System.out.println("a:" + a + ",s2:" + s2);
        // System.out.println("-------------------");

        int a = sc.nextInt();
        Scanner sc2 = new Scanner(System.in);
        String s = sc2.nextLine();
        System.out.println("a:" + a + ",s:" + s);
    }
}

operator

  1. Assignment Operators
    =

Member Wang Hao's Java score is 80 points. Student Zhang Meng's Java score is the same as that of Wang Hao. Output Zhang Meng's score

int wangScore = 80;    //Wang Hao's achievements
int zhangScore;        //Zhang Meng's achievements
zhangScore = wangScore; 
System.out.println("Zhang Meng's score is" +zhangScore);

2. Arithmetic operator
+,-,*,/,%

        System.out.println(1600%5);//0-4
        System.out.println(3%5);//3
        System.out.println(3%2);//1
        System.out.println(21%5);//1
        System.out.println(13%4);//1
//        System.out.println(m%n);//0----n-1
        System.out.println(23%7);//2
        System.out.println(25%7);//4

One question

The user enters a number of days on the screen, and the program answers how many weeks and days?

   //  The user enters a number of days on the screen, and the program answers how many weeks and days?
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter the number of days");
        //Get the number of days dayCount entered by the user
        int dayCount = scanner.nextInt();
        System.out.println(dayCount+"God is"+ dayCount/7 + "Zhou Ling" +  dayCount%7 + "day");

Relational operator

Compare height, size, length, etc
Is Zhang San's test score higher than Li Si
Do elephants live longer than turtles
Is basketball as big as the earth

,<
==,!=
=,<=
boolean type
Value of boolean type:
True: true
False: false

What is the result of the expression (3 + 40% 6) > (9 / 2 * 3)?

false

Input Zhang San's score from the console and compare it with Li Si's score (80 points), and output "is Zhang San's score higher than Li Si's score?" Judgment result of

int liSi = 80;          //Student Li Si's achievements
boolean isBig ;    
        
Scanner input = new Scanner(System.in);   
System.out.print("Enter student Zhang San's score: ");       
int zhangSan =  input.nextInt();                     //Enter Zhang San's grade 
        
isBig = zhangSan > liSi ; 
System.out.println( "Is Li San better than Zhang Si? "+isBig );    //Output comparison results

expression

y = x-9+(x +90);

practice

Shopping malls launch lucky draw
Lottery rules:
Customer's four digit membership card number
The sum of your numbers is greater than 20,
Lucky customers.

Type conversion

Automatic type conversion

The average score of the first Java test of a class is 81.29, and the second time is 2 points more than the first time. Calculate the average score of the second test?

double firstAvg = 81.29;  //First average score
  double secondAvg;         //Second average score
  int rise = 2;

  secondAvg = firstAvg + rise;
        
  System.out.println("The second average score is:"  + secondAvg);

Rule 1: if an operand is of double type, the entire expression can be promoted to double type

Rule 2: meet the conditions of automatic type conversion
The two types should be compatible:
Numeric types (integer and floating point) are compatible
Target type is greater than source type:
For example: double type is greater than int type

Cast type

(type name) expression

int  b  = (int)10.2;
double a = 10;
int c = (int)a;

Last year, the market share of Apple notebook was 20, and this year's increased market share was 9.8. What's the share this year?

int before = 20;     //apple notebook market share
double rise = 9.8;     //Share of growth

int now = before+ (int)rise;      //Current share

There is a loss of accuracy when casting

Tags: Java

Posted by icaro on Sat, 14 May 2022 08:18:04 +0300