动手动脑第一题:
代码如下
package helloworld;
public class EnumTest {
public static void main(String[] args) {
Size s=Size.SMALL;
Size t=Size.LARGE;
//s和t引用同一个对象?
System.out.println(s==t); //
//是原始数据类型吗?
System.out.println(s.getClass().isPrimitive());
//从字符串中转换
Size u=Size.valueOf("SMALL");
System.out.println(s==u); //true
//列出它的所有值
for(Size value:Size.values()){
System.out.println(value);
}
}
}
enum Size{SMALL,MEDIUM,LARGE};
运行结果如下

这代表enum枚举不是基本类型,不同的值也不是属于同一个对象。可以通过字符串的转换使得变量相等。
动手动脑第二题
代码如下
public class TestDouble {
public static void main(String args[]) {
System.out.println("0.05 + 0.01 = " + (0.05 + 0.01));
System.out.println("1.0 - 0.42 = " + (1.0 - 0.42));
System.out.println("4.015 * 100 = " + (4.015 * 100));
System.out.println("123.3 / 100 = " + (123.3 / 100));
}
}
运行结果如下

可以看出高位浮点数的计算基本上都是不精确的。
动手动脑第三题
int X=100;
int Y=200;
System.out.println("X+Y="+X+Y);
System.out.println(X+Y+"=X+Y");
运行如此的代码,结果如下

可以看出,在第一个输出语句中,+X+Y这部分被系统解释为直接与之前的字符串"X+Y"相连接;第二个输出语句中则被解释为先加成一个数再与字符串相连接,是一种自动的类型转换
为避免歧义,需要将第一个输出语句中的+X+Y写成+(X+Y)
课堂测试
一个能自动生成各类四则运算的小程序,可自定义数量和输出算式的种类
package test;
import java.util.Scanner;
import java.util.Random;
public class Class10 {
public static void main(String[] args) {
int fi,se;
int end=0,choice,pro=30,choiceb=1;
Scanner in=new Scanner(System.in);
System.out.println("请输入要输出的式子数目");
pro=in.nextInt();
System.out.println("是否需要乘除法 1 需要/2 不要");
choiceb=in.nextInt();
Random random = new Random();
for(int i=0;i<pro;i++)
{
fi=((random.nextInt(9)+1)*10+random.nextInt(9));
se=((random.nextInt(9)+1)*10+random.nextInt(9));
fi=(random.nextInt(9)+1)*10+random.nextInt(9);
se=(random.nextInt(9)+1)*10+random.nextInt(9);
if(choiceb==2)
{
choice=random.nextInt(1);
}
else
{choice=random.nextInt(3);}
System.out.println("第"+(i+1)+"道题目");
switch(choice)
{
case 0:
end=fi+se;
System.out.println(fi+"+"+se+"="+end);
break;
case 1:
end=fi-se;
System.out.println(fi+"-"+se+"="+end);
break;
case 2:
end=fi*se;
System.out.println(fi+"x"+se+"="+end);
break;
case 3:
end=fi/se;
System.out.println(fi+"/"+se+"="+end);
break;
}
}
}
}
运行结果:

之后就卡住不动了,同时电脑的风扇发出了我至今都没听过的巨大声响,这让我坚定了给它加个16G内存条的决心
课后作业
验证码程序
import java.util.Scanner;
import java.util.Random;
public class Class11 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
Random random=new Random();
StringBuffer sb=new StringBuffer();
for(int i=0;i<4;i++){
int number=random.nextInt(3);
long result=0;
switch(number){
case 0:
result=Math.round(Math.random()*25+65);
sb.append(String.valueOf((char)result));
break;
case 1:
result=Math.round(Math.random()*25+97);
sb.append(String.valueOf((char)result));
break;
case 2:
sb.append(String.valueOf(new Random().nextInt(10)));
break;
}
}
String key=sb.toString();
System.out.println("验证码如下:");
System.out.println(key);
System.out.println("请输入验证码");
String usekey=in.next();
for(;!(key.equals(usekey));)
{
System.out.println("验证码错误,请重新输入");
usekey=in.next();
}
System.out.println("验证成功!");
}
}
运行结果



浙公网安备 33010602011771号