201871010134-Summary of Zhou Yingjie's Second Week Study of Object-Oriented Programming (java)

project

content

Which course does this assignment belong to?

https://www.cnblogs.com/nwnu-daizh/

What are the requirements for this assignment?

https://www.cnblogs.com/nwnu-daizh/p/11475377.html

Target of homework learning

  1. Learn and master Java Application program structure;
  2. Learn and master the data types and variables of Java language;
  3. Learn to use Java operators to construct various expressions.
  4. Master the input and output technology of Java Application;
  5. Master Java process control technology (branch, loop);
  6. Master the usage of Math and String classes

 

 

 

 

 

 

 

 

 

 

 

Part I: Comparing the similarities and differences between Java and C basic grammar, summarize the theoretical knowledge of this week:

1.

1.1 identifier

It consists of letters, underscores, dollar symbols and numbers (the first letter cannot be a letter).

1.2 Keyword

class, public, try, catch, import... (For example, c is not the same.)

1.3 Interpretation

"/" is commented on in line;

Block annotations for "/* */";

"/** */" can be used to automatically generate comments for documents;

2. Data type

integer Floating point type char type Unicode and char types boolean type
Used to denote a value that has no decimal part. It is allowed to be negative. Used to denote parts with decimal numbers Originally used to represent a single character   Used to determine logical conditions

int) 4 bytes

short 2 bytes

long 8 bytes

Byte = 1 byte

float 4 bytes

double 8 bytes

(! It's infinite! Negative infinite! NaN)

 char   There are only two types: false, true

 

 

 

 

 

 

 

 

3. Variables

3.1 In Java, each variable belongs to a type. When declaring a variable, the type to which the variable belongs precedes the variable name.

3.2 In Java, a row can declare multiple variables. Declaring each variable one by one can improve the readability of the program.

Initialization of 3.3 Variables

After a variable is declared, it must be explicitly initialized through an assignment statement -- never using the value of an uninitialized variable.

2 > In Java, variable declarations can be made anywhere in the code. The declaration of variables should be as close as possible to the place where they are first used for easy reading and use.

3 > In Java, two variables with the same name cannot be declared in the same scope.

Definition of 3.4 Constant

1 > In Java, use the keyword final to indicate constants. It is customary to capitalize constant names.

final double CM_PER_INCH=2.54;

2 > The keyword final means that a variable can only be assigned once. Once the value is set, it can not be modified in subsequent code.

3 > In Java, it is often hoped that a constant can be used in more than one method in a class. These constants are usually called class constants. You can declare a class constants using the keyword static final.

4. Operators

[], () method calls from left to right * * * * * * * * * * * * * * * * * * * * * * * *

! ~+ - + (Monadic) - Monadic ((Mandatory Type Conversion) new From Right to Left

*/% From left to right.

+- From left to right

<< > > (arithmetic right shift) > (logic right shift) > from left to right

< <= > > > >= instanceof * * * * * * from left to right

== From left to right.

& From left to right.

^ From left to right.

| From left to right.

&& From left to right.

|| From left to right.

From right to left

=+=-=*=/=%=&=|=^= <<=>=>>>>=>>== From right to left

 

 

 

5. Strings

1 > In Java, strings are treated as objects.  

2 > The strings that need to be used in programs can be roughly divided into two categories:

The immutable string String class that will not be modified or changed after creation

Build StringBuilder class that allows changes and changes to be made after creation

3 > Use "" to define strings

4 > Java automatically generates a String class object for string constants, which can initialize String objects directly.

6. Input and output technology;

1 > Keyboard input:

         Scanner in=new Scanner(System.in);

          int cnt=in.nextInt();

2 > Output

          system.out.print();

7. Control process

control flow
branch loop

if-else statement

switch statement

for Loop Statement

When Loop Statement

do-while statement

 

 

 

 

 

 

 

 

 

** Unlike the java-specific loop for each in C, it can be used to handle each element in an array without distracting itself from specifying subscripts.

Statement format:

     for(variable:collection)statement

8. Arrays

1 > Array is a data structure. It is a collection of ordered data. The data types of each element in an array are the same.

2> The determination of elements is achieved by the array name and its subscripts.

Part II: Experiments

Lab Name: Lab 2 Java Basic Programming

1. Experimental purposes:

(1) Familiar with the basic steps of java program development in command line and IDE;

(2) Master the process of importing Java source program in Eclipse integrated development environment;

(3) Grasp the basic grammar of data type, variable, operator, expression, input and output, process control of Java language basic program construction.

(4) Master the usage of Math class, String class and StringBuilder class.

3. Experimental steps and contents:

Lab 1 Procedure Mutual Evaluation

Experiment 2: Write a java application containing the following code fragments, and output the value of string class object s3.

String s1="Hello!";

String s2="World";

String s3=s1+s2;

 

source code

 1 package MyProject;
 2 
 3 public class Week2 {
 4 
 5     public static void main(String[] args) 
 6     {
 7         // TODO Auto-generated method stub
 8         String s1 ="Hello!";
 9         String s2= "World";
10         String s3=s1+s2;
11         System.out.println(s3);
12     }
13 
14 }

Operation results

Experiment 3: Change s1, s2 and s3 as StringBuilder objects in experiment 2. Observe the results of program running and compare with the results of experiment 2. Understand the difference between String objects and StringBuilder objects.

source code

 1 package MyProject;
 2 
 3 public class Week2{
 4     public static void main(String[] args) 
 5 {
 6     StringBuilder s1=new StringBuilder("Hello!");
 7     StringBuilder s2=new StringBuilder("world");
 8     StringBuilder s3=new StringBuilder();
 9     s3.append(s1);   //append Character Mosaic
10     System.out.println(s3);
11  }
12 }

Operation results

Experiment 4: Debug and run the following programs in command line mode to understand the usage of command line parameters in java applications.

source code

 1 package MyProject;
 2 
 3         public class Message
 4         {  
 5         public static void main(String[] args)
 6           {     
 7           if (args[0].equals("-h")) System.out.print("Hello");
 8             else if(args[0].equals("-g")) System.out.print("goodbye,");
 9           for(int i=1;i<args.length;i++)
10             System.out.print("  "+args[i]);
11           System.out.println("!");
12           }
13         
14     }

 

Operation results

 

 

 

Experiment 5:1 > Import Java program into Eclipse environment and import Chapter 3 sample program InputTest.java steps:

 

 

2 > Select File - > Import - > File System - > Next, open the file import window as shown below, click Browse above to select the source program and select it, click Browse below to select the source program import location for the new project InputTest/src location, and click finish to complete the import.

 

 

3 > Open the default package of the InputTest project src folder and double-click InputTest.java to open the file in the IDE source program editing area.

4 > Right-click InputTest.java file name to open the shortcut menu, select Run as - > java application to run the program. Combining with the results of the program, understand the use of Scanner class objects in the code, and master the input method of the Java console.

source code

 1 import java.util.*;
 2 
 3 /**
 4  * This program demonstrates console input.
 5  * @version 1.10 2004-02-10
 6  * @author Cay Horstmann
 7  */
 8 public class InputTest
 9 {
10    public static void main(String[] args)
11    {
12       Scanner in = new Scanner(System.in);
13 
14       // get first input
15       System.out.print("What is your name? ");
16       String name = in.nextLine();
17 
18       // get second input
19       System.out.print("How old are you? ");
20       int age = in.nextInt();
21 
22       // display output on console
23       System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1));
24    }
25 }

 

 

 

 

