Java程序设计基础学习

 前言 

 

我的老师让我们跟着Java 程序设计基础开始学习先打好基础。所以从现在开始就跟着闵老师的专栏开始学习了。

1.第一天:环境搭建

1.1 关于Java

  • 我们在安装开发环境前,可以先了解一点计算机和编程语言的历史。

 当然还有很多其他编程语言2500种以上(如用于浏览器的JavaSript、现在很火的Python等)。

  • 与C和C++不同的是Java是一种面向对象发编程语言
  • 平台独立性和可移植性,它号称可以“一次编写,到处执行”(因为有JVM,只要平台带有JVM则可屏蔽操作系统的差异) 

        比如把windows编写的代码放到Linux中,只需要把.class改成.jar

 1.2 Java开发环境

JDK

        JDK(Java Development Kit),Java开发工具。它包含开发所需要的工具,如编译、运行、调试等。JDK是整个Java的核心,它里面包括了JRE(Java Runtime Environment)、JVM。

 

                                          图 Java Platform Standard Edition 8 Documentation

 1.3 Java环境搭建

  • 下载JDK和环境变量

        官网下载:Java Downloads | Oracle

还要对它进行环境变量配置,主要有三个:JAVA_HOME、PATH、CLASSPATH(我配置的环境的路径比书上少,但是运行又暂时没有影响,它CLASSPATH多的路径和在lib下的路径所以应该不影响)

        JAVA_HOME: 表示JDK的安装目录(Eclipse等引用Java_HOME就可以找到JDK)

D:\softwase\Java\jdk1.8.0_281            (我的JDK安装目录)

        PATH: 设置指定命令搜索路径 (cmd命令行中输入java/javac,电脑即可找到jjava.exe/javac.exe)

%JAVA_HOME%\bin

%JAVA_HOME%\jre\bin

        CLASSPATH: 设置提供类搜索路径

.;%JAVA_HOME%\lib

%JAVA_HOME%是相对路径,PATH和CLASSPATH就是在这个路径下再写具体位置

因为JDK没有提供具体编译器, 这个时候我们就可以通过记事本编译。

  • IDE(集成开发环境)

显然记事本编程没有高亮、提示,还需要通过命令行转化到源程序目录,然后运行javac命令和java命令。这太麻烦了,于是我们就需要在JDK的基础上再安装编辑工具或者集成开发环境。所谓集成 IDE 就是把代码的编写、调试、编译、执行都集成到一个工具中了。为了更好的学习、编写Java代码,所以这里我们还需要下载了一个Eclipse。

        Eclipse官网下载:Eclipse Downloads | The Eclipse Foundation

1.4编写HelloWorld.java.

编写一个程序能输出"Hello World"

package day01;

/**
 * This is the first code. Name and comments should be noticed.
 * @author He Jia
 */
public class Example1 {	
	public static void main(String []args) {
		System.out.print("Holle,world!");
	}//of class main
}//Of class HelloWorld

合法标识符定义规则

  • 由26个英文字母(大小写)、0-9、_或$组成;
  • 不能以数字开头;
  • 不能使用关键字和保留字;
  • 严格区分大小写;
  • 不能包含空格;
  • 名称命名规范

名称命名规范

  • 大小写敏感:Java是对大小写敏感的语言,所以大小写不同表示的内容就不同。
  • 包名:多个单词构成全部小写,如:mystudent;
  • 类名、接口名:多个单词构成,每个单词首字母大写(大驼峰),如:MyStudent;
  • 变量名、方法名:多个单词构成,第一个单词小写,后面的单词首字母大写(小驼峰),如:myStudent;
  • 常量名:多个单词构成时,由下划线连接,全部大写,如:PI

输出

        print()方法:不能换行、一个基本数类型的数据

        比如"a=10",则需要:

"a=" +a(后面的a转化为了字符串)

        println()方法:能换行、可有一个数据类型的参数

参数和变量

参数:调用过程中需要输入参数,参数才有值;过程中可使用。

变量:存在于过程中,过程中不可用;需要赋值才能调用值。

        printf()方法:多格式数据输出

printf(String format, Object... args)

foramt:[普通字符]%[标志字符][输出宽度][.小数点位]格式控制字符[普通字符](标红必须有)

