Java基础语法

1.关键字(Keyword)
Keyword
2.标识符(Identifier)

由字母,数字,下划线“_”,美元符号“ " 组 成 , 第 一 个 字 符 不 能 是 数 字 。 公 司 中 经 常 用 “ _ ” 代 表 某 一 类 名 称 , 通 过 “ "组成,第一个字符不能是数字。公司中经常用“\_”代表某一类名称, 通过“ "_,”分隔主名称与子名称

包名:多单词组成时所有字母都小写。
类名接口名:多单词组成时,所有单词的首字母大写。
变量名和函数名:多单词组成时,第一个单词首字母小写,第二个单词开始每个单词首字母大写。
常量名:所有字母都大写。多单词时每个单词用下划线连接。

3.注释

单行注释 //注释文字
多行注释 /*注释文字*/
文档注释 /**注释文字*/ java特有,注释内容可被Javadoc解析并生成一套以网页形式体现的该程序的说明文档。
现在就来给我的第一个小程序hello world加上注释:

/*
需求: 练习一个hello world程序    
思路: 
1.定义一个类,因为java程序都定义在类中,java程序都是以类的形式形成的,类的形式其实就是一个字节码文件的最终体现。   
2.定义一个主函数,为了让该类可以独立运行。   
3.因为要演示hello world,在控制台上看到该字样,所以需要使用输出语句完成。
步骤:
1.用class关键字来完成类的定义,并起一个阅读性强的类名。
2.主函数:public static void main(String[] args); 这是固定的格式,JVM识别
3.使用输出语句: System.out.println("hello world");
*/
class Demo
{
	//定义一个主函数,为了保证程序的独立运行。
	public static void main(String[] args)  
	{
		//这是输出语句,用于将括号中的数据打印到控制台上,ln可以在数据的结尾处换行。
		System.out.println("hello world");
	}
}

4.常量和变量

Java中的常量类型有:
  1.整数常量:所有整数。
  2.小数常量:所有小数。
  3.布尔(boolean)型常量:只有两个数值,true、false。
  4.字符常量:将一个数字字母或者符号用单引号(’’)标识,如:‘a’。
  5.字符串常量:将一个或者多个字符用双引号("")标识,如:“hello world”、“a”、""(空字符串)。
  6.null常量:只有一个数值就是:null。
  下图是进制转换的计算方法:

变量:内存中的一个存储区域,该区域有自己的名称(变量名)和类型(数据类型),该区域的数据可以在同一类型范围内不断变化。
  定义变量的格式: 数据类型 变量名 = 初始化值;

Java语言的数据类型包括8种基本类型,3种引用类型。

整数默认是int类型,小数默认double类型。
Java字符采用Unicode编码,每个字符占两个字节。
数据类型是可以相互转化的,有两种转换方式。
a.自动类型转换(隐式类型转换)

class VarDemo
{
	public static void main(String[] args){
		int x = 3;
		byte b = 5;
		x = x + b;   //byte自动转换成int类型
		System.out.println(x);
	}
}

b.强制类型转换(显式类型转换)

class VarDemo
{
	public static void main(String[] args){
		byte b = 3;
		b = (byte)(b +200)   //int类型直接赋值给byte类型变量会损失精度,因此需被强制转换成byte类型
		System.out.println(x);
	}
}

5.运算符

>>> 无符号右移,高位补0

/*
不定义第三方变量交换两个整数的值,可以用异或运算符。
*/
class OperatorDemo
{
	public static void main(String[] args){
		int a = 3, b = 5;
		System.out.println("a = "+ a + ", b = "+ b );
		a = a ^ b;
		b = a ^ b;
		a = a ^ b;
		System.out.println("a = "+ a + ", b = "+ b );
	}
}

6.程序流程控制

1.判断结构

import java.util.Scanner;
/*
根据用户指定月份,打印该月份所属的季节。
*/
class IfDemo
{
	public static void main(String[] args)
	{
		//一年有四季。春季:3 4 5;夏季:6 7 8;秋季:9 10 11;冬季:12 1 2
		Scanner input = new Scanner(System.in);
		System.out.println("请输入月份: ");
		int month = input.nextInt(); 
		if (month<1 || month>12)
			System.out.println("月份输入错误");
		else if (month >=3 && month <= 5)
			System.out.println("春季");
		else if (month >=6 && month <= 8)
			System.out.println("夏季");
		else if (month >=9 && month <= 11)
			System.out.println("秋季");
		else
			System.out.println("冬季");
	}
}

