【问题标题】:using a method in java在java中使用方法
【发布时间】:2012-07-22 21:50:28
【问题描述】:

我写了下面的代码来满足程序要求如下:

三个的平均值 编写一个读取三个整数的程序 显示三个数字的平均值。

输入注意事项:输入三个整数(非负整数) 在控制台。

输出注释(提示和标签):程序提示三个 具有以下字符串的整数:“输入第一个整​​数。”、“输入 第二个整数。”,“输入第三个整数。”。然后程序打印 NUMBER1、NUMBER2 和 NUMBER3 的平均值 = AVG,其中 NUMBER1 是输入的第一个整数值,NUMBER2 和 NUMBER3 随后的整数,而 AVG 是计算的平均值。

名称规范:应调用您的应用程序类 平均3:

我的源代码:

import java.util.Scanner;
public class Average3 {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int AVG, NUMBER1, NUMBER2, NUMBER3;
        System.out.println("Enter the first integer.");
        Scanner keyboard = new Scanner(System.in);
        NUMBER1 = keyboard.nextInt();
        System.out.println("Enter the second integer.");
        NUMBER2 = keyboard.nextInt();
        System.out.println("Enter the third integer.");
        NUMBER3 = keyboard.nextInt();
        AVG = (NUMBER1 + NUMBER2 + NUMBER3) / 3;
        System.out.println("The average of NUMBER1, NUMBER2, and NUMBER3 = " + AVG);

    }

}

我的程序编译得很好,但我知道我可以用关联的方法实现和调用一个对象,但是我在努力从哪里开始我从概念上理解方法和对象,但就编写代码而言。有人有什么建议吗?

【问题讨论】:

  • 尝试阅读一些 Java 入门课程或您的教科书。这一切在网上都有很好的解释。
  • 我也做过 STFW 和 RTFM,但仍在努力使其凝胶化
  • 所以你不知道如何编写计算平均值的方法?方法名:例如带有三个参数(数字 1 - 3)的 calcAVG,您需要一个 int 类型的返回值。 google如何创建方法以及返回值和参数是什么
  • 编程最好通过反复试验来学习。只需开始编写、熟悉、分析其他人编写的代码片段,然后将其变成您自己的代码。

标签: java object methods


【解决方案1】:

首先,我将创建一个类InputData 来存储用户的输入:

class InputData {
    public int number1;
    public int number2;
    public int number3;
}

这本身就是一种有用的通用技术:将多个相关值收集到一个数据结构中。然后,您可以重写您的 main 方法以使用此类而不是三个单独的 int 变量,或者您可以更进一步,为 InputData 类添加一些行为。添加的第一个明显行为是计算平均值:

class InputData {
    public int number1;
    public int number2;
    public int number3;

    public int average() {
        return (number1 + number2 + number3) / 3;
    }
}

有了这个,你可以重写你的main如下:

public class Average3 {
    static class InputData {
        public int number1;
        public int number2;
        public int number3;

        public int average() {
            return (number1 + number2 + number3) / 3;
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        InputData input = new InputData();
        System.out.println("Enter the first integer.");
        Scanner keyboard = new Scanner(System.in);
        input.number1 = keyboard.nextInt();
        System.out.println("Enter the second integer.");
        input.number2 = keyboard.nextInt();
        System.out.println("Enter the third integer.");
        input.number3 = keyboard.nextInt();
        System.out.println("The average of NUMBER1, NUMBER2, and NUMBER3 = "
            + input.average());
    }
}

请注意,我已将 InputData 设为 static inner classAverage3。它也可以是同一文件中的一个单独的顶级类(只要不是public)或单独文件中的一个类。

对此的改进是在InputData 类中使用数组而不是单独的int 字段。您的程序可能如下所示:

public class Average3 {
    static class InputData {
        public int[] numbers;

        InputData(int size) {
            numbers = new int[size];
        }

        public int average() {
            int sum = 0;
            for (int number : numbers) {
                sum += number;
            }
            return sum / numbers.length;
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        String[] prompts = { "first", "second", "third" };
        InputData input = new InputData(3);
        Scanner keyboard = new Scanner(System.in);
        for (int i = 0; i < prompts.length; ++i) {
            System.out.println("Enter the " + prompts[i] + " integer.");
            input.numbers[i] = keyboard.nextInt();
        }
        System.out.println("The average of NUMBER1, NUMBER2, and NUMBER3 = "
            + input.average());
    }
}

这里我在InputData 中添加了一个构造函数来初始化数组,并给它一个参数来设置数组的大小。

然后您可以引入额外的改进,例如使输入值的数量动态化(使用ArrayList&lt;Integer&gt; 而不是int 数组)。但这超出了作业的具体要求。有些人(实际上很多人)倾向于自动进行这种概括。但是,Extreme Programming 的拥护者会指出,通常最好保持简单:根据今天的需求设计和编码,而不是明天、下周或下个月的需求。

换句话说,你不知道下一个任务会带来什么,所以你在当前任务之外进行概括可能会浪费工作。

【讨论】:

