这个方法在这个Java程序中做了什么?

时间:2013-10-07 00:43:24

标签: java methods

我对确切的方法感到困惑,所以我希望有人用这个示例程序向我解释这个概念:

import java.io.*;
import java.util.*;

public class programB {

   public static void main(String[] args) throws IOException {

      String filename;
      String total="";
      String c = "";
      String size = "";
      int num1=0, num2=0;
      char ch;

      Scanner keyboard = new Scanner(System.in);

      System.out.println("Enter the name of the file you want to read data from:"); 
      filename=keyboard.next(); 

      Scanner fromFile = new Scanner(new FileReader(filename));

      while (fromFile.hasNext()) {
         String type = fromFile.next();

         ch = fromFile.next().charAt(0);
         num1 = fromFile.nextInt();
         if (type.equals("rectangle")) {
            num2 = fromFile.nextInt();
         }
         System.out.print(type + " ");
         System.out.print(ch + " ");
         System.out.print(num1 + " ");
         if (type.equals("rectangle")) {
            System.out.print(num2);
        }
         System.out.println();
         if (type.equals("rectangle")){
            rectangle(ch,num1,num2);

         }
         if (type.equals("triangle")){
            triangle(ch, num1);
         }

      }


   }
   /** Draw a rectangle of the specified width and height
    @param c the character that creates the drawing
    @param height the height of the rectangle
    @param width the width of the rectangle
*/
   public static void rectangle(char c, int height, int width){

      for (int i=1; i<=height; i++) {
         System.out.println();
         for (int a=1; a<= width; a++) {
            System.out.print(c);
     }

  }
  System.out.println();

   // put statements here to display a rectangle on the screen using
   // character c and the width and height parameters
   }



/** Draw a right triangle.
@param c the character that creates the drawing
@param size the height and width of the triangle
*/

   public static void triangle(char c, int size){
      for (int i=1; i<=size;i++) {
         for (int j=1; j<=i; j++) {
            System.out.print(c);
         }
         System.out.println();

      // put statements here to display a triangle on the screen using
      // character c and the size parameter
      }
   }
 }

有什么方法,有什么用?我尝试过在线研究它,我一直在研究我的教科书,但我仍然对这个概念感到困惑。

2 个答案:

答案 0 :(得分:1)

我认为,这些方法附带的文档可以很好地解释它们的作用。使用参数' - ',3和4调用rectangle()方法时,将在运行程序的控制台中“绘制”一个高3和4宽的矩形:

----
----
----

triangle()方法类似;当用' - '和3调用时,你会得到这样的形状:

-
--
---

答案 1 :(得分:1)

基本级别的方法是编写可以多次使用的代码的方法。 Java中的方法允许您在代码中定义某些操作。

这样想:你知道如何绘制三角形,对吧?所以,如果我告诉你,“画一个三角形,”你就知道该怎么做。我不会不得不说,“把你的铅笔放在一张纸上画一条短线,然后不用拿起铅笔,划出另一条线,然后绘制最后一条线连接你铅笔的地方现在已经到了你开始的地步。“这是很多指令,所以我只想说,每当我想要你绘制三角形时,我只会说,triangle()。同样,让我们​​对rectangle()执行相同的操作。

但如果这有点复杂呢?而不只是告诉你,“画一个三角形,”我说,“使用具有一定高度和一定宽度的ASCII字符绘制三角形,”这有多难?它实际上非常简单 - 你需要知道三个不同的东西:characterheightwidth。一旦你有了这些,你就知道该做什么。

当你调用triangle()rectangle()时,这正是你的代码正在做的事情 - 你将三个参数传递给它们,你的代码绘制一个三角形和一个矩形。你可以根据需要多次这样做。