标识符
标识符作用
-输出数据左对齐
#以8/16进制输出时,数据前加上“0”/“0X”
+强制输出符号(正负)
' '输出正数时前面有一个空格
0输出数据不达指定宽度时填充0
,千分位
(输出为负数给负数加括号

下面来用一下:

2.第 2 天: 基本算术操作

2.1数据类型

       

 2.2运算符

  • 优先级和结合性(左结合右结合)
  • 运算符(9种)
运算符
运算符含义
+ - * / %二元算数运算符
+ - ++ --一元算数运算符
> >= < <= == !=关系运算符
&& || !逻辑运算符
& | ~ << >> >>>位运算符
=赋值运算符
 ?:条件运算符
+= -= *= /= %= &= ^= |= <<= >>=  >>>=

扩展的运算符

instanceof判断某对象是否是某个类的实例

2.3编写BasicOperations.java

编写一个程序实现加减乘除取余

package day02;

/**
 * This is the second code. Names and comments should be noticed.
 * @author He Jia
 */
public class BasicOperations {
	public static void main(String args[]) {
		int tempFirstInt,tempSecoundInt,tempResultInt;
		double tempFirstDouble,tempSecoundDouble,tempResultDouble;
		
		tempFirstInt = 15;
		tempSecoundInt = 4;
		
		tempFirstDouble = 1.2;
		tempSecoundDouble = 3.5;
		
		//Addition
		tempResultInt = tempFirstInt + tempSecoundInt;
		tempResultDouble = tempFirstDouble + tempSecoundDouble;
		
		System.out.println("" + tempFirstInt + " + " + tempSecoundInt + " = " + tempResultInt);
		System.out.println("" + tempFirstDouble + " + " + tempSecoundDouble + " = " + tempResultDouble);
		
		//Subtraction
		tempResultInt = tempFirstInt - tempSecoundInt;
		tempResultDouble = tempFirstDouble - tempSecoundDouble;
		
		System.out.println("" + tempFirstInt + " - " + tempSecoundInt + " = " + tempResultInt);
		System.out.println("" + tempFirstDouble + " - " + tempSecoundDouble + " = " + tempResultDouble);
		
		//Multiplication
		tempResultInt = tempFirstInt + tempSecoundInt;
		tempResultDouble = tempFirstDouble + tempSecoundDouble;
		
		System.out.println("" + tempFirstInt + " + " + tempSecoundInt + " = " + tempResultInt);
		System.out.println("" + tempFirstDouble + " + " + tempSecoundDouble + " = " + tempResultDouble);
		
		//Modulus
		tempResultInt = tempFirstInt % tempSecoundInt;
		
		System.out.println("" + tempFirstInt + " % " + tempSecoundInt + " = " + tempResultInt);
	}//Of class Main
}//Of class BasicOperations

总结:

  • 我编写的时候有写到第二个的时候就没有给输出的运算符左右打空格了,需要注意。
  • 在第二次编写的时候,注意了空格的问题,却把浮点数写成了整数,(tempSecondDouble 写成了tempSecondInt),需要注意。
  • 这里我们也可以看到包是全小写,类名是大驼峰的命名方式,变量是使用的小驼峰的方式命名。
  • 还有一点我不明白的是在单独输入(答:如果输出的第一个是变量那么就要先写一个 "")
System.out.println("");

可以换行,但是如果后面有其他内容,前面不加""结果也是一样的。可能是为了代码的规范性?

System.out.println("" + tempFirstInt + " + " + tempSecoundInt + " = " + tempResultInt);

3.第 3 天: 基本if 语句

3.1流程控制语句

Java控制流程语句分为三种:顺序、选择、循环控制语句。会涉及到if-else、while、do-while、for、return、break和选择语句switch。

        顺序控制语句:从前往后依次执行。

        选择控制语句:(if、switch)

        循环控制语句:(for)

if选择语句:

  • 简单if语句

if(条件表达式){ //可以是逻辑常量、逻辑变量,一般是关系或逻辑表达式
    多条语句(if字句) //一条if语句可以不加大括号
}

  • if-else语句

if(条件表达式){
    语句1
}else
    语句2

max = a>b? a:b;
  • if语句的嵌套(没有固定模式)

注意:嵌套层数一般不超过3层,嵌套过多会降低程序的可读性。

  • if-else if-else(可实现多情况的判断)

if-else if-else就是if-else语句只不过书写形式改变了。

  • if嵌套和if-else if-else的使用:
package day03;

import java.util.Scanner;

public class IfNest {
	public static void main(String[] args) {
		Scanner reader = new Scanner(System.in);
		
		int score;
		String grade;
		
		System.out.print("输入成绩:");
		
		score = reader.nextInt();
		
		if(score >= 90)
			grade = "优秀";
		else 
			if(score >= 80)
				grade = "良好";
			else
				if(score >= 70)
					grade = "中等";
				else
					if(score >= 60)
						grade = "及格";
					else
						grade = "不及格";
		
		System.out.print("成绩等级为:" + grade);
		System.out.println();
		System.out.println("成绩等级为:" + grade);
		System.out.printf("成绩等级为:%s\n", grade);
		
		reader.close();
	}//Of class Main
}//Of class IfNest
package day03;

import java.util.Scanner;

public class IfElse {
	public static void main(String[] args) {
		Scanner reader = new Scanner(System.in);
		
		int score;
		String grader;
		
		System.out.print("输入成绩:");
		
		score = reader.nextInt();
		
		if(score >= 90)
			grader = "优秀";
		else if(score >=80)
			grader = "良好";
		else if(score >= 70)
			grader = "中等";
		else if(score >= 60)
			grader = "及格";
		else
			grader = "不及格";
		
		System.out.println("成绩等级为:" + grader);
		
		reader.close();
	}//Of class Main
}//Of class IfElse

我们可以看到使用if-else if-else比if嵌套精减,其实if-else if-else就是if-else语句的另一种书写形式。

3.2 注释

原则:形式统一、内容准确简洁

注释条件:

   基本注释(必须加)

  • 类(接口)的注释
  • 构造函数的注释
  • 方法的注释
  • 全局变量的注释
  • 字段/属性的注释

注意:简单的代码做简单注释,注释内容不大于10个字即可,另外,持久化对象或VO对象的getter、setter方法不需加注释。

    特殊必加注释(必须加)

  • 典型算法必须有注释。
  • 在代码不明晰处必须有注释。
  • 在代码修改处加上修改标识的注释。
  • 在循环和逻辑分支组成的代码中加注释。
  • 为他人提供的接口必须加详细注释。

注释格式:

  • 单行(single-line)注释:“//……”(Ctrl+/)
  • 块(block)注释:“/*……*/”(Ctrl+Shift+/)(Ctrl+Shift+\)
  • 文档注释:“/**……*/”(ALT + SHIFT +J)
  • javadoc 注释标签语法

@author   对类的说明 标明开发该类模块的作者

@version   对类的说明 标明该类模块的版本

@see     对类、属性、方法的说明 参考转向,也就是相关主题

@param    对方法的说明 对方法中某参数的说明

@return   对方法的说明 对方法返回值的说明

@exception  对方法的说明 对方法可能抛出的异常进行说明

注意:文档注释是可以生成文档的。

3.3 编写IfStatement.java

  • 方法(函数)调用: 增加代码的复用性.
  • 方法(函数)头部规范的注释, 是后期生成文档的基础.

编写代码使得读入一个值能够输出它的绝对值

package day03;

/**
 * This is the third day, we study the usage of the statement.
 * 
 * @author He Jia
 */

public class IfStatement {
	/**
	 *********************
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 *********************
	 */
	public static void main(String args[]) {
		int tempNumber1, tempNumber2;
		
		//Try a positive value
		tempNumber1 = 5;
		
		if(tempNumber1 >= 0) {
			tempNumber2 = tempNumber1;
		} else {
			tempNumber2 = -tempNumber1;
		} // Of if
		
		System.out.println("The absolute value of " + tempNumber1 + " is " +tempNumber2);
		
		//Try a negative value
		//Lines 22 through 28 are the same as Lines 34 through 40
		tempNumber1 = -3;
		
		if(tempNumber1 >= 0) {
			tempNumber2 = tempNumber1;
		} else {
			tempNumber2 = -tempNumber1;
		} // Of if
		
		System.out.println("The absolute value of " + tempNumber1 + " is " + tempNumber2);
		
		//Now we use a method/function for this purpose.
		tempNumber1 = 6;
		System.out.println("The absolute value of " + tempNumber1 + " is " + abs(tempNumber1));
		tempNumber1 = -8;
		System.out.println("The absolute value of " + tempNumber1 + " is " + abs(tempNumber1));
	}// Of main
	
	/**
	 ********************
	 *The absolute value of the given parameter.
	 *
	 * @param paraValue The given value.
	 *********************
	 */
	public static int abs(int paraValue) {
		if(paraValue >= 0) {
			return paraValue;
		} else {
			return -paraValue;
		} // Of if
	}// Of abs
}// Of class IfStatement

总结:

  • 代码中就对类、方法、字段和其他进行了注释。
  • 我在第二次编写时,在abs中的方法是先在函数中定义了一个变量,然后使用if-else确定变量值,再返回该变量。但是这里可以直接在if-else中写返回变量。
	private static int abs(int paraNumber) {
		int paraNumber1;
		
		if (paraNumber >= 0) {
			paraNumber1 = paraNumber;
		} else {
			paraNumber1 = -paraNumber;
		} // Of if
		
		return paraNumber1;
	}// Of abs

4.第四天:闰年的计算

4.1 if 语句的嵌套

昨天我们已经写到了控制流程语句→选择控制流→if语句。今天来复习复习if语句的嵌套。

  • if嵌套语句没有固定的格式
  • if-else if-if也是if嵌套的一种写法

4.2 布尔类型

之前我们有写Java的基本数据类型有四类八种(整型数、浮点数/实型数、字符型数、布尔型数),布尔型数就是逻辑值(用于表示真假),值用true和false表示。

4.3编写LeapYear.java

编写代码判断年份是闰年还是不是闰年。

package day04;

/**
 * The complex usage of the if statement.
 * 
 * @author He Jia
 *
 */
public class LeapYear {

	/**
	 ********************** 
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 **********************
	 */
	public static void main(String[] args) {
		//Test isLeapYear
		int tempYear = 2021;
		
		System.out.print("" + tempYear + " is ");
		if(!isLeapYear(tempYear)) {
			System.out.print("NOT ");
		} // Of if
		System.out.println("a leap year.");
		
		tempYear = 2000;
		
		System.out.print("" + tempYear + " is ");
		if(!isLeapYear(tempYear)) {
			System.out.print("NOT ");
		} // Of if
		System.out.println("a leap year.");
		
		tempYear = 2100;
		
		System.out.print("" + tempYear + " is ");
		if(!isLeapYear(tempYear)) {
			System.out.print("NOT ");
		} // Of if
		System.out.println("a leap year.");
		
		tempYear = 2004;
		
		System.out.print("" + tempYear + " is ");
		if(!isLeapYear(tempYear)) {
			System.out.print("NOT ");
		} // Of if
		System.out.println("a leap year.");
		
		//Test isLeapYaerV2
		System.out.println("Now use the second version.");
		tempYear = 2021;
		
		System.out.print("" + tempYear + " is ");
		if(!isLeapYearV2(tempYear)) {
			System.out.print("NOT ");
		} // Of if
		System.out.println("a leap year.");
		
		tempYear = 2000;
		
		System.out.print("" + tempYear + " is ");
		if(!isLeapYearV2(tempYear)) {
			System.out.print("NOT ");
		} // Of if
		System.out.println("a leap year.");
		
		tempYear = 2100;
		
		System.out.print("" + tempYear + " is ");
		if(!isLeapYearV2(tempYear)) {
			System.out.print("NOT ");
		} // Of if
		System.out.println("a leap year.");
		
		tempYear = 2004;
		
		System.out.print("" + tempYear + " is ");
		if(!isLeapYearV2(tempYear)) {
			System.out.print("NOT ");
		} // Of if
		System.out.println("a leap year.");

	}// Of main


	/**
	 *******************
	 *Is the given year leap?
	 *
	 * @param paraYear The given year.
	 ********************
	 */
	private static boolean isLeapYear(int paraYear) {
		if((paraYear % 4 == 0) && (paraYear % 100 != 0) || (paraYear % 400 == 0)) {
			return true;
		} else {
			return false;
		} // Of if
	}// Of isLeapYear

	/**
	 ********************
	 *Is the given year Leap? Replace the complex condition with a number of if.
	 *
	 * @param paraYear The given year.
	 *********************
	 */
	private static boolean isLeapYearV2(int paraYear) {
		if(paraYear % 4 != 0) {
			return false;
		} else if (paraYear % 400 == 0) {
			return true;
		} else if (paraYear % 100 == 0) {
			return false;
		} else {
			return true;
		} // Of if
	}//Of isLeapYearV2
	
}//Of class LeapYear

总结:

   关于注释:

  • 通过四天的学习我们可以发现,对类和方法/函数进行注释时,在最后一个大括号后面是没有加空格的;在对if注释时,在最后一个大括号后面加了空格。
  • 在使用print/println时,如果输出的第一个是变量那么就要先写一个 ""
System.out.println("" + tempYear);
  • 一个问题,在自动生成isLeapYear和isLeapYearV2的文本注释时,生成了@return但是没有要这个注释。是只需要对参数进行说明,不需要对返回值做说明?

关于代码:

  • 代码中先定义了isLeapYear和isLeapYearV2,然后调用方法增加了复用性
  • 代码中定义的这两种方法分别用到了if-else语句(更简洁)和if-else if-else语句。

5.第 5 天: 基本switch 语句

5.1 Switch, case, break, default 的用法

第三天的时候我们说到Java控制流程语句分为三种:顺序、选择、循环控制语句。而选择控制流程语句有可以分为if和switch。

switch(表达式) {

case 常量1:

        语句组1;

case 常量2:

        语句组2;

......

default:

        语句组n+1;

}

注意:

  • 如果没有使用到break的话,如果常量1满足,那么他会执行语句组1、语句组2......语句组n+1。最后的结果会是语句组n+1。
  • 表达式和常量必须是byte、short、char、int、枚举或String


5.2 编写SwitchStatement.java

  • 单元测试单独使用一个方法, main 方法里面的代码越少越好.
package day05;

/**
 * This is the fifth code. Names and comments should be drew attention.
 * 
 * @author He Jia
 *
 */
public class SwitchStatement {
	
	/**
	 ********************* 
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
     *********************
	 */
	public static void main(String[] args) {
		scoreToLevelTest();
	}// Of main


	/**
	 ********************* 
	 * Score to level.
	 * 
	 * @param paraScore From 0 to 100.
	 * @return The level from A to F.
	 **********************
	 */
	private static char scoreToLevel(int paraScore) {
		// E stands for error, and F stands for fail.
		char resultLevel = 'E';
		
		//Divide by 10, the result ranges from 0 to 10
		int tempDigitalLevel = paraScore / 10;
		
		//The use of break is important.
		switch(tempDigitalLevel) {
		case 10:
		case 9:
			resultLevel = 'A';
			break;
		case 8:
			resultLevel = 'B';
			break;
		case 7:
			resultLevel = 'C';
			break;
		case 6:
			resultLevel = 'D';
			break;
		case 5:
		case 4:
		case 3:
		case 2:
		case 1:
		case 0:
			resultLevel = 'F';
			break;
		default:
			resultLevel = 'E';
		}// Of switch
		
		return resultLevel;
	}// Of scoreToLevel

	/**
	 ********************
	 * Method unit test.
	 ********************
	 */
	private static void scoreToLevelTest() {
		int tempScore = 100;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
		
		tempScore = 91;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
		
		tempScore = 82;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
		
		tempScore = 75;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
		
		tempScore = 66;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
		
		tempScore = 53;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
		
		tempScore = 8;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
		
		tempScore = 120;
		System.out.println("Score " + tempScore + " to level is: " + scoreToLevel(tempScore));
	}// Of scoreToLevelTest 
	
}// Of class SwitchStatement
  • 注意加break
  • 还有// Of switch和大括号之间没有空格?

6.第 6 天: 基本for 语句

6.1 for循环

前两天我们写道了Java控制流语句分为三种,顺序、循环和选择。循环语句就是在满足一定条件先反复执行某一表达式的操作,直到满足循环语句的条件,可分为有三种for、do...while()、while。

for(变量初始化;布尔表达式;变量增量){

        循环体

}

三个表达式都没有:

int sum = 0;

int i = 1;

for( ; ; ){

        sum += i;

        if(i >= 100)

                break;

        i++;

}

for-each语句(方便对数组和集合进行遍历的方法)

int array[] = {7, 8, 9};

for(int arr : array){

        System.out.println(arr);

}

for循环嵌套

6.2 编写ForStatement.java

  • 循环语句是程序的核心.
  •  算法的时间复杂度一般根据循环语句来计算.
  • 写的内容:使用for语句求出从数字1加到n的和,写出两种方法/函数,addToN函数实现从1依次加到n,addtoNWithStepLength方法实现等差数列的求和,公差可以改变。
package day06;

/**
 * This is the sixth code. Names and comments should be drew attention.
 * 
 * @author He Jia 
 *
 */
public class ForStatement {

	/**
	 *********************
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 ********************* 
	 */
	public static void main(String[] args) {
		forStatementTest();
	}// Of main

	private static void forStatementTest() {
		int tempN = 10;
		System.out.println("1 add to " + tempN + " is: " + addToN(tempN));
		
		tempN = 0;
		System.out.println("1 add to " + tempN + " is: " + addToN(tempN));
		
		int tempStepLength = 1;
		tempN = 10;
		System.out.println("1 add to " + tempN + " with step length " + tempStepLength + " is: "
				+ addtoNWithStepLength(tempN, tempStepLength));
	}// Of forStatementTest

	/**
	 *********************
	 * Add from 1 to N.
	 * 
	 * @param paraN The given upper bound.
	 * @return The sum.
	 ********************* 
	 */
	private static int addToN(int paraN) {
		int resultSum = 0;
		
		for(int i = 1; i <= paraN; i++) {
			resultSum +=i;
		} // Of for i
		
		return resultSum;
	}// Of addToN

   	/**
	 ********************** 
	 * Add from 1 to N with a step length.
	 * 
	 * @param paraN          The given upper bound.
	 * @param paraStepLength The given step length.
	 * @return The sum.
	 **********************
	 */
	private static int addtoNWithStepLength(int paraN, int paraStepLength) {
		int resultSum = 0;
		
		for(int i = 1; i <= paraN; i +=paraStepLength) {
			resultSum += i;
		} // Of for i
		
		return resultSum;
	}// Of addToNWithStepLength
	
}// Of class ForStatement

i += a;

i = i + a;

7.第 7 天: 矩阵元素相加

7.1 数组

在编写矩阵元素加减前,我们应该先了解一下数组。

  • 数组在使用前需要声明、创建、才能使用。
  • 所有元素有相同的数据类型
  • 一旦创建不能改变容量
  • 数组用一个标识符表示,有下标
  • 数组可分为一维数组、二维数组、三维数组

一维数组

声明数组:

int a[];

创建数组:

new int[10];

使用数组:

int a[] = new int[10];

注意:

  • 使用合法下表
  • 数组创建后有合法下表,整型是0;布尔是false;浮点数是0.0。
  • 数组有length属性(a.length)

Java中有一个类Array,类中的sort()方法,可以对数组进行排序。

Arrays.sort(a);

数组中定义的标识符如:int a[] = new int[10]; 中的a其实是一个地址值。所以如果分别定义并给两个数组赋值,然后将b的值赋给a,那么此时调用a数组则是b数组的结果。

二维数组

每一行元素相同:

int a[][] = new a[3][4];

每一行元素不同(和C语言不同):

int a[][] = new a[3][];

a[0] = new int[4];

a[1] = new int[2];

a[2] = new int[5];

注意:列必须有值。

 使用for和for加强循环实现冒泡排序

package day07;

import java.util.Random;

/**
 * A BubbleSort example used for.
 *
 * @author He Jia
 *
 */
public class BubbleSort {

	/**
	 ********************* 
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 *********************
	 */
	public static void main(String[] args) {
		int a[] = new int[10];
		
		getElements(a);
		forPrint(a);
		sort(a);
		forPrint(a);
	}// Of main

	/**
	 *************
	 * Unit test for respective method.
	 *************
	 */
	private static void sort(int a[]) {
		int t;
		
		for(int i = 0; i < a.length-1; i++) {
			for(int j = 0; j < a.length-1-i; j++) {
				if(a[j] > a[i]) {
					t = a[i];
					a[i] = a[j];
					a[j] = t;
				}
			} // Of for
		} // Of for
	}// Of sort

	/**
	 ******************** 
	 * Random some elements. 
	 * 
	 * @param a
	 ********************
	 */
	private static void getElements(int a[]) {
		Random rand = new Random();
		
		for(int i = 0; i < a.length-1; i++)
			a[i] = rand.nextInt(100);
	}// Of getElements

	/**
	 ******************** 
	 * Use for print array.
	 * 
	 * @param a
	 ********************
	 */
	private static void forPrint(int a[]) {
		for(int i: a) {
			System.out.printf("%3d", i);
		}
		System.out.println();		
	}// Of print

}// Of BubbleSort

7.2 编写MatrixAddition.java

  • 矩阵的赋值
  •  二重循环

编写代码能求矩阵的和以及能够将两个行列相同的矩阵相加,分别用matrixElement和matrixAddition表示。

package day07;

import java.util.Arrays;

/**
 * This is the seventh code. Name and comments should be drew attention.
 * 
 * @author He Jia
 */
public class MatrixAddition {

	/**
	 ********************* 
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 *********************
	 */
	public static void main(String[] args) {
		matrixElementSumTest();
		
		matrixAdditionTest();
	}// Of main

	/**
	 ********************* 
	 * Sum the elements of a matrix.
	 * 
	 * @param paraMatrix The given matrix.
	 * @return The sum of all its elements.
	 **********************
	 */
	public static int matrixElementSum(int[][] paraMatrix) {
		int resultSum = 0;
		for (int i = 0; i < paraMatrix.length; i++) {
			for (int j = 0; j < paraMatrix[0].length; j++) {
				resultSum += paraMatrix[i][j];
			} // Of for j
		} // Of for i
		
		return resultSum;
	}

	/**
	 ********************
	 * Unit test for respective method.
	 ******************** 
	 */
	private static void matrixElementSumTest() {
		int[][] tempMatrix = new int[3][4];
		for (int i = 0; i < tempMatrix.length; i++) {
			for (int j =0; j< tempMatrix[0].length; j++) {
				tempMatrix[i][j] = i * 10 + j;
			} // Of for j
		} // Of for i
		
		System.out.println("The matrix is: \r\n" + Arrays.deepToString(tempMatrix));
		System.out.println("The matrix elemenr sum is: " + matrixElementSum(tempMatrix) + "\r\n");
	}//Of matrixElementSumTest


	/**
	 * 
	 * Add two matrices. Attention: No error check is provided at this moment.
	 * 
	 * @param paraMatrix1 The first matrix.
	 * @param paraMatrix2 The first matrix. It should have the same size as
	 * 					  the first one's.
	 * @return The addition of these matrices.
	 */
	private static int[][] matrixAddition(int[][] paraMatrix1, int[][] paraMatrix2) {
		int[][] resultMatrix = new int[paraMatrix1.length][paraMatrix1[0].length];
		
		for (int i = 0; i < paraMatrix1.length; i++) {
			for (int j =0; j < paraMatrix1[0].length; j++) {
				resultMatrix[i][j] = paraMatrix1[i][j] + paraMatrix2[i][j];
			} // Of for j
		} // Of for i
		
		return resultMatrix;
	}
	
	/**
	 ******************** 
	 * Unit test for respective method.
	 ********************
	 */
	private static void matrixAdditionTest() {
		int[][] tempMatrix = new int[3][4];
		for (int i = 0; i < tempMatrix.length; i++) {
			for (int j = 0; j < tempMatrix[0].length; j++) {
				tempMatrix[i][j] = i * 10 + j;
			} //Of for j
		} //Of for i
		
		System.out.println("The matrix is: \r\n" + Arrays.deepToString(tempMatrix));
		int[][] tempNewMatrix = matrixAddition(tempMatrix, tempMatrix);
		System.out.println("The new matrix is: \r\n" + Arrays.deepToString(tempNewMatrix));
	}// Of matrixAdditionTest

}// Of MatrixAddition

7.3 代码格式总结

关于注释

单行注释:

  • 在函数中的,往往在需要注释的内容上方

//Addition
tempResultInt = tempFirstInt + tempSecondInt;

  • 在类、方法和if、switch、for的最后,如果是类和方法则“}//”(不空格),如果是if、for则“} //”(要空格)

