JAVA第章例题.docVIP

  • 4
  • 0
  • 约12.08万字
  • 约 21页
  • 2016-12-08 发布于河南
  • 举报
JAVA第章例题

JAVA第3章例题 【例3-1】有参方法实例。编写一个方法模块,实现计算1 + 2 + 3 + …… + n的n项和的功能。 int mysum(int n) {  int i, s = 0;  for(i=1; i = n; i++)   s = s + i;  return s; } 【例3-2】方法中有多个return的示例,求二个数中的较大数。 int max(int x, int y) { if(x y) return x; else return y; } 【例3-3】方法调用示例,计算1 + 2 + 3 + …… + 100的和。  import javax.swing.*;  public class Example3_3  {   public static void main(String[] args)   {   float sum = mysum(100); JOptionPane.showMessageDialog(null, 1 + 2 + 3 + …… + 100 = + s);   System.exit(0);   }    int mysum(int n)  {   int i, s = 0;   for(i = 1; i = n; i++)    s = s + i;   return s;  } 【例3-4】具有多个参数的方法示例。已经三角形的底和高,计算三角形面积。  import javax.swing.*;  public class Example3_4  {   public static void main(String[] args)   { float s = area(3, 4);   JOptionPane.showMessageDialog(null, 三角形面积 = + s);   System.exit(0);   }     static float area(int x, int h)   { float s; s = (x * h) / 2; return s; }  }    【例3-5】 计算平面空间距离的计算公式分别是 和 ,使用一个方法名用方法重载实现的程序如下: /* 方法重载示例 */  import javax.swing.*;  public class Example3_5   {   static double distance(double x , double y) { double d=Math.sqrt(x*x+y*y); return d; } static double distance(double x , double y ,double z ) { double d=Math.sqrt(x*x+y*y+z*z); return d; } public static void main(String args[]) {  double d1 = distance(2,3);   double d2 = distance(3,4,5);    JOptionPane.showMessageDialog(null,       接受二个参数:平面距离 d=+d1+\n+       接受三个参数:空间距离 d=+d2 );   System.exit(0);   } } 【例3-6】 计算长方体的体积。 /* 构造长方体 */ class Box { double width, height, depth; Box() { width = 10; height = 10; depth = 10; } double volume() { return width * height * depth; } } public class Example3_6 { public static void main(String args[]) {

文档评论(0)

1亿VIP精品文档

相关文档