2.选择结构
switch语句选择的类型只有四种:byte,short,int,char。

/*
判断grade在哪个成绩区间。
*/
public class SwitchDemo {
	public static void main(String[] args)
	{
		char grade = 'D';
		switch(grade){
		case 'A':
			System.out.println(grade+" is 85~100");
			break;
		case 'B':
			System.out.println(grade+" is 70~84");
			break;
		case 'C':
			System.out.println(grade+" is 60~69");
			break;
		case 'D':
			System.out.println(grade+" is < 60");
			break;
		default:
			System.out.println("input error");
		}		
	}
}

3.循环结构

/*
计算1到100的整数之和。
*/
public class WhileDemo {
	public static void main(String[] args)
	{
		int result = 0;
		int i = 1;
		while (i <= 100){
			result += i;
			i++;
		}
		System.out.println("result = "+result);		
	}
}
/*
计算1到100的整数之和。
*/
public class DoWhileDemo {
	public static void main(String[] args)
	{
		int result = 0;
		int i = 1;
		do{
			result += i;
			i++;
		}while(i <= 100);
		System.out.println("result = "+result);		
	}
}
/*import java.util.Scanner;
打印出如下格式的三角形:
* * * * *
 * * * *
  * * *
   * *
    *  
*/
public class ForDemo {
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("请输入三角形的行数: ");
		int index = input.nextInt();
		for (int x = 1; x <= index; x ++){
			//首先打印出*前面的空格
			for (int y = 1; y < x; y++)
				System.out.print(" ");
			//再打印出*
			for (int y = x; y <= index; y++)
				System.out.print("* ");
			System.out.println();
		}		
	}
}

break语句:跳出循环。

/*
break语句在多层嵌套的语句块中时,可以通过标签指明要终止的是哪一层循环。
输出: x = 0;
*/
public class BreakDemo{
	public static void main(String[] args){
		out: for(int x = 0; x < 3; x++){
			in: for(int y = 0; y < 4; y++){
				System.out.println("x= "+x);
				break out;
			}
		}
	}
}

continue语句:结束本次循环继续下次循环。

/*
continue语句在多层嵌套的语句块中时,可以通过标签指明要跳过的是哪一层循环。
输出: x = 0;
	  x = 1;
      x = 2;
*/
public class BreakDemo{
	public static void main(String[] args){
		out: for(int x = 0; x < 3; x++){
			in: for(int y = 0; y < 4; y++){
				System.out.println("x= "+x);
				continue out;
			}
		}
	}
}

7.函数

函数的格式:
修饰符 返回值类型 函数名(参数类型 形式参数1,参数类型 形式参数2,…)
{
  执行语句;
  return 返回值;
}
定义函数可以将功能代码进行封装,提高了代码的复用性。
函数的重载:函数重载是指在同一作用域内,可以有一组具有相同函数名,不同参数列表的函数,这组函数被称为重载函数。
wiki是这样定义的:

“In some programming languages, function overloading or method overloading is the ability to create multiple methods of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.”

/*
 用函数重载求圆、矩形和梯形的面积。
 */
public class FunOverloadDemo {

	public static void main(String[] args){
		System.out.println("半径为1的圆面积为"+CalArea(1));
		System.out.println("长2宽1的矩形面积为"+CalArea(2,1));
		System.out.println("长3宽1高2的梯形面积为"+CalArea(3,1,2));
	}
	//计算圆面积
	public static double CalArea(int radius)
	{
		return Math.PI*radius*radius;
	}
	//计算矩形面积
	public static double CalArea(int length, int width)
	{
		return length*width;
	}
	//计算梯形面积
	public static double CalArea(int a, int b, int height)
	{
		return (a+b)*height/2;
	}
}

8.数组

数组是多个相同类型数据的组合。
一维数组
  格式1:元素类型[] 数组名=new 元素类型[元素个数或数组长度];
  格式2:元素类型[] 数组名=new 元素类型[]{元素,元素,……};
二维数组
  格式1:int[][] arr = new int[3][2];
  格式2:int[][] arr = new int[3][];
数组操作异常:
  数组脚标越界异常(ArrayIndexOutOfBoundsException)
  空指针异常(NullPointerException)