多行注释:

  • 在被定义的方法和类上方,类不需要额外加两行************,方法需要。
/**
 * This is the seventh code. Name and comments should follow this style strictly.
 * 
 * @author He Jia
 */
    /**
     ********************* 
     * The entrance of the program.
     * 
     * @param args Not used now.
     *********************
     */

关于main方法下面的方法排序

按照main方法中调用方法的顺序排序,如果main方法调用的方法中,还调用了其他方法则其它方法在main方法调用方法之前。

package basic;

/**
 * example.
 * @author He Jia
 */
public class Fruit{
	/**
	 ******************** 
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 *********************
	 */
	public static void main(String[] args) {
		appleTest();
	}// Of main

	/**
	 ***************
	 * Is there an apple.
	 *
	 * @param paraI
	 * @return
	 ***************
	 */
	private static String apple(int paraI) {
		if (paraI == 0) {
			return "吃苹果!";
		} else {
			return "没有苹果。";
		} //Of if
	}// Of apple
	
	/**
	 *********************
	 * Method unit test.
	 *********************
	 */
	private static void appleTest() {
		int tempI;
		
		tempI = 0;
		System.out.println(apple(tempI));
		
		tempI =1;
		System.out.print(apple(tempI));
	}// Of eatApple
	
}// Of Fruit

