Java初学之代码篇<一>

来源:互联网 发布:coc各级墙升级数据 编辑:程序博客网 时间:2024/06/14 02:27

1 打印100~1000的水仙花数

public class MyDemo {    public static void main(String[] args){        int b1,b2,b3;        for(int m=101;m<1000;m++){            b1=m%10;       //个位数            b2=m%100/10;    //十位数            b3=m/100;      //百位数            if(b1*b1*b1+b2*b2*b2+b3*b3*b3==m){                System.out.println(m+"是一个水仙花数");            }        }    }}

2 利用Java类库中的Point类设计一个三角形类(Triangle),编程求三角形面积

import java.awt.Point;import java.util.Scanner;public class Triangle {    public static void main(String[] args){        Scanner x=new Scanner(System.in);        Scanner y=new Scanner(System.in);        int x1,y1,x2,y2,x3,y3;        System.out.println("请输入第一个点的坐标:");        x1=x.nextInt();        y1=y.nextInt();        System.out.println("请输入第二个点的坐标:");        x2=x.nextInt();        y2=y.nextInt();        System.out.println("请输入第三个点的坐标:");        x3=x.nextInt();        y3=y.nextInt();        Point p1=new Point(x1,y1);        Point p2=new Point(x2,y2);        Point p3=new Point(x3,y3);        double a=Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));        double b=Math.sqrt((x1-x3)*(x1-x3)+(y1-y3)*(y1-y3));        double c=Math.sqrt((x2-x3)*(x2-x3)+(y2-y3)*(y2-y3));        double p=(a+b+c)/2;        double s=Math.sqrt(p*(p-a)*(p-b)*(p-c));     //海伦公式        System.out.println(a+" "+b+" "+c);        System.out.println("面积是"+s);    }}

3 为某研究所编写一个通用程序,用来计算每一种交通工具行驶1000公里所需的时间。要求在未来如果增加第三种交通工具的时候,不必修改以前的任何程序,只需要编写新的交通工具的程序。

package test;public interface Common {    public double time(double A,double B,double C);}public class Car007 implements Common1{    int A,B,C;    public double time(double A,double B,double C){        if(C==0){            System.out.println("除零错误!");            return -1;        }        else if (A*B/C<0){            System.out.println("速度不能小于零,输入错误。");            return -1;        }        else            return A*B/C;           }}public class Plane implements Common1{    int A,B,C;    public double time(double A,double B,double C)    {        if(A+B+C<0){            System.out.println("速度不能为零,输入错误。");            return -1;            }        else            return A+B+C;    }}import java.util.Scanner;public class ComputeTime {    public static void main(String args[]) throws InstantiationException, IllegalAccessException, ClassNotFoundException  {        System.out.println("交通工具: ");        Scanner sc = new Scanner(System.in);        String name=sc.next();//交通工具        System.out.println("参数A: ");        Scanner in1= new Scanner(System.in);        double A=in1.nextDouble();        System.out.println("参数B: ");        Scanner  in2= new Scanner(System.in);        double B=in2.nextDouble();        System.out.println("参数C: ");        Scanner in3 = new Scanner(System.in);        double C=sc.nextDouble();        Common d=(Common) Class.forName("test."+name).newInstance();        sc.close();        System.out.println(name+"行驶1000公里所需的时间为"+1000/(d.time(A, B, C))+"小时");  }}