直接打印数组名,结果是数组初始地址的哈希表。

数组元素排序
  选择排序:从所有序列中先找到最小的,然后放到第一个位置。再找剩余元素中最小的,放到第二个位置,以此类推。
  冒泡排序:比较相邻元素,若第一个元素大于第二个则交换。则没经过一轮循环,剩余数组中最大的数就会就位。

public class ArrayDemo {
	public static void main(String[] args){
		int[] arr1 = {89, 34, -270, 17, 3, 100};
		System.out.print("排序前数组:");
		printArray(arr1);
		selectSort(arr1);
		System.out.print("选择排序后数组:");
		printArray(arr1);
		int[] arr2 = {89, 34, -270, 17, 3, 100};
		System.out.print("排序前数组:");
		printArray(arr2);
		bubbleSort(arr2);
		System.out.print("冒泡排序后数组:");
		printArray(arr2);
	}
	//打印数组元素
	public static void printArray(int[] arr){
		System.out.print("[");
		for (int x = 0, len = arr.length; x < len; x++){
			if (x != len-1)
				System.out.print(arr[x] + ", ");
			else
				System.out.println(arr[x] + "]");
		}
	}
	//选择排序
	public static void selectSort(int[] arr){
		for (int x = 0, len = arr.length; x < len-1; x++){
			for (int y = x + 1; y < len; y++){
				if (arr[x] > arr[y]){
					swap(arr, x, y);
				}
			}
		}
	}
	//冒泡排序
	public static void bubbleSort(int[] arr){
		for (int x = 0, len = arr.length; x < len-1; x++){
			for (int y = 0; y < len-1-x; y++){
				if (arr[y] > arr[y+1]){
					swap(arr, y, y+1);
				}
			}
		}
	}
	//交换两个元素的值
	private static void swap(int[] arr, int a, int b){
		int temp = arr[a];
		arr[a] = arr[b];
		arr[b] = temp;
	}
}

数组元素查找——二分查找(折半查找)
  条件:待查询的数组是有序的。
  思路:将数组arr分成两半,取中间元素arr[mid]与待查找元素key比较,若找到则返回该元素角标。若key>arr[mid],则继续在数组右半部分查找;若key<arr[mid],则继续在数组左半部分查找。

public class ArrayDemo2 {
	public static void main(String[] args){
		int[] arr = {13, 15, 19, 28, 33, 45, 78, 106};
		int index = binarySearch(arr, 78);
		System.out.println("index = "+index);
	}
	public static int binarySearch(int[] arr, int key){
		int max, min, mid;
		min = 0;
		max = arr.length - 1;

		while(min <= max){
			mid =(max + min) >> 1;
			if(key > arr[mid])
				min = mid + 1;
			else if (key < arr[mid])
				max = mid - 1;
			else
				return mid;
		}
		return -1;
	}
}

在实际开发中,排序和二分查找都不需要我们自己去写,JDK中已经提供了相关的API供调用,如排序:Arrays.sort(arr); 查找:Arrays.binarySearch(arr,78); 。
  接下来写一个进制转换的程序,功能超级强大,能把十进制转换成任意进制!

public class TransferDemo {
	public static void main(String[] args){
		toHex(15);
		toBin(-7);
		toOctal(32);
	}
	//十进制——>二进制
	public static void toBin(int num){
		trans(num,1,1);
	}
	//十进制——>十六进制
	public static void toHex(int num){
		trans(num,15,4);
	}
	//十进制——>八进制
	public static void toOctal(int num){
		trans(num,7,3);
	}
	//进制转换的通用方法。
	public static void trans(int num, int base, int offset){
		if (num == 0){
			System.out.println("0");
			return;
		}
		char[] chs = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
		//定义arr用来存储转换后的数据
		char[] arr = new char[32];
		//pos记录转换后数据的指标,因为数据是从右往前进行转换,因此pos从最后的数组元素角标开始递减。
		int pos = arr.length;
		//将待转换数据的与base进行&运算,然后再向右无符号移动offset位。
		while(num != 0){
			int temp = num & base;
			arr[--pos] = chs[temp];
			num = num >>> offset;
		}
		//System.out.println("pos = "+pos);
		//打印转换后的数
		for(int x = pos; x < arr.length; x++){
			System.out.print(arr[x]);
		}
		System.out.println();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值