java入门第二篇
- 一、数据类型篇
- 计算机底层以二进制补码形式进行存储。
- 1.整数能否直接赋值给char?
答:可以,当一个整数赋值给char类型的时候,会自动转化为char类型。
public class CharTest{
public static void main(String[] args){
char c1 = a;
char c2 = 97;
}
}
- char c3 = 65535; 输出结果实际上是一个看不懂的字符。当一个整数没有超过byte,short,char的范围,直接赋值。超过的话强转。
public class CharTest02{
public static void main(String[] args){
byte = 129;//报错,超过了byte的数据范围,需要强转。
byte = (byte)129;
}
}
- 2.byte、short、char做混合运算时,各自先转化为int类型再做运算。
注意:编译器只检查语法。
- 如 char c1 =‘a’;short c2 = 1;
short c3 = c1 + c2;//报错,编译不能通过,因为编译器不负责运算。
java运算中short 、char 先被认为int类型再做运算,可能超过范围。
可以改为 short c3 = (short)(c1+c2);
short c4 = 98;//正确
int a = 1;
short s = a;//不行,编译器只能检测a是int类型,不知道a的取值。
- 3.多种数据类型做混合运算时,最终运算结果是最大容量对应的类型。 除过byte,short,char类型,因为这三种运算时会先转化为int类型再做运算。
- 4.浮点型
- float 和 double 存储的数据其实都是近似值。
- 任何一个浮点型都比整型空间大。java中默认浮点型为double。
- 大容量无法直接赋值给小容量,需要强转。
- 5.布尔类型boolean
public class BooleanTest{
public static void main(String[] args){
boolean sex = true;
if(sex){
System.out.println('男');
}else{
System.out.println('女');
}
}
}
- 6.类型转换时,需要遵循哪些规则?
- 大转小,强制类型转换。
- 小转大,自动类型转换。
- 7.重要的语法机制。
- x+=1;等同于x=()x+1;给式子前面加了个强制转换运算符。
- 所以x+=1与x=x+1,是不太一样的。
byte x = 100;
byte x = x + 1;//编译不能通过,因为x+1 会先转化为int类型再赋值。
byte x+=1;//相当于 byte x = (byte)(x+1);
使用扩展运算符 永远不会改变变量的类型。
- 二、选择语句、循环语句、转向语句
- 1.if语句(分支语句)
public class IfTest{
public class void main(String[] args){
int a = 10;
int b = 20;
boolean c = true;
if(a>=b){
c = false;
}else{
c = true;
}
printf(c);
}
}
- 2.根据成绩判断等级。根据考试成绩输出等级,优良中及格 不及格。
public class ScoreTest{
public static void main(){
java.util.Scanner s = new java.util.Scanner(System.in);
System.out.println("您输入的成绩是:");
double score = s.next();
String dengji = "A";
if(score<0||score>100){
System.out.println("成绩不合法");
return;
}else if(score>=90){
dengJi = "优";
}else if(score>=80){
dengJi = "良";
}else if(score>=60){
dengJi = "及格";
else{
dengJi = "不及格";
}
System.out.println(dengji);
}
}
- 3.使用for循环,实现1-100奇数求和。
public class SumTest{
public static void main(String[] args){
int sum = 0;
for(i = 1;i<=100;i+=2){
sum = sum + i;
}
System.out.println(sum);
}
for(i = 1;i<=100;i++){
if(i%2!=0){
sum=sum+i;
}
}
System.out.println(sum);
}
- 4.for循环99乘法表
public class ChengTest{
public static void main(String[] args){
int sum = 0;
for(i=1;i<=9;i++){
for(j=1;j<=i;j++){
sum = i*j;
System.out.print(i+"*"+j+"="+sum+" ");
}
System.out.println();
}
System.out.print(i+"*"+j+"="+sum+" ");
}
}
- 三、方法
- 1.方法
- 就是可以重复利用完成某个特定功能的代码片段。
- 定义:[修饰符列表] 返回值类型 方法名(形参列表){
方法体;
}
- 3.返回值类型 :1.基本数据类 2.引用数据类型
- 什么叫返回值:方法结束后的结果,一般会是一个数据。
- 方法就是为了完成某个特定的结果。
- 当一个方法结束 不返回任何类型时,也不能为空,用void。
- 方法必须调用才能执行。类名.方法名(实参列表);
//计算两个int类型的 商。
public static int Shang(int a,int b){
int jieguo = a/b;
return jieguo;//或者直接 return a/b;
}
//无需返回值可以这样写
public static void divided(int x,int y){
System.out.println(x/y);
}
- 4.方法位于同一个类下,调用时类名可以省略。注意:调用程序 不一定得在main 方法中,其他方法也可以调用。
- 5.方法体中 代码执行顺序 依次执行,自上而下。main方法其实也只是一种普通的方法。只不过main 方法是jvm中的,作为程序的入口。