List of articles

  • Java Basic grammar ( Four )—— Program logic control
  • One 、 Sequential structure
    • 1. What is sequence structure ?
    • 2. The order of structure examples
  • Two 、 Selection structure
  • 1. if sentence
  • (1) Basic writing format
  • (2) practice
    • Exercise one
    • Exercise 2
    • Practice three
  • (3) matters needing attention
    • 1. Overhang else problem
    • 2. Code style problem
    • 3. Semicolon problem
  • 2. switch .. case sentence
    • (1) Basic grammar
    • (2) Code example
    • (3) matters needing attention
  • 3、 … and 、 Loop structure
  • Keywords in the loop
  • 1.while Loop statement
  • (1) Basic grammar
  • (2) practice
    • Exercise one
    • Exercise 2
  • (3) matters needing attention
  • 2.for Loop statement
  • (1) Basic grammar
  • (2) practice
    • Exercise one
    • Exercise 2
  • 3.do … while Loop statement
  • (1) Basic grammar
  • (2) practice
  • (3) matters needing attention
  • Four 、 Representation of input and output
  • 1. Output to console
    • (1) Basic grammar
    • (2) Be careful
    • (3) Format output
  • 2. Input from keyboard
    • (1) Use Scanner Read string / Integers / Floating point numbers
    • (2) Use Scanner Cyclic reading N A digital
    • (3)Java Input suggestions
  • 5、 … and 、 Guess the realization of the number game
    • 1. Writing process
    • (1) Generate random number
    • (2) Enter the number you want to guess
    • (3) Loop structure , Compare numbers
    • 2. Complete code implementation
  • End !

Next chapter Java Basic grammar ( 3、 … and )—— Operator

Java Basic grammar ( Four )—— Program logic control

This introduction outlines :

 Insert picture description here

One 、 Sequential structure

1. What is sequence structure ?

The program is executed line by line according to the writing order of our code , If you change the writing order of the code , The execution order also changes

2. The order of structure examples

Now I’ll give two examples of code , Take you to understand the specific use of sequence structure

Code 1

 Insert picture description here

Compile to achieve the effect

 Insert picture description here
As we thought , The order structure follows the order in which we write our code , Execute the code line by line . Print out I like Beijng

If we change the order of printing , How to implement the code execution under the sequential structure ?

Code 2

 Insert picture description here

Compile to achieve the effect

 Insert picture description here

When we change the order of the code , So the execution is structured in order , The printed content will change with it .

Two 、 Selection structure

1. if sentence

(1) Basic writing format

Writing format one

 Insert picture description here

Writing format two

 Insert picture description here

Writing format three —- In the case of multiple branches

 Insert picture description here
There are three writing norms here , On behalf of if There are many situations of statement . We can make our own choice according to the actual situation .

Okay , Next, we’ll do a few exercises of selecting sentences, programming questions .

(2) practice

Exercise one

Subject requirements :

Judge odd even number

Code implementation :

public class Main {// Judge odd even number public static void main(String[] args) {int num = 10;if (num % 2 == 0) { System.out.println("num  It's even ");} else { System.out.println("num  Is odd ");}}}

The effect of compiler implementation :

 Insert picture description here

We used if …else Statement to distinguish between odd numbers 、 even numbers , So as to judge the parity of the number .

Exercise 2

Subject requirements :

Determine whether a number is positive or negative

Code implementation :

  public static void main(String[] args) {int num = 10;if (num > 0) {  System.out.println("num  Positive number ");} else if (num < 0) {  System.out.println("num  It's a negative number ");} else {  System.out.println("num  yes  0");}}

Compiler effect implementation :

 Insert picture description here

Here we use the usage of multiple choice statements , When making three choices , use if…else if…else Program structure control , Achieve what we want to achieve .

Practice three

Subject requirements :

Determine whether a year is a leap year

Code implementation :

