基本数据类型
public class PreimitiveType
{
public static void main(String[] args)
{
/*
byte a = 127;
short b = 32767;
int c = 10;
long d = 14L;
// 十六进制
byte e = 0x10;
// 八进制
byte f = 020;
// 二进制
byte g = 0b11;
// 加下划线易读
int h = 1_000_000;
System.out.println(a + " " + b + " " + c + " " + d + " " + e + " " + f + " " + g + " " + h + " ");
*/
// 浮点数
float i = 2.43f;
double j = 3.333;
// 十六进制表示浮点数
double k = 0x1.0p-3;
if(Double.isNaN(Math.sqrt(-4)))
{
System.out.println("Math.sqrt(-4) is NaN!");
}else
{
System.out.println("ERROR!");
}
// char 字符型
char l = 'A';
char m = 65;
if (l == m)
{
System.out.println("字符串A 可以表示为'A',也可以表示为65。");
}
// 字符串还能用16进制表示
char n = '\u0041';
if (l == n)
{
System.out.println("字符串A 可以表示为'A',也可以表示为\\u0041。");
}
//转义字符
System.out.println("制表\t双引号\"单引号\'反斜杠\\换行\n");
System.out.println("回车\r");
System.out.println("------------分界线------------");
System.out.println("退格\b");
// boolean类型
boolean o = true;
if(o){
System.out.println("定义的boolean值正确。");
}
}
}
- char是基本数据类型,直接存储,比较用“==”
- Unicode转义序列会在解析代码之前处理,比如注释里的"\user"会报错,因为"\u"后面没有跟着4位十六进制数;“\u0022+\u0022"会转义为”“+”"得到空串。
运行结果
Math.sqrt(-4) is NaN!
字符串A 可以表示为'A',也可以表示为65。
字符串A 可以表示为'A',也可以表示为\u0041。
制表 双引号"单引号'反斜杠\换行
回车
------------分界线------------
退格
定义的boolean值正确。
常量与变量
public class Variable{
public static void main(String[] args){
int date0508 = 4;
int date_5_8 = 5;
if(date0508-date_5_8 < 0 )
System.out.println("date0508与date_5_8都是合格的变量名。");
// 可以在一行中声明多个变量
int i,j;
// 常量
final String CONSTANT = "常量";
}
}
- 变量名由字母、数字、货币符号以及“标点连接符”组成,第一个字符不能是数字
- 从Java10开始,对于局部变量,如果可以从变量的初始值推断出它的类型,就不需要声明类型,用var
- 关键字final指示常量
运行结果
date0508与date_5_8都是合格的变量名。
操作符
public class Operator{
public static void main(String[] args){
if(Double.isNaN(1.0/0) || 1.0/0 == Double.POSITIVE_INFINITY)
{
System.out.println("整数除0将会产生一个异常,浮点数除0将会得到无穷大或者NaN结果" + 1.0/0);
}
}
}
- 所有NaN值都认为是不同的
- 整数除0将会产生一个异常,浮点数除0将会得到无穷大或者NaN结果Infinity
- 可以用**||**避免被除数为0的情况
- && 的优先级比 || 的优先级更高
运行结果
整数除0将会产生一个异常,浮点数除0将会得到无穷大或者NaN结果Infinity
数学函数
public class MathMethod{
public static void main(String[] args)
{
double a = 4;
double b = -1;
System.out.println(Math.sqrt(a));
System.out.println(Math.pow(a,b));
int c = 4;
int d = -3;
System.out.println(Math.floorMod(c,d));
System.out.println(Math.PI);
System.out.println(Math.E);
}
}
Math.floorMod() 对于负除数会得到负数结果
Math.pow() 参数都为double类型,结果也为double类型
运行结果
2.0
0.25
-2
3.141592653589793
2.718281828459045
类型转换
public class TpyeConversion{
public static void main(String[] args)
{
int a = 4;
float b;
int c ;
char d = 'A';
c = d;
System.out.println("字符串‘A’转换为int类型为" + c);
// int -> float精度损失
b = a;
System.out.println("4转换为flat类型为" + b);
}
}
- double类型转换为int类型是截断小数部分,如果需要舍入,可以用Math.round( ) 方法, 但是 用 round方法仍需强制类型转换,因为其返回值为long类型
运行结果
字符串‘A’转换为int类型为65
4转换为flat类型为4.0
字符串
public class StringTest
{
public static void main(String[] args)
{
String greeting = "Hello";
greeting = "help";
System.out.println(greeting);
if(greeting == "help")
{
System.out.println("greeting指向的\"help\"与常量\"help\"一样");
}else
{
System.out.println("greeting指向的\"help\"与常量\"help\"不一样");
}
if(greeting.equalsIgnoreCase( "HELP"))
{
System.out.println("greeting指向的\"help\"忽略大小写与HELP一样");
}
String str = null;
String str2 = "";
System.out.println("空字符串为:" + str + "----分界线----");
System.out.println("\"\"字符串为" + str2);
// 码点与代码单元
// 代码单元个数
System.out.println("\"help\"的代码单元个数为" + greeting.length() + ",而码点个数(实际长度)为" + greeting.codePointCount(0,greeting.length()));
// charAt() 返回的为代码单元
System.out.println("\"help\"第3个代码单元为" + greeting.charAt(2));
// 遍历一个字符串
int[] codePoints = greeting.codePoints().toArray();
String str3 = new String(codePoints,0,codePoints.length);
System.out.println(str3);
// String API
System.out.println("\"help\"第2个位置开始的码点为:" + greeting.codePointAt(2));
System.out.println("\"help\".compareTo(\"hello\"为:)" + greeting.compareTo("hello"));
System.out.println("\"\"是否为空字符串" + "".isEmpty());
System.out.println("\" \"是否由空白符组成:"+ " ".isBlank());
System.out.println("\"help\"是否由he开始:"+ greeting.startsWith("he"));
System.out.println("\"help\"是否由me开始:"+ greeting.endsWith("me"));
String str4 = greeting.replace("e","a");
System.out.println("\"help\"中用a替换e为:"+ str4);
String str5 = greeting.substring(3);
System.out.println("\"help\"中从3开始的字符串为:"+ str5);
String[] strarr = {"a","b","c","d","e"};
String str6 = String.join("--",strarr);
System.out.println(str6);
String str7 = greeting.repeat(3);
System.out.println(str7);
}
}
- compartTo(String other) 方法,如果字符串位于other之前,返回一个负数,在other之后,返回一个正数,如果相等返回 0。
运算结果
help
greeting指向的"help"与常量"help"一样
greeting指向的"help"忽略大小写与HELP一样
空字符串为:null----分界线----
""字符串为
"help"的代码单元个数为4,而码点个数(实际长度)为4
"help"第3个代码单元为l
help
"help"第2个位置开始的码点为:108
"help".compareTo("hello"为:)4
""是否为空字符串true
" "是否由空白符组成:true
"help"是否由he开始:true
"help"是否由me开始:false
"help"中用a替换e为:halp
"help"中从3开始的字符串为:p
a--b--c--d--e
helphelphelp
文件读写 字符串构造
import java.util.*;
import java.io.*;
import java.nio.file.Path;
import java.nio.charset.StandardCharsets;
public class InAndOut
{
public static void main(String[] args) throws IOException
{
Scanner in = new Scanner(Path.of("poetry.txt"),StandardCharsets.UTF_8);
StringBuilder builder = new StringBuilder();
int count = 0;
while(in.hasNextLine())
{
String str = in.nextLine();
builder.append("\n" + str);
System.out.println(" " + str);
count++;
}
in.close();
System.out.println(count);
System.out.println(builder.toString());
System.out.println("Builder代码单元个数为:" + builder.length());
//文本块
//输出\\
System.out.println("\\\\");
// Console cons = System.console();
// char[] passwd = cons.readPassword("Possword:");
// System.out.println(String.valueOf(passwd));
//写入文件
PrintWriter out = new PrintWriter("out.txt",StandardCharsets.UTF_8);
out.println(builder.toString());
out.close();
}
}
-可以用 console 类来输入密码,但是应该在标准输入输出流没有被重定向的时候。
运行结果:
青玉案·元夕
【作者】辛弃疾 【朝代】宋
东风夜放花千树。更吹落、星如雨。宝马雕车香满路。凤箫声动,玉壶光转,一夜鱼龙舞。
蛾儿雪柳黄金缕。笑语盈盈暗香去。众里寻他千百度。蓦然回首,那人却在,灯火阑珊处。
Ode to the West Wind
O wild West Wind, thou breath of Autumn's being
Thou, from whose unseen presence the leaves dead
Are driven, like ghosts from an enchanter fleeing,
Yellow, and black, and pale, and hectic red,
Pestilence-stricken multitudes:O thou
Who chariltest to their dark wintry bed
The winged seeds, where they lie cold and low,
Each like a corpse within its grave, until
Thine azure sister of the Spring shall blow
Her clarion o'er the dreaming earth, and fill
(Driving sweet buds like flocks to feed in air)
With living hues and odors plain and hill:
Wild Spirit, which art moving everywhere;
Destroyer and presserver; hear, oh, hear!
21
青玉案·元夕
【作者】辛弃疾 【朝代】宋
东风夜放花千树。更吹落、星如雨。宝马雕车香满路。凤箫声动,玉壶光转,一夜鱼龙舞。
蛾儿雪柳黄金缕。笑语盈盈暗香去。众里寻他千百度。蓦然回首,那人却在,灯火阑珊处。
Ode to the West Wind
O wild West Wind, thou breath of Autumn's being
Thou, from whose unseen presence the leaves dead
Are driven, like ghosts from an enchanter fleeing,
Yellow, and black, and pale, and hectic red,
Pestilence-stricken multitudes:O thou
Who chariltest to their dark wintry bed
The winged seeds, where they lie cold and low,
Each like a corpse within its grave, until
Thine azure sister of the Spring shall blow
Her clarion o'er the dreaming earth, and fill
(Driving sweet buds like flocks to feed in air)
With living hues and odors plain and hill:
Wild Spirit, which art moving everywhere;
Destroyer and presserver; hear, oh, hear!
Builder代码单元个数为:918
\\
格式化输入输出
public class Format
{
public static void main(String[] args)
{
double x = 1000.0/3.0;
System.out.println(x);
System.out.printf("%8.2f\n",x);
System.out.printf("%8d\n",(int)x);
// 十六进制整数
int a = 123456789;
System.out.printf("123456789的十六进制形式为:%x\n",a);
System.out.printf("-123456789带符号为:%+d\n",-a);
System.out.printf("123456789前加空格为:% d\n",a);
System.out.printf("123456789的八进制形式为:%o\n",a);
double b = 100.012341;
System.out.printf("100.012341的指数形式为:%e\n",b);
System.out.printf("100.012341的十六进制浮点数形式为:%a\n",b);
char c = 'a';
String d = "a";
System.out.printf("%c\n",c);
System.out.printf("%s\n",d);
boolean e = true;
System.out.printf("%b\n",e);
// 用%s转换字符格式化任意对象。
// ?System.out.printf("用%s转换字符格式化布尔值:%s\n",x);
}
}
- 八进制前面为字母o,而不是0.
运行结果:
333.3333333333333
333.33
333
123456789的十六进制形式为:75bcd15
-123456789带符号为:-123456789
123456789前加空格为: 123456789
123456789的八进制形式为:726746425
100.012341的指数形式为:1.000123e+02
100.012341的十六进制浮点数形式为:0x1.900ca31e7d999p6
a
a
true
控制流程
/**
this is 控制流程
*/
import java.util.Scanner;
public class Control
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("你期望存到多少钱就退休:");
double goal = in.nextDouble();
System.out.println();
System.out.print("你现在的薪资是多少:");
double salary = in.nextDouble();
System.out.println();
System.out.print("你现在的利率是多少:");
double rate = in.nextDouble();
System.out.println();
retirement(goal,salary,rate);
System.out.print("input a num:");
int num = in.nextInt();
if(isPalindrome(num))
{
System.out.println(num + "是回文数字");
}else
{
System.out.println(num + "不是回文数字");
}
System.out.println("是否继续:");
String input = in.next();
switch(input.toLowerCase())
{
case "yes","y" ->
{
System.out.println("继续选择");
break;
}
case "no","n"->
{
System.out.println("退出选择");
break;
}
}
int choose = switch(input.toLowerCase())
{
case "yes","y" ->
{
System.out.println("选择1");
yield 1;
}
case "no","n" ->
{
System.out.println("选择2");
yield 2;
}
default -> 3;
};
System.out.println(choose);
// switch 直通
int i = 0;
int j = 2;
switch(choose)
{
case 1 :
case 2 : i++;
case 3 : i++;
default : j = 0;
}
System.out.println(i + " " + j);
}
private static void retirement(double goal,double salary,double rate)
{
double sum = 0;
int count = 0;
while(sum < goal)
{
count++;
sum = (sum + salary) * (1 + rate);
}
System.out.println("总共需要工作" + count + "年才能退休");
sum = count = 0;
do
{
count++;
sum = (sum + salary) * (1 + rate);
}while(sum <goal );
System.out.println("总共需要工作" + count + "年才能退休");
}
// 判断是否为回文数字
public static boolean isPalindrome(int num)
{
String str = Integer.toString(num);
int len = str.length();
boolean result = true;
for(int i = 0; i <= len / 2; i++)
{
if(str.charAt(i) != str.charAt(len - i - 1) )
{
System.out.println("test:" + str.charAt(i) + " " + str.charAt(len - i - 1));
result = false;
break;
}
}
return result;
}
}
- 使用整数或String 操作数的switch表达式必须有一个 default ,因为不论操作数是什么,表达式必须生成一个值。即包含所有可能
- java不能在嵌套的两个块中声明同名的变量,而在C++中可以,在内层定义的变量会遮蔽在外层定义的变量。
- switch表达式 关键是生成一个值,不允许跳出表达式,即 不能在switch表达式中使用 return、break、continue语句。
- switch表达式优于switch语句。
- switch语句中可以这样:case “yes”,“y” ->
- 在循环中,检测两个浮点数是否相等需要格外小心
- switch表达式中的 yield 关键字与 break 类似,会终止运行,但是 yield 会生成一个值,就是表达式的值
运行结果:
你期望存到多少钱就退休:1000000
你现在的薪资是多少:60000
你现在的利率是多少:0.02
总共需要工作15年才能退休
总共需要工作15年才能退休
input a num:1234321
1234321是回文数字
是否继续:
y
继续选择
选择1
1
2 0
数组
import java.util.Arrays;
public class ArrayTest
{
public static void main(String[] args)
{
int[] nums = new int[10]; //初始化数组,长度10,值为0
int[] nums2 = {1,2,3,4,5,};
int[] nums3 = new int[]{1,2,3,4,5,6,7,}; //匿名数组赋给nums3
System.out.println(Arrays.toString(nums));
System.out.println(Arrays.toString(nums2));
System.out.println(Arrays.toString(nums3));
// for(int i = 0; i < 8; i++)
// LotteryDrawing(49, 6);
int[][] arr = {{1,2,3,4},{12,13,14,5},{11,16,15,6},{10,9,8,7}};
int[][] arr2 = {{1,2,3},{8,9,4},{7,6,5}};
int[] result = spiralArray(arr2);
System.out.println(Arrays.toString(result));
}
// 从m个数字中抽取n个数
public static void LotteryDrawing(int m, int n)
{
int[] nums = new int[m];
int[] result = new int[n];
int i = 1;
// foreach内部实际上是使用了一个临时变量来值传递,所以并不会更改数组本身的值
// for(int num : nums)
// num = i++;
for(int k = 0; k < m; k++)
nums[k] = k + 1;
//System.out.println(Arrays.toString(nums));
int x = 0;
for(int j = 0; j < n; j++)
{
x =(int) (Math.random() * m);
result[j] = nums[x];
nums[x] = nums[m-1];
m--;
}
System.out.println(Arrays.toString(result));
}
//多维数组
/*
螺旋遍历数组
给定一个二维数组 array,请返回「螺旋遍历」该数组的结果。
螺旋遍历:从左上角开始,按照 向右、向下、向左、向上 的顺序 依次 提取元素,然后再进入内部一层重复相同的步骤,直到提取完所有元素。
示例 1:
输入:array = [[1,2,3],[8,9,4],[7,6,5]]
输出:[1,2,3,4,5,6,7,8,9]
示例 2:
输入:array = [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
输出:[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
*/
public static int[] spiralArray(int[][] array) {
if(array.length == 0)
return new int[0];
int rows = array.length;
int columns = array[0].length;
int result[] = new int[rows * columns];
int rowsmax = rows - 1;
int columnsmax = columns - 1;
int rowsmin = 0;
int columnsmin = 0;
int k = 0;
// rowsmax != rowsmin && columnsmax != columnsmin
while(k <= rows * columns - 1){
for(int i = columnsmin; i <= columnsmax; i++){
result[k] = array[rowsmin][i];
k++;
}
rowsmin++;
if(k == rows * columns )
break;
for(int i = rowsmin; i <= rowsmax; i++){
result[k] = array[i][columnsmax];
k++;
}
columnsmax--;
if(k == rows * columns )
break;
for(int i = columnsmax; i >= columnsmin; i--){
result[k] = array[rowsmax][i];
k++;
}
rowsmax--;
if(k == rows * columns )
break;
for(int i = rowsmax; i >= rowsmin; i--){
result[k] = array[i][columnsmin];
k++;
}
columnsmin++;
if(k == rows * columns )
break;
}
return result;
}
}
- 匿名数组
- foreach内部实际上是使用了一个临时变量来值传递,所以并不会更改数组本身的值
- 输出数组:Arrays.toString(nums)
- 在Java中,运行有长度为0的数组,并且与null并不相同。
- 创建数组时,数字数组所有元素都初始化为0,boolean数组元素初始化为false,对象数组元素初始化为null。
运行结果:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7]
[45, 1, 16, 41, 23, 11]
[29, 9, 11, 23, 10, 44]
[43, 6, 8, 27, 34, 3]
[5, 4, 10, 31, 3, 39]
[16, 5, 7, 19, 42, 44]
[39, 47, 34, 22, 29, 36]
[47, 37, 20, 1, 6, 41]
[35, 16, 48, 14, 36, 47]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
力扣
/*
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
*/
import java.util.Arrays;
public class Solution {
public static void main(String[] args){
int[] nums = {0,0,0,1};
moveZeroes(nums);
}
public static void moveZeroes(int[] nums) {
for(int i = 0; i <nums.length ; i++){
for(int j = 0 ;j <nums.length - i - 1;j++){
if(nums[j] == 0){
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
System.out.println(Arrays.toString(nums));
}
}
System.out.print("[");
for(int i = 0; i < nums.length; i++){
System.out.printf("%d," , nums[i]);
}
System.out.print("]");
}
}
运行结果
[0, 0, 0, 1]
[0, 0, 0, 1]
[0, 0, 1, 0]
[0, 0, 1, 0]
[0, 1, 0, 0]
[1, 0, 0, 0]
[1,0,0,0,]