201871010110-- Li Hua "object-oriented programming (java)" the second week of learning summary

Part I: theoretical knowledge and learning section

A simple Java program should be shipped Program

1. identifier identified by the letter 0, underscore, dollar signs and numbers, and the first symbol is not a number.
  Identifier may be used: class name, object name, variable name, a method name, array name, file name, etc.
2. The keyword is a keyword in the Java language some words have been given a specific meaning. Common are: class, public, try, catch, if, float, import, void and so on. Keyword is not a variable name.
II. Notes
Notes Java There are three ways Notes: 1. The footnotes have been this line by the end of //.
                                               2./* and * / define a comment block.
                                               3./** start, end with * / comment this method can be used to automatically generate documentation.
III. Data Types
1. Data Types Java is a strongly typed language. This means that each variable must declare one for the type.
  There are eight basic types of Java - integer types (int, short, long, byte ) - floating-point type (float, double) - character types (char) - boolean (boolean)
2. integer type integer constant, said: decimal, octal, hexadecimal, binary
   Integer variable data into four types: int short long byte, Java in a range of integers running Java code and machine-independent Java no unsigned type.
 
                                              int type, variable definitions: int x; int height, age ; definitions will be assigned: intheight = 180, age = 20 ; for int variables, memory allocation, 4-byte, 32-bit representing
                                              a short type, variable definitions: short h ; short m, n; the same time define the assignment: shortm = 12, n = 20 ; for short variables, memory allocation, two bytes, representing 16,
                                              Long-type, variable definitions: long sum; long I, jk ; defined while assignment: longsum = 343435L; for long variable, 8 bytes of memory allocation, representing 64
                                              byte type variable definitions: byte w; byte x, y , z; assignment can be defined at the same time: bytex = 12, y = 24, z = 36; for byte variables, memory allocation 1-byte, 8 bits
3. there are two floating point types in Java floating point types: float double
 
   Floating-point constants, said: decimal, scientific notation
   Indicates an overflow error and three special floating-point constants: --Double.POSITIVEINFINITY positive infinity negative infinity --Double.NEGATIVE_INFINITYNaN
   float type active decimal digits 6-7, float x variable defined; floatx1, x2, x3, initial values defining floatx1 = 12.23f, x2 = 32.00f, x3, memory allocations for variables float 4 bytes , accounting for 32-bit
   double type scale is valid 15, the variable definition double d; doubled1, d2, d3 , initial values can be defined when doubled1 = 12.23, d2 = 32.00d, d3 ; double-type variable memory allocation for the eight words section, accounting for 64.

4. The character type constants 'a', 'A', '8', '?'. Variable definition char q; char c, type, cat; definitions will be assigned char c = 'a', type , cat; 19
  Character set: Java uses unicode character code set, the code sets 16, containing 65,536 characters.
  Unicode (Unicode, Unicode) is a coding standard, the escape character - prefix lu represent Unicode values, and hexadecimal 4-digit number indicates which specific Unicode characters.
The Boolean constants true, false variables defined boolean x; boolean x, y; definitions will be assigned booleanx = true, y = false; in Java, Boolean and integer not interchangeable
 
IV. Variables
1. In Java variables, each variable belonging to one type. When you declare a variable, the variable type belongs to precede the variable name. -double salary; -int vacationDays; -long earthPopulation ; -boolean done; in Java, and his party can declare multiple variables. Individually declare each variable can improve the readability of the program.
2. After a variable initialization variable declaration must be explicitly initialized by assignment to it - Never use an uninitialized variable value. In Java, you can declare a variable anywhere in the code. Declare variables as close as possible to use local variables for the first time, which is a good programming style. In Java, you can not declare a variable within the same scope of two of the same name
 
V. operator
1. The various operators: the object a particular operator to provide operator-oriented Java related new- This is used to create objects operator. Another particular Java Instanceof- operator returns a Boolean value indicating whether an object is an instance of a particular class or one of its subclasses.
2. It should be noted operator precedence and associativity priority operator binding
3. The mathematical functions and constants in a mathematical function contained in the Math class. - power function - trigonometric functions - exponential function and its inverse function such as Java also provides two constants. -Math.PI-Math.E If not want to add the prefix in front of mathematics Math method name and constant name. ", You can add the following code to the top of the source file.
4. casts to force type conversion syntax :( target type) variable .
 
VI. String
1. Java string is a sequence of Unicode characters string, which is the basic character of the data structure of the organization, similar to the use of an array of characters. There are built-in string type, provides a Java String predefined classes in the standard Java class library.
   Strings need to use the program can be divided into two categories: - do not modify and change the immutable string String class after creation; - allows to change and do change after the creation of the build string StringBuilder class.
 
VII. O
1. reads input input through the console, a Scanner need to construct the object, and with a "standard input stream" the System.in association. -Scannerin = newScanner (System.in); - Example 3-2InputTest.javap55 Task: Test InputTest.javaScanner java.util package in the class definition, and therefore need to load the appropriate package using come
2. To file input and output read the file, you need to construct a Scanner objects with a file object. To write to a file, you need to construct a PrintWriter object in the constructor, we need to need to provide the file name.
 

Eight control statements (program control flow is determined by these control statements)

1.if、switch、for、while、do-while

2.Package statement and import statements

IX. Large value

    a) If the basic integer and floating point data type can not achieve the required accuracy, the package may be used java.math two classes, a BigInteger and BigDecimal.

    b) these two classes can be operated for any length of numbers: BigInteger class implements arbitrary-precision integer arithmetic, BigDecimal achieve arbitrary precision floating point

X. Array

1. The array is a data structure that is an ordered set of data. The data type of each element in the array are the same.

2. declare the array: one-dimensional array format array element type array name []; array element type [] array name;   

                        Two-dimensional array format: array element type array name [] [];     array element type [] [] array name; type wherein data can be any type of java, including basic and complex types. Class may also be defined to declare an array;

  not allocate memory for an array of java in the array declaration, in java, arrays are separate classes, have their own way.

3. Creating an array

After the array is declared, the new operator to use its allocated memory space, the length of the array must be specified when allocating memory.

Format: Array = new array element type name [number]

Part II: Experimental part

 

1 , experimental purposes and requirements

( 1) become more familiar with the command line and IDE two modes basic steps java program development;

( 2) master the Eclipse import under integrated development environment process Java source code;

( 3) Data structure of the Java language type master basic programs, variables, operators, various types of expression, the input and output, the basic syntax of flow control;

( 4) master the use of the Math class, String class, StringBuilder class.

2 , experimental and step

Experiment 1: java multiplication table style mutual evaluation program (out of 10)

Rating Requirements: binding operation program ratings, program performance score is given out of 5 minutes, each error deduction 1 minute, until the deduction to 0;

Each rater find a correct error, experiment a score of 1 point, maximum 5 points.

'Ve rated!

Experiment 2 : The following code fragment comprising write java application, the output string class object value of s3.

String s1=“Hello!”;

String s2=“World”;

String s3=s1+s2;

Write code as follows:

package example1;
 
public  class  test2 {
 
     public  static  void  main(String[] args) {   //程序入口
         // TODO Auto-generated method stub
         String s1= "Hello!" ;             //定义了一个String,名为s1,并将字符串Hello赋值给s1
         String s2= "World" ;              //定义了一个String,名为s2,并将字符串World赋值给s2
         String s3=s1+s2;                //定义了一个String,名为上,并将s1+s2的值赋给s3
         System.out.println(s3);         //输出s3的值
     }
 
}

Screenshot program runs as follows:

 

 

  

Experiment 3: Experiment 2 Change S1 , S2 , S3 as StringBuilder class object is observed with the experimental result of the program and comparing the results 2, understood String class object distinction StringBuilder class object.

Code is as follows:

Message Package; 

public class the Message { 

	public static void main (String [] args) { 
		StringBuilder StringBuilder new new S1 = ( "the Hello!"); // string StringBuilder builder creates a new StringBuilder 
		StringBuilder StringBuilder new new S2 = ( "World"); 
		StringBuilder StringBuilder new new S3 = (); 
		s3.append (s1); 
		s3.append (s2); // with the s1 and s2 StringBuilder stitching together 
        System.out.println (S3); 
		
	} 

}

  Screenshot program runs as follows:

 

 Experimentally found that changes in the experiment 2 s1, s2, s3 StringBuilder class of objects, the same results;

String class difference between the object and the StringBuilder class objects:

When an object string constant, the string stringBuider object representation is variable. When modifying a string of information, this time not allowed to create an object, you can use stringBuilder object.

String objects are immutable. Each time one of the methods in use System.String class, create a new string object in memory, which requires the allocation of new space for the new object. 

 

Experiment 4: commissioning program in the following command line, understanding the use of java application command line arguments.

public class Message

{  

public static void main(String[] args)

  {     

  if (args[0].equals(“-h”)) System.out.print(“Hello”);

    else if(args[0].equals(“-g”)) System.out.print(“goodbye,”);

  for(int i=1;i<args.length;i++)

    System.out.print(“  ”+args[i]);

  System.out.println(“!”);

  }

}

程序代码如下:

package message;

public class Message {

	public static void main(String[] args) {
		 if (args[0].equals("-h")) System.out.print("Hello");
		    else if(args[0].equals("-g")) System.out.print("goodbye,");
		  for(int i=1;i<args.length;i++)
		    System.out.print(""+args[i]);
		  System.out.println("!");
		
	}

}

  

程序运行截图如下:

 

 

 

通过 调试运行此程序, 可知java应用程序命令行参数的用法:

Java中的命令行参数原来是通过主函数的参数实现的,且主函数的参数个数以及参数的类型其实并没有限制,在Java的基础知识中可知道,数组中存储的对象类型必须一致,所以即使是参数中写入的是数字也会按照String的类型进行强制数据类型转换。

实验5:Eclipse环境下导入第3章示例程序InputTest.java步骤:

(1) 新建java project如下图:

 

 

 

(2) 选择File->import->File ystem->Next,打开文件导入窗口如下图,点击上方Browse选择导入源程序并选中,点击下方Browse选择源程序导入位置为新项目InputTest/src位置后,点击finish完成导入。

 

 

 

 

 

(3) 打开InputTest项目src文件夹的缺省包,双击InputTest.javaIDE源程序编辑区打开文件。

(4) 右键单击InputTest.java文件名打开快捷菜单,选择Run as->java application运行此程序,结合程序运行结果,理解代码中Scanner类对象用法,掌握java控制台输入方法。

程序代码如下:

import java.util.*;

/**
 * This program demonstrates console input.
 * @version 1.10 2004-02-10
 * @author Cay Horstmann
 */
