最常见的
// java中常见的数据类型 int double long short float
double a = 1.53;
// int b = a; // 报错:java: 不兼容的类型: 从double转换到int可能会有损失
// int b = (int)a; // 输出: b=1
// 题外话以下 四舍五进的是
long b = Math.round(a);
// 直接的 例: double c = 1.23; int a = (int)c; 直会得到整数部门,且不会四舍五进
// 其中元素为double/float 输出: long型 b=2
System.out.println("b="+b);
奇特的一点
double a = 1.23, b = 3.23;
int c = a+b;
System.out.println("c="+c);
很明显,大家都知道,会报错,但是请接着看我稍微改一下
double a = 1.23, b = 3.23;
int c = 0;
c+=(a+b); //int c = a+b;
System.out.println("c="+c);
输出-------------------------------<><><><><><><><><><><><><><><><>
那就奇怪了,为何我就稍微修改那么一点点,将正常的语句 c = c + (a+b); → c +=(a+b);就会成功了呢?(○´・д・)ノ
不急~,我们先看看菜鸟教程中对 += 的介绍:
可惜,并没有涉及到我们遇到的问题,但是我们可以尝试发现:
int a = 1, b = 2;
double c = 0;
c+=(a+b); //int c = a+b;
System.out.println("c="+c);
显示输出:
唉,发现了,类型跟随左侧操作数的类型,且是强制转化模式
同理: -= /= %= 同样原理
1.-
int a = 1, b = 2;
double c = 5.6;
c-=(a+b); //int c = a+b;
System.out.println("c="+c);
输出:
2./
int a = 1, b = 2;
double c = 5.6;
c/=(a+b); //int c = a+b;
System.out.println("c="+c);
输出:
3.%
int a = 1, b = 2;
double c = 5.6;
c%=(a+b); //int c = a+b;
System.out.println("c="+c);
输出:
字符部分
char a = '1';
int a_value = (int)a;
System.out.println("a_value="+a_value); // 输出: a_value=49
// 没错,没有按照1输出,而是输出了ascii码
int a_value1 = a - '0';
System.out.println("a_value1="+a_value1); // 对了,输出1了
// 当个数字得先转化为字符串,再用charAt去获取单个字符
字母递增
char ch5 = 'a';
char ch6 = (char)(ch5+1);
System.out.println("为:"+ch6); // 输出: 为:b
字符串部分
Integer → String
String a = "12";
int a_value = Integer.valueOf(a);
System.out.println("a_value="+a_value); // 输出 a_value=12
<!翻转!>: Integer → String
int a = 123;
String str = String.valueOf(a);
System.out.println("str="+str); // 输出 a_value=12
charAt()
String str = "0123456789";
System.out.println(str.charAt(0)); // 输出: 0
System.out.println(str.charAt(1)); // 输出: 1
数组和字符串
字符串 → 数组 使用toCharArray()
String str = "0123456";
char[] ch = str.toCharArray();
for(char ch1:ch) {
System.out.print(ch1+" "); // 输出: 0 1 2 3 4 5 6
}
数组 → 字符串
char[] ch = new char[]{1, 2, 3, 4, 5};
String str;
str = String.copyValueOf(ch);
System.out.println("str="+str); // 输出会有乱码现象,但一般都用于“中转站”,所以无碍
判断空格
char ch2 = 'a', ch3 = ' ';
if(Character.isSpace(ch2))
System.out.println("ch2是空格"); // 输出: (没有输出哦~)
if(Character.isSpaceChar(ch3))
System.out.println("ch3是空格"); // 输出: ch2是空格
外加
字符串的一些常用操作:
// substring、startsWith、endsWith
// substring: 提出子串
// startsWith: 判断是否以某某子串开始
// endsWith: 判断是否以某某子串结束
String str5 = "abcdefg";
boolean answer1 = str5.startsWith("ab"); // 注意是"" 单引号不行 即使是单个字符也得用"",因为参数得是字符串
boolean answer2 = str5.endsWith("f");
str5 = str5.substring(0,2); // 从下标0开始,但不包括下标2
System.out.println("answer1="+answer1+",answer2"+answer2); // 输出:answer1=true,answer=true
System.out.println("str5为:"+str5);
报告!OVER~(●’◡’●)