在java中使用方法

时间:2012-07-22 21:50:28

标签: java object methods

我在下面编写代码以满足程序要求,如下所示:

  

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

     

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

     

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

     

名称规范:应该召唤您的申请类   Average3:

我的源代码:

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);

    }

}

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

4 个答案:

答案 0 :(得分:1)

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

我会创建一个具有ArrayList<Integer>的对象(类),这样您就可以计算出超过3个数字的平均值。

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

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

我想我会怎么做,因为我被指示使用对象。

祝你好运!

答案 1 :(得分: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 Average3 public int。它也可以是同一文件中的单独顶级类(只要它不是InputData)或单独文件中的类。

对此的改进是使用数组而不是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<Integer>

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

然后,您可以引入其他改进,例如使输入值的数量动态化(使用{{1}}而不是{{1}}数组)。但这超出了任务的具体要求。有些人(实际上很多人)倾向于自动进行这种泛化。然而,static inner class的拥护者会指出,保持简单通常更好:为今天的需求设计和编码,而不是明天,下周或下个月的需求。

换句话说,你不知道下一个任务会带来什么,所以除了你的直接任命以外,你可能会浪费工作。

答案 2 :(得分:0)

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

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

/* 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();
    }
}

答案 3 :(得分:0)

作为一个非常基本的示例,在一个.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() {}

    ...
}

然后你可以在你想要的地方使用这个课程,就像你的'主要'功能

一样
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());
    }
}

但是很多评论都表明你真的需要阅读一些材料/参考/例子并“玩转”