public class InputTest
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);

      // get first input
      System.out.print("What is your name? ");
      String name = in.nextLine();

      // get second input
      System.out.print("How old are you? ");
      int age = in.nextInt();

      // display output on console
      System.out.println("Hello, " + name + ". Next year, you'll be " + (age + 1));
   }
}

  

程序运行截图如下:

 

 

实验6:按照实验5操作步骤,导入WriteReadFileTest.java示例程序,运行程序并理解程序代码,观察项目文件夹下文件myfile.txt的内容,掌握文件的输入输出操作。

程序代码如下:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Arrays;

public class WriteReadFileTest {

	/**
	 * @param args
	 * @throws FileNotFoundException 
	 */
	public static void main(String[] args) throws FileNotFoundException {

		//写入文件演示
		PrintWriter out = new PrintWriter("myfile.txt");
		out.println("姓名 高数 Java 数据结构 平均成绩 总成绩");
		out.println("张三 20 30 40 0 0");
		out.println("李四 50 60 70 0 0");
		out.close();//切记,输出完毕,需要close
		
		
		//读入文件演示
		Scanner in = new Scanner(new File("myfile.txt"));//为myfile.txt这个File创建一个扫描器in
		int number = 1;//行号
		while(in.hasNextLine()){//判断扫描器是否还有下一行未读取,该循环把文件的每一行都读出
			String line = in.nextLine();//读出myfile.txt的下一行
			System.out.println("第"+(number++)+"行的内容" +"="+line);
			
			Scanner linescanner = new Scanner(line);//对每一行的内容建立一个扫描器
			linescanner.useDelimiter(" ");//使用空格作为分隔符
			String name = linescanner.next();
			String math = linescanner.next();
			String java = linescanner.next();
			String ds = linescanner.next();
			String avg = linescanner.next();
			String total = linescanner.next();
			System.out.println("name="+name+" math="+math+" java="+java+" ds="+ds+" avg"+avg+" total="+total);
		}
		in.close();//读入完毕,最后需要对其进行close。	

 }
}

  