    public static void main(String[] args) {int year = 2000;if (year % 100 == 0) {//  Determine the leap year of the century if (year % 400 == 0) {System.out.println(" It's a leap year ");} else {System.out.println(" It's not a leap year ");}} else {//  Common leap year if (year % 4 == 0) {System.out.println(" It's a leap year ");}}}

Compile to achieve the effect :

 Insert picture description here
We are in this exercise , Used if Nesting of statements , So as to achieve our topic requirements more conveniently .

(3) matters needing attention

1. Overhang else problem

int x = 10;int y = 10;if (x == 10) 
   if (y == 10)
   System.out.println("aaa");else
 System.out.println("bbb");

if It can be followed without braces , But only one statement following it can be executed , In this code , We see it visually else And the first if Match , however Without parentheses ,else And the only Current if Match .

also , In order to avoid my own mistakes in judgment , Try to add braces to all statements that need to be bracketed ( Don’t omit ).

2. Code style problem

//  style 1  int x = 10;  if (x == 10) {  //  Meet the conditions   } else {  //  Not meeting the conditions   }//  style 2  int x = 10;  if (x == 10) {  //  Meet the conditions   }  else  {  //  Not meeting the conditions   }

stay Java Although both code styles are legal , however Java It’s better to recommend style 1

{ Put it in if / else The same line .

3. Semicolon problem

      int x = 20;  if (x == 10); {  System.out.println("hehe");  }
   //  Running results hehe

We can see in the if() And then I accidentally added ;, Here’s one more A semicolon , The semicolon becomes if The body of a statement , and { } The code in has become and a if Unrelated code blocks .

We should try our best to avoid such mistakes .

2. switch … case sentence

(1) Basic grammar

 Insert picture description here

(2) Code example

int day = 1;switch(day) {case 1:System.out.println(" Monday ");break;case 2:System.out.println(" Tuesday ");break;case 3:System.out.println(" Wednesday ");break;case 4:System.out.println(" Thursday ");break;case 5:System.out.println(" Friday ");break;case 6:System.out.println(" Saturday ");break;case 7:System.out.println(" Sunday ");break;default:System.out.println(" Incorrect input ");break; }

according to switch The difference in the median , Will perform the corresponding case sentence . encounter break It will be the end of the case sentence .

If switch The values in do not match case, Will execute default The statement in .

Code implementation effect :

 Insert picture description here

We suggest a switch It’s better to bring all the sentences with you default. And default The position of is not fixed .

(3) matters needing attention

matters needing attention 1

break Don’t leave out , Or you’ll lose “ Multi branch selection ” The effect of

Code example :

public static void main(String[] args) {int day = 1;switch(day) {case 1:System.out.println(" Monday ");case 2:System.out.println(" Tuesday ");case 3:System.out.println(" Wednesday ");case 4:System.out.println(" Thursday ");case 5:System.out.println(" Friday ");case 6:System.out.println(" Saturday ");case 7:System.out.println(" Sunday ");default:System.out.println(" Incorrect input "); }}

Realization effect :

 Insert picture description here

matters needing attention 2

switch The value in can only be Integers | enumeration | character | character string

Our code example before switch() The middle heel is full of int Data of type

that switch() Can values in be of other types ?

We’re experimenting with other types of data …

long

 Insert picture description here
therefore switch () The data in cannot be long type

float

 Insert picture description here
therefore switch () The data in cannot be float type

double

 Insert picture description here
therefore switch () The data in cannot be double type

char

 Insert picture description here
 Insert picture description here
switch() Middle can be char Data of type

String

 Insert picture description here

Code implementation effect :

 Insert picture description here

therefore switch() The data in can be String Type of .

All in all ,switch The value in can only be Integers | enumeration | character | character string .

matters needing attention 3

switch Can’t express complex conditions

If it’s code like this :

 Insert picture description here

This kind of topic condition , Obviously use if Sentence expression is more convenient , Use switch Statement cannot express .

3、 … and 、 Loop structure

Keywords in the loop

break

function : break Its function is to make the loop end earlier , Execute to break It will end the cycle , Jump straight out of the loop

coutinue

function : continue The function of is to skip this loop , Enter the next cycle immediately .

1.while Loop statement

(1) Basic grammar

 Insert picture description here
I understand while The grammatical structure of a sentence , So let’s make a comparison while Code practice of statement .

(2) practice

Exercise one

Subject requirements :

Print 1 – 10 The number of

Code implementation :

 Insert picture description here

Realization effect :

 Insert picture description here

Exercise 2

Subject requirements :

Calculation 1 – 100 And

Code implementation :

 Insert picture description here
Realization effect :

 Insert picture description here

(3) matters needing attention

1. and if similar , while The following statement may not be written { } , But only one statement can be supported when not writing . The suggestion is to add { }

2. and if similar , while hinder { Recommendations and while On the same line .

3. and if similar , while Don’t write more in the back A semicolon , Otherwise, the loop may not execute correctly .

2.for Loop statement

(1) Basic grammar

 Insert picture description here

Compared with while loop , for The loop combines these three parts , It’s not easy to leave out when writing code .

I understand for The grammatical structure of a sentence , So let’s make a comparison while Code practice of statement .

(2) practice

We’ll take the top two while Change the circular exercise to for Loop to express

Exercise one

Subject requirements :

Print 1 – 10 The number of

Code implementation :

 Insert picture description here

Realization effect :

 Insert picture description here

Exercise 2

Subject requirements :

Calculation 1 – 100 And

Code implementation :

 Insert picture description here

Realization effect :

 Insert picture description here

3.do … while Loop statement

(1) Basic grammar

 Insert picture description here

(2) practice

Print 1 -10 The number of

 Insert picture description here
Realization effect :

 Insert picture description here

(3) matters needing attention

  1. do while Don’t forget the semicolon at the end of the loop
  1. commonly do while Rarely use , More recommended for and while.

Four 、 Representation of input and output

1. Output to console

(1) Basic grammar

System.out.println(msg); Output a string , With a new line

System.out.print(msg); Output a string , Without a line break

System.out.printf(format, msg); Format output

(2) Be careful

println The output comes with \n, print No \n

printf Format output mode and C Linguistic printf It’s basically the same .

(3) Format output

What is formatted output ?

Sort the data into the following types ( part ) For the output :

Conversion character type give an example
d Decimal integer ( “%d” ,10)
x Hexadecimal integer (“%x”, 100)
f Single-precision floating-point (“%f”,100.0)
s character string (“%s”,“abc”)
c character (“%c”,‘1’)

We’re just listing some of the formatted data , Please find the specific format type by yourself . This format is printed in C It’s very common in language .

2. Input from keyboard

(1) Use Scanner Read string / Integers / Floating point numbers

First we need to import util package

import java.util.Scanner; //  Import required  util  package 

Enter a shape from the keyboard

public static void main(String[] args) {//  Enter an integer Scanner scanner = new Scanner(System.in);int a=scanner.nextInt();//  Enter a number and print a number System.out.println(a);}

Realization effect :

 Insert picture description here
there nextInt It’s reading a plastic .
 Insert picture description here

Enter a string from the keyboard

public static void main(String[] args) {//  Enter a string Scanner scanner = new Scanner(System.in);String a=scanner.nextLine();//  Enter a string, print a string System.out.println(a);}

Realization effect :

 Insert picture description here
there nextline —— It’s typing a line , And it will not stop reading if it encounters a space
 Insert picture description here

Enter a floating-point number from the keyboard

public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);double a = scanner.nextDouble();System.out.println(a);}

Realization effect :

 Insert picture description here
there nextDouble Is to enter a double precision floating point number .

 Insert picture description here

(2) Use Scanner Cyclic reading N A digital

Code implementation :

import java.util.Scanner; public class Main {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);while(scanner.hasNextInt()){int a = scanner.nextInt();System.out.println(a);}}

Realization effect :

 Insert picture description here

We implement multiple sets of input numbers , Last ctrl + D Stop the cycle .

Here is hasNext Specific use of

 Insert picture description here

(3)Java Input suggestions

We use personal information , The input and output are as follows

 Insert picture description here

The type of input in turn is character string plastic floating-point

The display effect is as follows :

 Insert picture description here
good , We change the order of the input types for the second time .

 Insert picture description here
This time we encountered a problem in the input …

 Insert picture description here

We’re inputting plastic data 18 in the future , Press enter , I found that I jumped directly to the content of the input floating-point data , The string type just skips , There’s a problem with this input .

We can act as After input shaping My carriage return Take it for granted. Enter the contents of the string type , So the input string is skipped .

therefore about Java We suggest that : Put the input string first , Don’t enter plastic or other types of data before the string .

5、 … and 、 Guess the realization of the number game

The rules of the game :

The system automatically generates a random integer (1-100), Then the user enters a guess number . If the number entered is smaller than the random number , Tips “ low 了 ”, If the number entered is larger than the random number , Tips “ High ” , If the number entered is equal to the random number , Prompt “ Guessed it ”

1. Writing process

Here is Random Use .
 Insert picture description here

 Insert picture description here
 Insert picture description here

Okay , We are familiar with Random Use , In this game, we first need to generate a stay 0-100 Random numbers in the range

(1) Generate random number

 Randnum randNum = new Random();
 int randNum = Randdom.nextInt(100);

(2) Enter the number you want to guess

    Scanner scanner = new Scanner(System.in); int num = scanner.nextInt();

(3) Loop structure , Compare numbers

Compare your guess with a random number , If the guess is small , Print “ You guess it’s small ”, Guess the , Print “ You guessed big ”, Guessed it , Print “ You guessed it ”, Then jump out of the loop . If you don’t guess right, it’s always better .

We use it while(true) To keep cycling , When num== randNum when break Out of the loop .

  Scanner scanner = new Scanner(System.in);
 while(true){System.out.print(" Please enter the number you want to guess :>");int num = scanner.nextInt();if(num<randNum){System.out.println(" You guess it's small ");}else if(num>randNum){System.out.println(" You guessed big ");}else{System.out.println(" You guessed it ");break;}
 }

2. Complete code implementation

import java.util.Random;import java.util.Scanner;public static void main13(String[] args) {Scanner scan=new Scanner(System.in);Random random = new Random();int randNum = random.nextInt(100);//System.out.println(randNum);while(true){System.out.println(" Please enter a number :");int num=scan.nextInt();if(num<randNum){System.out.println(" You guess it's small ");}else if(num==randNum){System.out.println(" You guessed it ");break;}else if(num>randNum){System.out.println(" You guessed big ");}}}

Realization effect :

 Insert picture description here

Okay ,Java Basics – The knowledge of program logic control is shared here , I hope you can practice more after watching it , Thank you for your appreciation !!!

my Java There are exercises in basic introductory training , You can pay attention to !

Java Basic introductory training blog entry

Thank you for your appreciation and attention !!!

End !