8. 第8天:矩阵乘法

8.1 关于toString和deepToString

toString

数组也是一个类?

Object是所有类的父类,所有类都会去继承它,而toString又是Object中的方法。所有对象都可以使用toString,这里我们可以发现数组也是一个类。一般我们使用String方法都会在子类中重写它。而这里我们来看看它本来是怎么写的。

而当它是二维数组是Arrays.toString()输出的是两个数组转化为16进制的值。

deepToString

deepToString(Object[] a)

这个方法中的参数是一个对象,它可以打印出二维数组的值

8.2 编写MatrixMultiplication.java

  • 三重循环是多数程序的极限.
  • 非法输入检查是程序正常运行的基本保障. 如果检查所有的非法输入, 会导致大量代码行, 这在商业代码中是必须的.

编写代码使得两个矩阵相乘用multiplication方法,注意如果矩阵1的行不等于矩阵2的列那么就不能相乘需要返回null,如果相等则相乘。

package day08;

import java.util.Arrays;

/**
 * This is the eighth code. Names and comments should be drew attention.
 * 
 * @author He Jia
 */
public class MatrixMultiplication {
	/**
	 ********************* 
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 *********************
	 */
	public static void main(String args[]) {
		matrixMultiplicationTest();
	}

	/**
	 ********************* 
	 * Matrix multiplication. The columns of the first matrix should be equal to the
	 * rows of the second one.
	 * 
	 * @param paraFirstMatrix The first matrix.
	 * @param paraSecondMatrix The second matrix.
	 * @return The result matrix.
	 ********************** 
	 */
	private static int[][] multiplication(int[][] paraFirstMatrix, int[][] paraSecondMatrix) {
		int m = paraFirstMatrix.length;
		int n = paraFirstMatrix[0].length;
		int p = paraSecondMatrix[0].length;
		
		// Step 1. Dimension check.
		if (paraSecondMatrix.length != n) {
			System.out.println("The two matrices cannot be multiplied.");
			return null;
		}
		
		// Step 2. The loop.
		int[][] resultMatrix = new int[m][p];
		for(int i = 0; i < m; i++) {
			for(int j = 0; j < p; j++) {
				for(int k = 0; k < n; k++) {
					resultMatrix[i][j] += paraFirstMatrix[i][k] * paraSecondMatrix[k][j];
				} // Of for k
			} // Of for j
		} //Of for i
		
		return resultMatrix;
	} // Of multiplication
	