程序运行截图如下:

 

 

文件myfile.txt的内容:

 

 

 

实验7:按照实验5的操作步骤,导入第3章3-3——3-4示例程序,掌握两个程序循环控制结构的用途。

程序代码如下:3-3

import java.util.*;

/**
 * This program demonstrates a <code>while</code> loop.
 * @version 1.20 2004-02-10
 * @author Cay Horstmann
 */
public class Retirement
{
   public static void main(String[] args)
   {
      // read inputs
      Scanner in = new Scanner(System.in);

      System.out.print("How much money do you need to retire? ");
      double goal = in.nextDouble();

      System.out.print("How much money will you contribute every year? ");
      double payment = in.nextDouble();

      System.out.print("Interest rate in %: ");
      double interestRate = in.nextDouble();

      double balance = 0;
      int years = 0;

      // update account balance while goal isn't reached
      while (balance < goal)
      {
         // add this year's payment and interest
         balance += payment;
         double interest = balance * interestRate / 100;
         balance += interest;
         years++;
      }

      System.out.println("You can retire in " + years + " years.");
   }
}

  3-4代码 

import java.util.*;

/**
 * This program demonstrates a <code>do/while</code> loop.
 * @version 1.20 2004-02-10
 * @author Cay Horstmann
 */
public class Retirement2
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);

      System.out.print("How much money will you contribute every year? ");
      double payment = in.nextDouble();

      System.out.print("Interest rate in %: ");
      double interestRate = in.nextDouble();

      double balance = 0;
      int year = 0;

      String input;

      // update account balance while user isn't ready to retire
      do
      {
         // add this year's payment and interest
         balance += payment;
         double interest = balance * interestRate / 100;
         balance += interest;

         year++;

         // print current balance
         System.out.printf("After year %d, your balance is %,.2f%n", year, balance);

         // ask if ready to retire and get input
         System.out.print("Ready to retire? (Y/N) ");
         input = in.next();
      }
      while (input.equals("N"));
   }
}

  