Experiment 6: Import WriteReadFileTest.java sample program according to the operation steps of experiment 5, run the program and understand the program code, observe the contents of file myfile.txt under the project folder, and master the input and output operation of the file.

source code

 1 import java.io.File;
 2 import java.io.FileNotFoundException;
 3 import java.io.PrintWriter;
 4 import java.util.Scanner;
 5 import java.util.Arrays;
 6 
 7 public class WriteReadFileTest {
 8 
 9     /**
10      * @param args
11      * @throws FileNotFoundException 
12      */
13     public static void main(String[] args) throws FileNotFoundException {
14 
15         //Write file demonstration
16         PrintWriter out = new PrintWriter("myfile.txt");
17         out.println("Name high Java Data Structure Average Achievement Total Achievement");
18         out.println("Zhang San20 30 400");
19         out.println("Li Si 50 60 700");
20         out.close();//Keep in mind that output is complete, need close
21         
22         
23         //Read-in File Demo
24         Scanner in = new Scanner(new File("myfile.txt"));//by myfile.txt this File Create a scanner in
25         int number = 1;//Line number
26         while(in.hasNextLine()){//Determine if the scanner still has the next line unread, which reads out each line of the file
27             String line = in.nextLine();//read out myfile.txt Next line
28             System.out.println("The first"+(number++)+"Content of the line" +"="+line);
29             
30             Scanner linescanner = new Scanner(line);//Create a scanner for each line of content
31             linescanner.useDelimiter(" ");//Use spaces as separators
32             String name = linescanner.next();
33             String math = linescanner.next();
34             String java = linescanner.next();
35             String ds = linescanner.next();
36             String avg = linescanner.next();
37             String total = linescanner.next();
38             System.out.println("name="+name+" math="+math+" java="+java+" ds="+ds+" avg"+avg+" total="+total);
39         }
40         in.close();//Read it, and you need to do it at last. close.     
41 
42  }
43 }