	/**
	 ********************
	 * Unit test for respective method.
	 ********************
	 */
	private static void matrixMultiplicationTest() {
		int[][] tempFirstMatrix = new int[2][3];
		for (int i = 0; i < tempFirstMatrix.length; i++) {
			for (int j = 0; j < tempFirstMatrix.length; j++) {
				tempFirstMatrix[i][j] = i + j;
			} // Of for j
		} // Of for i
		System.out.println("The first matrix is: \r\n" + Arrays.deepToString(tempFirstMatrix));
		
		int[][] tempSecondMatrix = new int[3][2];
		for (int i = 0; i < tempSecondMatrix.length; i++) {
			for (int j = 0; j < tempSecondMatrix[0].length; j++) {
				tempSecondMatrix[i][j] = i * 10 + j;
			} // Of for j
		} // Of for i
		System.out.println("The second matrix is:  \r\n" + Arrays.deepToString(tempSecondMatrix));
		
		int[][] tempThirdMatrix = multiplication(tempFirstMatrix, tempSecondMatrix);
		System.out.println("The third matrix is: \r\n" + Arrays.deepToString(tempThirdMatrix));
		
		System.out.println("Trying to multiply the first matrix with itself.\r\n");
		tempThirdMatrix = multiplication(tempFirstMatrix, tempFirstMatrix);
		System.out.println("The result matrix is: \r\n" + Arrays.deepToString(tempThirdMatrix));
	}// Of matrixMultiplicationTest	

}// Of class MatrixMultiplication