程序运行截图如下:

 

 

 

 

实验8:按照实验5的操作步骤,导入第3章3-5示例程序,理解抽奖概率计算算法。

程序代码如下:

import java.util.*;

/**
 * This program demonstrates a <code>for</code> loop.
 * @version 1.20 2004-02-10
 * @author Cay Horstmann
 */
public class LotteryOdds
{
   public static void main(String[] args)
   {
      Scanner in = new Scanner(System.in);

      System.out.print("How many numbers do you need to draw? ");
      int k = in.nextInt();

      System.out.print("What is the highest number you can draw? ");
      int n = in.nextInt();

      /*
       * compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
       */

      int lotteryOdds = 1;
      for (int i = 1; i <= k; i++)
         lotteryOdds = lotteryOdds * (n - i + 1) / i;

      System.out.println("Your odds are 1 in " + lotteryOdds + ". Good luck!");
   }
}

  

程序运行截图如下:

 

 

在运行过程中, 该程序用来计算抽奖中奖的概率,应用了for循环,计算了如下公式的值:n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3...*k)

第三部分 实验总结

在经过实验之后,将需要注意的知识点做一总结,细节知识需要作为重点记忆。
Java有8种数据类型,其中4种整型、2种浮点类型、1种用于表示Unicode编码的字符单元的字符类型char和1种用于表示真值的boolean类型。float类型的数值有一个后缀F或者f,如1.23f,没有后缀的话就默认为double。 

有三种特殊的浮点数值:正无穷大,负无穷大,NaN

三种数值是用于表示溢出和出错情况的,例如一个正浮点数除以0的结果为正无穷大(Infinity),而负浮点数除以0的结果为负无穷大(-Infinity)。计算0.0/0或者负数的平方根结果为NaN。
正无穷大通过Double或FLoat的POSITIVE_INFINITY表示;正无穷大通过Double或FLoat的NEGATIVE_INFINITY表示;正无穷大通过Double或FLoat的NaN表示。需要注意的是所有正无穷大数值都是一样的,所有负无穷大数值都是一样的,但是NaN不与任何数值相等,即便是自身也不相等,要判断一个特定值是否是NaN只能用Double.isNaN方法。

在Java中,利用关键字final指示常量,一次。一旦被赋值之后,就不能够再更改了。

boolean类型值有两个 true 和false,Java中boolean和整形两者之间不能相互转换,数据之间进行运算时需要注意运算符的先后 顺序。

字符串包含两类:创建之后不会再做修改和变动的不可变字符串String类;-创建之后允许再做更改和变化的构建字符串StringBuilder类。在编写程序的过程中也要注意文件的输入与输出。

总之,通过这一章的学习对java有了更清楚的理解,知识点在程序中的应运也更加重要。

 

Guess you like

Origin www.cnblogs.com/LH-18110/p/11483213.html