初学JAVA,简单问题请别见笑
来源: 互联网 发布时间:2015-04-19
本文导语: 程序: // filename TestPrint.java // This is a test program public class TestPrint { public static void main(String args[]) { int i = 10; long l = 100; float f = 0.1; double d = 0.01; boolean b = true; char c = 'a'; Str...
程序:
// filename TestPrint.java
// This is a test program
public class TestPrint {
public static void main(String args[]) {
int i = 10;
long l = 100;
float f = 0.1;
double d = 0.01;
boolean b = true;
char c = 'a';
String str = "this is a string";
char ch[] = {'c','h','a','r','a','r','r','a','y'};
System.out.print("i = " + i);
System.out.println(" l = " + l);
System.out.print("f = " + f);
System.out.println(" d = " + d);
System.out.print("b = " + b);
System.out.println(" c = " + c);
System.out.print("str = " + str);
System.out.println(" ch = " + ch);
}
}
用JB6带的jdk1.3.1编译:
C:>javac TestPrint.java
TestPrint.java:7: possible loss of precision
found : double
required: float
float f = 0.1;
^
1 error
问题:为什么会出现上边的错误?
我把0.1改成1就可以编译通过,但执行结果为:
C:>java TestPrint
i = 10 l = 100
f = 1.0 d = 0.01
b = true c = a
str = this is a string ch = [C@77d134
问题:为什么ch不是char array?如何输出char array?
// filename TestPrint.java
// This is a test program
public class TestPrint {
public static void main(String args[]) {
int i = 10;
long l = 100;
float f = 0.1;
double d = 0.01;
boolean b = true;
char c = 'a';
String str = "this is a string";
char ch[] = {'c','h','a','r','a','r','r','a','y'};
System.out.print("i = " + i);
System.out.println(" l = " + l);
System.out.print("f = " + f);
System.out.println(" d = " + d);
System.out.print("b = " + b);
System.out.println(" c = " + c);
System.out.print("str = " + str);
System.out.println(" ch = " + ch);
}
}
用JB6带的jdk1.3.1编译:
C:>javac TestPrint.java
TestPrint.java:7: possible loss of precision
found : double
required: float
float f = 0.1;
^
1 error
问题:为什么会出现上边的错误?
我把0.1改成1就可以编译通过,但执行结果为:
C:>java TestPrint
i = 10 l = 100
f = 1.0 d = 0.01
b = true c = a
str = this is a string ch = [C@77d134
问题:为什么ch不是char array?如何输出char array?
|
0.1在java中默认为double类型,赋值给float会损失精度,1赋值给float类型的变量会自动转换成float类型
|
for(i=0;i