9. 第 9 天: while 语句

9.1 while语句

循环结构包括for和while,这里我们来了解了解while和do-while。

while语句的循环方法为利用一个条件来控制是否要反复执行这条语句。while循环语句的格式如下:

int i = 0;

while(boolean){

        //body

        i++;

}

do-while循环至少执行一次。(斐波那契数列前36项)

package day09;

/**
 * This is the ninth code. It uses do-while
 * @author He Jia
 *
 */
public class DoWhile {

	/**
	 *********************
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 *********************
	 */
	public static void main(String[] args) {
		long f1 = 1, f2 = 1;
		int counter = 0;
		
		//make Fibonacci sequence
		do {
			System.out.printf("%10d %10d", f1,f2);
			counter +=2;
			
			if(counter % 6 ==0) {
				System.out.println();
			} //Of if
			
			f1 = f1 + f2;
			f2 = f2 + f1;
		} while (counter < 36); // Of do-while
	}// Of main
}// Of DoWhile

9.2 跳转语句 break、continue、return

break终止循环,用于强行退出当前循环

continue放在循环中时是执行下一次循环。

return从一个方法返回另一个方法。

9.3 编写WhileStatent.java

注意:\n,   \r\n,输出结果均为 换行并且新的输入光标 定位在新一行的开头,我们在代码中使用的是\r\n.

