class Ex 210 public static void mainString args
class Ex 2_10 { public static void main(String args) { int a, b, c, d, add; int s=3587; a=s/1000; b=(s-a*1000)/100; c=(s%100)/10; d=s%10; add=a+b+c+d; System. out. println(“千位数是”+a+“t 百位数是”+b); System. out. println(“十位数是”+c+“t 个位数是”+d); System. out. println(“这个四位”+s+“的各位数字的和 是: ”+add); } }
import java. io. *; public class Ex 2_11 { public static void main(String args[]) { int i; System. out. println("Input a integer or character: "); i=Integer. parse. Int(args[0]); //从命令行接收一个数 try { int j=10/i; System. out. println("The input is '"+i+"'"+"j="+j); } catch (Arithmetic. Exception e) { System. out. println("the exception is : "+e); } } }
public class Ex 2_12{ public static void main(String args[]) { double nln; int years; double dj; System. out. println("Enter yearly rate, for example 2. 25: "); nln=Def. Input. read. Double(); double yln=nln/1200; System. out. println("Enter number of years, for example 8: "); years=Def. Input. read. Int(); System. out. println("Enter load ammount, for example 30000: "); dj=Def. Input. read. Double(); double monthly. Pay=dj*yln/(1 -1/(Math. pow(1+yln, years*12))); double total. Pay=monthly. Pay*years*12; 程序中的定义的变量都必须进行说明,并根据存储的数据定义 System. out. println("The monthly pay is: "+monthly. Pay); 合适的类型。例如,年份为整型,金额定义为双精度型。从键 盘上读入数据用Def. Input类的方法read. Int()和read. Double()。 System. out. println("The total pay is: "+total. Pay); } 但要保证Def. Input类与Ex 2_12. class类在一个目录下,才能这样 } 用上面两个方法。
import java. io. *; public class Def. Input{ public static String read. String(){ Buffered. Reader br=new Buffered. Reader( new Input. Stream. Reader(System. in), 1); String string=“ ”; try{ string=br. read. Line(); } catch(IOException ex){ System. out. println(ex); return string; } public static int read. Int(){ return Integer. parse. Int(read. String()); } public static double read. Double(){ return Double. parse. Double(read. String()); } } }
成员变量的初始化 1. 成员变量定义后,如果 没有赋值,则其初值是它 的默认值。例如byte、 short 、int和long类型的默 认值为 0,float的默认值为 0. 0 f,double类型为的默认 值为 0. 0,boolean类型的默 认值为false,char 类型默 认值为’u 0000’,引用类型 默认值为null 2. 如果需要变量具有其他 初值,那么可以在定义的 同时给变量赋值 public class Circle{ float radius=10. 0 f; float get. Radius() { return radius; }} public class Ex 3_2 { public static void main(String[] args){ Circle ci=new Circle(); // ci. radius=9. 0 f; System. out. println(ci. get. Radius()); } }
- Slides: 25