Operation results

 

 

 

In experiment 7, according to the operation steps of experiment 5, we import the 3-3-3-4 sample program of Chapter 3 to grasp the use of the two program loop control structures.

3-3 source code

 1 import java.util.*;
 2 
 3 /**
 4  * This program demonstrates a <code>while</code> loop.
 5  * @version 1.20 2004-02-10
 6  * @author Cay Horstmann
 7  */
 8 public class Retirement
 9 {
10    public static void main(String[] args)
11    {
12       // read inputs
13       Scanner in = new Scanner(System.in);
14 
15       System.out.print("How much money do you need to retire? ");
16       double goal = in.nextDouble();
17 
18       System.out.print("How much money will you contribute every year? ");
19       double payment = in.nextDouble();
20 
21       System.out.print("Interest rate in %: ");
22       double interestRate = in.nextDouble();
23 
24       double balance = 0;
25       int years = 0;
26 
27       // update account balance while goal isn't reached
28       while (balance < goal)
29       {
30          // add this year's payment and interest
31          balance += payment;
32          double interest = balance * interestRate / 100;
33          balance += interest;
34          years++;
35       }
36 
37       System.out.println("You can retire in " + years + " years.");
38    }
39 }

Operation results

 

 

3-4 source code

 1 import java.util.*;
 2 
 3 /**
 4  * This program demonstrates a <code>do/while</code> loop.
 5  * @version 1.20 2004-02-10
 6  * @author Cay Horstmann
 7  */
 8 public class Retirement2
 9 {
10    public static void main(String[] args)
11    {
12       Scanner in = new Scanner(System.in);
13 
14       System.out.print("How much money will you contribute every year? ");
15       double payment = in.nextDouble();
16 
17       System.out.print("Interest rate in %: ");
18       double interestRate = in.nextDouble();
19 
20       double balance = 0;
21       int year = 0;
22 
23       String input;
24 
25       // update account balance while user isn't ready to retire
26       do
27       {
28          // add this year's payment and interest
29          balance += payment;
30          double interest = balance * interestRate / 100;
31          balance += interest;
32 
33          year++;
34 
35          // print current balance
36          System.out.printf("After year %d, your balance is %,.2f%n", year, balance);
37 
38          // ask if ready to retire and get input
39          System.out.print("Ready to retire? (Y/N) ");
40          input = in.next();
41       }
42       while (input.equals("N"));
43    }
44 }

Operation results

 

 

 

 

In experiment 8, according to the operation steps of experiment 5, the sample program of Chapter 3, 3-5, is imported to understand the algorithm of lottery probability calculation.

 1 import java.util.*;
 2 
 3 /**
 4  * This program demonstrates a <code>for</code> loop.
 5  * @version 1.20 2004-02-10
 6  * @author Cay Horstmann
 7  */
 8 public class LotteryOdds
 9 {
10    public static void main(String[] args)
11    {
12       Scanner in = new Scanner(System.in);
13 
14       System.out.print("How many numbers do you need to draw? ");
15       int k = in.nextInt();
16 
17       System.out.print("What is the highest number you can draw? ");
18       int n = in.nextInt();
19 
20       /*
21        * compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
22        */
23 
24       int lotteryOdds = 1;
25       for (int i = 1; i <= k; i++)
26          lotteryOdds = lotteryOdds * (n - i + 1) / i;
27 
28       System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");
29    }
30 }

Operation results

 

 

 

4. Experimental summary:

After experimenting, I learned that the Java language has eight data types, including four integers, two floating-point types, one character type char for Unicode encoding character units and one boolean type for truth values. The float value has a suffix F or f, and if there is no suffix, it defaults to double. In the Java language, the keyword final is used to indicate constants, once. Once assigned, it cannot be changed. There are only two Boolean type values, true and false. In Java language, Boolean and shaping can not be converted to each other. The order of operators should be paid attention to when data is processed. There are two types of strings: an immutable String class that will not be modified or changed after creation, and a StringBuilder class that allows for changes and changes after creation. In the process of compiling the program, we should pay attention to the input and output of the file. The rest of the arrays, control flow and C language are roughly the same, which was almost done last week.

 

 

 

 

 

 

 

 

 

 

 

 

Keywords: Java Eclipse Programming encoding

Added by michalchojno on Mon, 09 Sep 2019 15:58:38 +0300