package day09;

/**
 * This is the ninth code. Names and comments should be drew attention.
 *  
 * @author He Jia
 */
public class WhileStatement {

	/**
	 ******************** 
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 ********************
	 */
	public static void main(String[] args) {
		whileStatementTest();
	}

	/**
	 ********************* 
	 * The sum not exceeding a given value.
	 *********************
	 */
	private static void whileStatementTest() {
		int tempMax = 100;
		int tempValue = 0;
		int tempSum = 0;
		
		//Approach 1.
		while (tempSum <= tempMax) {
			tempValue++;
			tempSum += tempValue;
			System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
		} // Of while
		tempSum -= tempValue;
		
		System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);
		
		//Approach 2.
		System.out.println("\r\nAlternative approach");
		tempValue = 0;
		tempSum = 0;
		while (true) {
			tempValue++;
			tempSum += tempValue;
			System.out.println("tempValue = " + tempValue + " tempSum = " +tempSum);
			
			if(tempMax < tempSum) {
				break;
			} // Of if
		} // Of while
		tempSum -= tempValue;
		
		System.out.println("The sum not exceeding " + tempMax + " is: " + tempSum);
	}// Of whileStatementTest
	
}// Of class WhileStatement

从代码中我们可以发现这里的空行是一个方法空一行,而不是完全按照while\if\System空行.

当然这里我们也可以用

tempMax = 100;
tempValue = 0;
tempSum = 0;

while (tempSum + tempValue <= tempMax) {
	tempValue++;
	tempSum += tempValue;
	System.out.println("tempValue = " + tempValue + ", tempSum = " + tempSum);
} // Of while

下面我们可以使用for循环来写写:

tempMax = 100;
tempSum = 0;
for (int value = 0; tempSum - value < tempMax; ++value) {
	tempSum += value;
	System.out.println("value = " + value + " tempSum = " + tempSum);
} // Of for
		
System.out.println("The sum not exceeding " + tempMax + " is: " +tempSum);

10.  第 10天: 综合任务 1

10.1 任务要求

学生的成绩存放于一个矩阵,其中行表示学生,列表示科目。如:第 0 行表示第 0 个学生的数学、语文、英语成绩。

要求:

  1. 进行学生成绩的随机生成, 区间为 [50, 100].
  2. 找出成绩最好、最差的同学。但有挂科的同学不参加评比.

