编写java代码计算全班同学年龄

编写java代码计算全班同学年龄,第1张

计算全班同学年龄之和。

思路:从键盘上蚂信高依次输入每个同学的年龄,然后求坦肆和输出:

import java.util.Scanner

public class TestMain {

public static void main(String[] args) {

int sum=0

Scanner in =new Scanner(System.in)

int n = in.nextInt()

sum+=n;闷尺

System.out.println(sum)

}

}

经过调试,运行正确的

第一题

abstract class Shape

{abstract double area()

abstract double perimeter()

void print()

{System.out.println("面积是:"+area()+",周长是:"+perimeter())}

}

class Circle extends Shape

{double radius

Circle(double radius)

{this.radius=radius}

double area()

{return 3.14*radius*radius}

double perimeter()

{return 2*3.14*radius}

}

class Triangle extends Shape

{int a

int b

int c

int p=(a+b+c)/2

Triangle(int a,int b,int c)

{this.a=a

this.b=b

this.c=c}

double area()

{return Math.sqrt(p*(p-a)*(p-b)*(p-c)) }

double perimeter()

{return a+b+c}

}

class Square extends Shape

{double width

double height

Square(double width,double height)

{this.width=width

this.height=height}

double area()

{return width*height}

double perimeter()

{return 2*(width+height)}

}

public class Testshape

{public static void main(String args[])

{Circle c1=new Circle(8.6)

System.out.println("圆的半径是:"+c1.radius)

c1.print()

Triangle t1=new Triangle(3,4,5)

System.out.println("三角形的边长分别是:"+t1.a+","+t1.b+","+t1.c)

t1.print()

Square s1=new Square(6.3,4.5)

System.out.println("铅握长方形的棚激返长是:"+s1.width+",宽是:"+s1.height)

s1.print()

}

}

第3题

package jacky // 声明一个jacky包,区分大链饥小写

import java.util.*

public class YMD{

private int year,month,day

public static void main(String []args)

{}

public YMD(int y, int m ,int d){

year=y

month=(((m>=1)&(m<=12))?m:1)

day=(((d>=1) &(d<=31))?d:1) }

public YMD(){

this(0,0,0) }

public static int thisyear(){

return Calendar.getInstance().get(Calendar.YEAR)}//获得当年的年份

public int year(){

return year }

public String toString(){

return year+"-"+month+"-"+day//转化为字符串

}}

第4题

import jacky.YMD

public class P3{

private String name

private YMD birth

public static void main(String args[]){

P3 a=new P3("张弛",1990,1,11)

a.output()}

public P3(String n1,YMD d1){

name=n1

birth=d1 }

public P3(String n1,int y,int m,int d){

this(n1,new YMD(y,m,d))//初始化变量与对象,调用上一个构造方法}

public int age()

{return YMD.thisyear()-birth.year()//计算年龄 }

public void output(){

System.out.println("姓名: "+name)

System.out.println("出生年龄: "+birth.toString())

System.out.println("今年年龄: "+age())

}}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/8225364.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-14
下一篇 2023-04-14

发表评论

登录后才能评论

评论列表(0条)

保存