    【解决方案2】:

    我不知道我是否会为这么简单的任务使用对象。但是,既然你问了,我会解释如果需要对象我会怎么做,

    我会创建一个具有ArrayList&lt;Integer&gt; 的对象(类),这样您就可以计算出不止3 个数字的平均值。

    这个对象有 2 个公共方法。 void addNumber(int number)double/int getAverage() addNumber 会简单地将一个数字添加到 arraylist,而 getAverage 会遍历整个列表,将所有数字相加,然后除以它的大小(不要忘记 -1)

    在 main 中,您创建该类的新对象,然后扫描仪的每次扫描,使用 addNumber 方法将输入的数字插入到数组列表中。

    鉴于我被指示使用对象,我想我会怎么做。

    祝你好运!

    【讨论】:

      【解决方案3】:

      作为一个非常基本的示例,您可以在一个 .java 文件中创建一个“知道如何”获取输入并创建平均值的类,例如:

      // takes input and stores in a list which it 
      // can do mathematical operations on
      class InputMath
      {
          // ivar to store input
          private List<int> list;
      
          // contructor
          public AverageInput() {}
      
          // gets user input and pushes to `list`
          public void getInput(String question) {}
      
          // works out the average of `list`
          public int average() {}
      
          // works out the total of `list`
          public int total() {}
      
          ...
      }
      

      然后你可以在你想要的地方使用类,比如在你的'main'函数中

      import InputMath;
      
      class Main
      {
          public static void main(String args)
          {
              InputMath im = new InputMath();
      
              for(int i=0; i<3; i++)
              {
                  im.getInput("Enter number " + (i+1));
              }
              System.out.println(im.average());
          }
      }
      

      但就像许多 cmets 建议的那样,您确实需要通读一些材料/参考/示例并“玩耍”

      【讨论】:

        【解决方案4】:

        这是一个关于如何使用非常简单的类制作程序的简短示例。

        您可以轻松更改它并询问要计算平均数的数量。

        /* using default package */
        
        import java.util.ArrayList;
        import java.util.List;
        import java.util.Scanner;
        
        /**
         * The Class Average3.
         */
        public class Average3 {
        
            /** The number list. */
            private List<Integer> numberList;
        
            /** The sum. */
            private float sum;
        
            /**
             * Instantiates a new my first class.
             */
            public Average3() {
                this.numberList = new ArrayList<Integer>();
                this.sum = 0;
            }
        
            /**
             * Adds the integer.
             *
             * @param integer the integer
             */
            public void addInteger(int integer) {
                this.numberList.add(integer);
                this.sum += integer;
            }
        
            /**
             * Gets the average.
             *
             * @return the average
             */
            public float getAverage() {
                return (this.sum/this.numberList.size());
            }
        
            /**
             *  Prints the Average.
             */
            public void printAverage() {
                System.out.print("The average of ");
                for(int j = 0; j < this.numberList.size()-1; j++) {
                    Integer i = this.numberList.get(j);
                    System.out.print(i.toString() + ", ");
                }
        
                System.out.print("and " + numberList.get(numberList.size()-1));
                System.out.println(" = " + this.getAverage());
            }
        
            /**
             * The main method.
             *
             * @param args the arguments
             */
            public static void main(String[] args) {
                Average3 myClass = new Average3();
        
                System.out.println("Enter the first integer.");
                Scanner keyboard = new Scanner(System.in);
        
                myClass.addInteger(keyboard.nextInt());
        
                System.out.println("Enter the second integer.");
                myClass.addInteger(keyboard.nextInt());
        
                System.out.println("Enter the third integer.");
                myClass.addInteger(keyboard.nextInt());
        
                myClass.printAverage();
            }
        }
        

        【讨论】:

        • 你的平均计算确实有问题。基于这种方法,2、2、2 和 2 的平均值是...... 0。为什么要在两个地方计算平均值(并重复相同的错误)?不要重复自己!
        • 当然,真的忘了除法确实需要浮点数:D
        猜你喜欢
        • 2017-08-01
        • 2019-05-03
        • 1970-01-01
        • 1970-01-01
        • 2022-12-03
        • 2016-12-16
        • 2012-01-08
        • 2019-05-03
        • 1970-01-01
        相关资源
        最近更新 更多