注意:

  • 实际代码中,for 和 if 是最常见的, switch 和 while 使用少得多.
  • 使用了 continue, 它是指继续跳过本次循环后面的代码,直接进入下一次循环. 而 break 是跳出整个循环体.
  • 为了随机数,迫不得已提前使用了 new 语句生成对象.
  • 通过数据测试找出程序中的 bug.
     

10.2 我的写法

先按照自己的思路思考了一下,然后写出的代码:

package day10;

import java.util.Arrays;
import java.util.Random;

/**
 * This is the tenth code, also the first task.
 * 
 * @author He Jia
 */
public class Task1 {
	/**
	 ******************** 
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 ********************
	 */
	public static void main(String[] args) {
		task1();
	}// Of main

	/**
	 *************************
	 * calculate total score of each student.
	 * 
	 * @param parascore
	 * @return The total score
	 *************************
	 */
	private static int[] totalScore(int[][] parascore) {
		int n = parascore.length;
		int m = parascore[0].length;
		int totalscore[] = new int[n];

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				totalscore[i] += parascore[i][j];
				if (parascore[i][j] < 60) {
					totalscore[i] = 0;
					break;
				} // Of if
			} // Of for
		} // Of for

		return totalscore;
	}// Of totalScore

	/**
	 **************** 
	 * Unit test for respective method.
	 ****************
	 */
	private static void task1() {
		Random random = new Random();

		int n = 10;
		int m = 3;
		int score[][] = new int[n][m];

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				score[i][j] = 50 + random.nextInt(50);
			} // Of for
		} // Of for
		System.out.println("The score is: \n" + Arrays.deepToString(score));

		int total[] = totalScore(score);
		System.out.println("The total score is: \n" + Arrays.toString(total));

		// search the best and worst score.
		int i, j = 0, p = 0;
		int min = total[0];
		int max = total[0];
		for (i = 1; i < n; i++) {
			if (total[i] > 0 && total[i] < min) {
				min = total[i];
				j = i;
			}
			if (total[i] > max) {
				max = total[i];
				p = i;
				continue;
			}
		} // Of for

		System.out.println("The " + j + "th student is the worst score and his total score is " + min + ".");
		System.out.println("The " + p + "th student is the best score and his total score is " + max + ".");

	}// Of task1

}// Of Task1

其中遇见的问题:

当时是把寻找最好和最差成绩的for循环中逻辑写错了,然后一直得不到正确答案。应该把total[i]和min/max比较。

注意:我在编写代码的时候并没有考虑到所有学生多不及格的情况,我们应该检查是否代码的健壮性。

10.3 编写Task1.java

其实我们在看代码的时候就会发现tempRandom.nextInt()里面的参数应该是50,所以我们只需要把upperBound改成100.

package day10;

import java.util.Arrays;
import java.util.Random;

/**
 * This is the tenth code, also the first task.
 * 
 * @author He Jia
 */
public class TaskOne {

	/**
	 ******************** 
	 * The entrance of the program.
	 * 
	 * @param args Not used now.
	 ********************
	 */
	public static void main(String[] args) {
		task1();
	}// Of main

	/**
	 ******************** 
	 * Method unit test.
	 ********************
	 */
	private static void task1() {
		// Step 1. Generate the data with n students and m courses.
		// Set these values by yourself
		int n = 10;
		int m = 3;
		int lowerBound = 50;
		int upperBound = 100;
		int threshold = 60;

		// Here we have to use and object to generate random numbers.
		Random tempRandom = new Random();
		int[][] data = new int[n][m];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				data[i][j] = lowerBound + tempRandom.nextInt(upperBound - lowerBound);
			} // Of for j
		} // Of for i

		System.out.println("The data is:\r\n" + Arrays.deepToString(data));

		// Step 2. Compute the total score of each student.
		int[] totalScores = new int[n];
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				if (data[i][j] < threshold) {
					totalScores[i] = 0;
					break;
				} // Of if

				totalScores[i] += data[i][j];
			} // Of for
		} // Of for i

		System.out.println("The total score are:\r\n" + Arrays.toString(totalScores));

		// Step 3. Find the best and worst student.
		// Typical initialization for index : invalid values.
		int tempBestIndex = -1;
		int tempWorstIndex = -1;
		// Typical initialization for best and worst values.
		// They must be replaced by valid values.
		int tempBestScore = 0;
		int tempWorstScore = m * upperBound + 1;
		for (int i = 0; i < n; i++) {
			// Do not consider failed students.
			if (totalScores[i] == 0) {
				continue;
			} // Of if

			if (tempBestScore < totalScores[i]) {
				tempBestScore = totalScores[i];
				tempBestIndex = i;
			} // Of if

			// Attention: This if statement cannot be combined with last one
			// using "else if", because a student can be both the best and the
			// worst. I found this bug while setting upperBound = 65.
			if (tempWorstScore > totalScores[i]) {
				tempWorstScore = totalScores[i];
				tempWorstIndex = i;
			} // Of if
		} // Of if

		// Step 4. Output the student number and score.
		if (tempBestIndex == -1) {
			System.out.println("Cannot fing best student. All students have failed.");
		} else {
			System.out.println(
					"The best student is No." + tempBestIndex + " with scores:" + Arrays.toString(data[tempBestIndex]));
		} // Of if

		if (tempWorstIndex == -1) {
			System.out.println("Cannot fing worst student. All students have failed.");
		} else {
			System.out.println("The worst student is No." + tempWorstIndex + " with scores:"
					+ Arrays.toString(data[tempWorstIndex]));
		} // Of if
	}// Of task1

}// Of TaskOne

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值