跟韩老师学Java第三天(章)-变量

变量

有图的笔记可以直接看码云

值得注意的概念

  • 变量三要素:变量=变量名+值+数据类型
  • 长整型需要在数后加上lL默认为int)、单精度浮点型需加fF默认为double
  • Java中文在线文档
  • char的本质是一个整数,在输出时是unicode码对应的字符,所以它是可以进行运算的
  1. Java数据类型
  2. 数据类型转换
  3. ASIIC表
  4. 基本数据类型与String类型转换
  5. 作业

1

图(必记)

2

2.1 数据类型转换-自动转换

  • 不同类型数据混合运算会自动转换成容量(精度)最大的数据类型
float d1 = n1 + 1.1;//错,因为浮点默认是double
int n2 = 1.1;//错,因为不可大到小
  • byteshortchar之间不会相互自动转换
byte b2 = n2;//错,变量赋值需判断类型,整型比byte”高一级“

byte b1 = 10;
char c1 = b1;//错,byte不可自动转char
  • byteshortchar之间可以计算,但需先转换为int
byte b1 = 1;
byte b3 = 2;
short s1 = 1;
short s2 = b2 + s1;//错
int s2 = b2 + s1;//对
  • boolean不参与转换
boolean pass = true;
int num = pass;//错

2.2 数据类型转换-强制转换

  • 强制转换可使用小括号提升优先级
  • char可以保存int的常量值,但不可以保存int变量
  • byteshortchar类型在进行运算时,当做int处理
int y = (int)8.8;

char c1 = 100;//正确

int m = 100;
char c2 = m;//错

3

4

4.1 基本型转String

int n1 = 100;
float f1 = 1.1f;
double d1 = 4.5;
boolean b1 =true;
String s1 = n1 + "";
String s2 = f1 + "";
String s3 = d1 + "";
String s4 = b1 + "";

4.2 Stirng转基本型

String s5 = "123";
int num1 = Integer.parseInt(s5);
double num2 = Double.parseDouble(s5);
float num3 = Float.parseFloat(s5);
long num4 = Long.parseLong(s5);
byte num5 = Byte.parseByte(s5);
short num6 = Short.parseShort(s5);
boolean b = Boolean.parseBoolean("true");

4.3 Stringchar

String s1 = "Hello";
char c1 = s1.charAt(0);
System.out.println(c1);//输出 H

作业

  1. as
n3 = 30
n5 = 8
  1. as
public class myHomework2 {
	public static void main(String args[]) {
		char c1='\n';
		char c2='\t';
		char c3='\r';
		char c4='\\';
		char c5='1';
		char c6='2';
		char c7='3';
		System.out.println(c1);
		System.out.println(c2);
		System.out.println(c3);
		System.out.println(c4);
		System.out.println(c5);
		System.out.println(c6);
		System.out.println(c7);
	}
}
  1. 不要把"\t"写成'\t'否则会显示数字
    • 这是因为单引号是字符串,字符串的相加实际上是对应ASCII码相加
    • System.out.println('a'+'b');相当于97+98故显示195
public class myHomework3 {
	public static void main(String args[]) {
		String book1="小学语文",book2="初中物理";
		char sex1='男',sex2='女';
		double price1=17.2,price2=8.29;
		System.out.println(book1+"\t"+book2);
		System.out.println(sex1+"\t"+sex2);
		System.out.println(price1+"\t"+price2);
	}
}
public class myHomework4 {
	public static void main(String argsp[]) {
		String name="张三",hobby="玩游戏";
		int age=12;
		float grade=59;
		char sex='男';
		System.out.println("姓名\t\t年龄\t成绩\t性别\t爱好\n"
			+name+"\t\t"+age+"\t"+grade+"\t"+sex+"\t"+hobby);
	}
}

posted on 2022-01-30 17:13  stuMartin  阅读(37)  评论(0编辑  收藏  举报

导航