Java:从文件扫描到数组列表,然后最小/最大/平均值/标准偏差

发布于 2024-12-03 13:41:11 字数 2482 浏览 1 评论 0原文

作业是创建一个程序,将从标准输入(包含整数列表的文件)读取到数组中,然后查找这些整数的平均值、最大值、最小值、中位数和标准差。首先,这是代码:

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


public class DescriptiveStats
{

protected List<Integer> scores = new ArrayList<Integer>();

public DescriptiveStats()
{
    // default constructor
}


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

    try{
        Scanner sc = new Scanner(new FileReader("students.txt"));
        while(sc.hasNextInt())
        {
            scores.add(sc.nextInt());
        }
        sc.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

    DescriptiveStats stat = new DescriptiveStats();
    System.out.println("Min = " + stat.getMin(scores[]));
    System.out.println("Max = " + stat.getMax(scores[]));
    System.out.println("Median = " + stat.getMedian(scores[]));
    System.out.println("Mean = " + stat.getMean(scores[]));
    int Mean = stat.getMean(scores[]);
    System.out.println("Standard Deviation = " + stat.getStandardDev(scores[], Mean));
}


public int getMin(int []lst)
{
    int min = lst[0];
    for(int i=0;i<lst.length;i++)
    {                                      
        if(min>lst[i])
        min=lst[i];
    }
    return min;
}

public int getMax(int []lst)
{
    int max = lst[0];
    for(int i=0;i<lst.length;i++)
    {
        if(max<lst[i])
        max=lst[i];
    }
    return max;
}

public int getMedian(int [] lst)
{
    Arrays.sort(lst);
    int middle = lst.length/2;
    if(lst.length%2==1)
    {
        return lst[middle];
    }
    return (lst[middle-1] + lst[middle]);
}

public int getMean(int [] lst)
{
    Arrays.sort(lst);
    int mean = 0;
    int sum = 0;
    int count = 0;
    for(int i=0;i>lst.length;i++)
    {
        sum = sum + lst[i];
        count++;
    }
    mean = sum/count;
    return mean;
}

public int getStandardDev(int [] lst, int m)
{
    int mean = m;
    int [] array = lst;
    int total = 0;
    for(int i =0; i < array.length; i++)
    {
        int result = array[i]-mean;
        int [] all = Math.pow(result, 2);

    }
    total = result/array.length;
    int standev = Math.sqrt(total);
    return standev;
}

}

我的具体问题归结为:我不知道我是否正确读取文件。我遵循了从书籍到网站的许多说明,这似乎是扫描仪的正确公式,但找不到该文件。我尝试了三种不同的 IDE(BlueJ、Eclipse、Netbeans),但没有成功。

其次,我创建了将数组列表作为输入的方法,并在“public void main(string[] args)”方法中调用它们。我很确定我可以做到这一点,但它不会编译,而且我不确定我错过了什么。

最后,我想确保我的标准差方法是正确的。 我不期望任何人能够解决所有这些问题,但这些是我陷入困境的点,任何帮助将不胜感激。谢谢你!

The assignment is to create a program that will read from standard input (a file containing a list of integers) into an array, and then finding the mean, max, min, median, and standard deviation of those integers. first things first, here's the code:

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


public class DescriptiveStats
{

protected List<Integer> scores = new ArrayList<Integer>();

public DescriptiveStats()
{
    // default constructor
}


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

    try{
        Scanner sc = new Scanner(new FileReader("students.txt"));
        while(sc.hasNextInt())
        {
            scores.add(sc.nextInt());
        }
        sc.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

    DescriptiveStats stat = new DescriptiveStats();
    System.out.println("Min = " + stat.getMin(scores[]));
    System.out.println("Max = " + stat.getMax(scores[]));
    System.out.println("Median = " + stat.getMedian(scores[]));
    System.out.println("Mean = " + stat.getMean(scores[]));
    int Mean = stat.getMean(scores[]);
    System.out.println("Standard Deviation = " + stat.getStandardDev(scores[], Mean));
}


public int getMin(int []lst)
{
    int min = lst[0];
    for(int i=0;i<lst.length;i++)
    {                                      
        if(min>lst[i])
        min=lst[i];
    }
    return min;
}

public int getMax(int []lst)
{
    int max = lst[0];
    for(int i=0;i<lst.length;i++)
    {
        if(max<lst[i])
        max=lst[i];
    }
    return max;
}

public int getMedian(int [] lst)
{
    Arrays.sort(lst);
    int middle = lst.length/2;
    if(lst.length%2==1)
    {
        return lst[middle];
    }
    return (lst[middle-1] + lst[middle]);
}

public int getMean(int [] lst)
{
    Arrays.sort(lst);
    int mean = 0;
    int sum = 0;
    int count = 0;
    for(int i=0;i>lst.length;i++)
    {
        sum = sum + lst[i];
        count++;
    }
    mean = sum/count;
    return mean;
}

public int getStandardDev(int [] lst, int m)
{
    int mean = m;
    int [] array = lst;
    int total = 0;
    for(int i =0; i < array.length; i++)
    {
        int result = array[i]-mean;
        int [] all = Math.pow(result, 2);

    }
    total = result/array.length;
    int standev = Math.sqrt(total);
    return standev;
}

}

My particular issues come down to this: I don't know if I'm reading in the file correctly. I've followed many instructions from books to website and that seems to be the correct formula for scanner, but the file isn't found. I've tried three different IDE's (BlueJ, Eclipse, Netbeans) to no avail.

Secondly, I've created the methods to take an arraylist as input and called them in a 'public void main(string[] args)' method. I'm pretty sure i can do this, but it won't compile, and i'm not sure what i'm missing.

Finally, I want to make sure that my standard deviation method is correct.
I don't expect any one person to solve all of these, but those are the points at which I'm stuck, and any help would be appreciated. Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

流殇 2024-12-10 13:41:11

要做的第一件事是让你的程序编译并运行(无论正确与否)。然后您可以简单地打印它读取的值并测试它们是否与数据文件中的值相同。

为了让你的程序运行,你首先需要将 main() 方法声明为static。另外,由于您正在捕获 IOException(顺便说一句,这是个好主意!),因此您不需要声明 main 来引发异常。最后,由于您尝试读取 main 内的数据,因此无法访问 scores 字段,因为它是一个实例变量,并且您没有 的实例DescriptiveStats 还没有。此外,由于您将数组作为参数传递给分析函数,因此它不需要是实例变量。试试这个:

public static void main(String[] args) {
    List<Integer> scores = new ArrayList<Integer>();
    try{
        Scanner sc = new Scanner(new FileReader("students.txt"));
        while(sc.hasNextInt())
        {
            scores.add(sc.nextInt());
        }
        sc.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    // etc.
}

The first thing to do is to get your program to compile and run (correctly or not). Then you can simply print the values it reads and test whether they are identical to the values in the data file.

To get your program to run, you first need to declare the main() method to be static. Also, since you're catching the IOException (good idea, by the way!), you don't need to declare main to throw the exception. Finally, since you are trying to read the data inside main, you can't access the scores field, since it's an instance variable and you don't have an instance of DescriptiveStats yet. Besides, since you're passing the array as a parameter to the analysis functions, it doesn't need to be an instance variable. Try this instead:

public static void main(String[] args) {
    List<Integer> scores = new ArrayList<Integer>();
    try{
        Scanner sc = new Scanner(new FileReader("students.txt"));
        while(sc.hasNextInt())
        {
            scores.add(sc.nextInt());
        }
        sc.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    // etc.
}
不美如何 2024-12-10 13:41:11

如果您想知道程序尝试从何处读取文件,请使用以下命令:

File students = new File("students.txt");
System.out.println("Reading data from :" + students.getAbsolutePath());
Scanner sc = new Scanner(new FileReader(students));
...

If you want to know from where the program tries to read the file, use this:

File students = new File("students.txt");
System.out.println("Reading data from :" + students.getAbsolutePath());
Scanner sc = new Scanner(new FileReader(students));
...
红墙和绿瓦 2024-12-10 13:41:11

您将文件“students'txt”放在哪里。如果它与“DescriptiveStats”类不在同一位置,JVM 将无法找到该文件。因此,请确保该文件与类位于同一路径中,或者如果您想从其他地方获取它,请指定正确的路径。

来到第二点。您绝对可以从 main() 函数调用这些方法。您遇到的编译器错误是什么?

感谢您尝试不同 IDE 所付出的努力。但这和IDE无关。

Where do you have placed the file "students'txt". If it is not in the same location as the class "DescriptiveStats", JVM won't be able to locate the file. So, make sure that the file is in the same path as the class or specify the correct path if you want to take it from somewhere else.

Coming to the second point. You can absolutely call these methods from the main() function. What is the compiler error you are getting?

Appreciate your effort in trying out with different IDEs. But it has nothing got to do with the IDE.

不奢求什么 2024-12-10 13:41:11

好的,所以我根据人们的建议做了一些更改。我取消了硬编码文件,并将其替换为标准输入。现在,我真正的重点是:
-确保我正确使用数组列表和方法,
-确保我能够正确地将这些应用到标准差
这是我的新代码:

import java.io.*;
import java.util.*;
/**
 * Read from a standard input a series of exam scores,    
 * then compute the min, max, avg, med, & stand deviation.
 */
public class DescriptiveStats
{

public DescriptiveStats()
{
    // default constructor
}


public static void main(String[] args) throws IOException
{
    ArrayList<Integer> scores = new ArrayList<Integer>();
    try{
        Scanner input = new Scanner(System.in);
        while(input.hasNextInt())
        {
            scores.add(input.nextInt());
        }
        input.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

    DescriptiveStats stat = new DescriptiveStats();
    System.out.println("Min = " + stat.getMin(scores));
    System.out.println("Max = " + stat.getMax(scores));
    System.out.println("Median = " + stat.getMedian(scores));
    System.out.println("Mean = " + stat.getMean(scores));
    int Mean = stat.getMean(scores);
    //System.out.println("Standard Deviation = " + stat.getStandardDev(scores, Mean));
}


public int getMin(ArrayList<Integer> lst)
{
    int min = 0;
    int d = 0;
    for(int i=0;i<lst.size();i++)
    {                         
        d = lst.get(i);
        if(min>d)
        {
            min=d;
        }
    }
    return min;
}

public int getMax(ArrayList<Integer> lst)
{
    int max = lst.get(0);
    for(int i=0;i<lst.size();i++)
    {
        if(max<lst.get(i))
        max=lst.get(i);
    }
    return max;
}

public int getMedian(ArrayList<Integer> lst)
{
    Collections.sort(lst);
    int middle = lst.size()/2;
    if(lst.size()%2==1)
    {
        return lst.get(middle);
    }
    return (lst.get(middle-1) + lst.get(middle));
}


public int getMean(ArrayList<Integer> lst)
{
    Collections.sort(lst);
    int mean = 0;
    int sum = 0;
    int count = 0;
    for(int i=0;i>lst.size();i++)
    {
        sum = sum + lst.get(i);
        count++;
    }
    mean = sum/count;
    return mean;
}
/**
public int getStandardDev(ArrayList lst, int m)
{
    int mean = m;
    int [] array = lst;
    int total = 0;
    for(int i =0; i < array.length; i++)
    {
        int result = array[i]-mean;
        int [] all = Math.pow(result, 2);

    }
    total = result/array.length;
    int standev = Math.sqrt(total);
    return standev;
}**/

}

如您所见,标准差方法及其在主方法中的引用都被注释掉了。我还没有尝试将它们转换为数组列表,因为我不确定我对其他人做了正确的事情。

最后,当我运行我所拥有的内容时,编译器不会返回任何错误。相反,它只是挂起,可能已经崩溃了。我不知道为什么。当我在 BlueJ 中使用“void main(String[] args”选项时,我提交文本文件的名称(位于项目目录中。主目录中甚至有一个,以防万一这就是所引用的内容。

谢谢全部。

Okay, so I made some changes in accordance to what people were suggesting. I did away with the hard coded file, and replaced it with standard input. Now, my real focus is:
-Making sure that I'm using array-lists in conjunction with the methods correctly,
-Making sure that I'm correctly able to apply those to standard deviation
Here is my new code:

import java.io.*;
import java.util.*;
/**
 * Read from a standard input a series of exam scores,    
 * then compute the min, max, avg, med, & stand deviation.
 */
public class DescriptiveStats
{

public DescriptiveStats()
{
    // default constructor
}


public static void main(String[] args) throws IOException
{
    ArrayList<Integer> scores = new ArrayList<Integer>();
    try{
        Scanner input = new Scanner(System.in);
        while(input.hasNextInt())
        {
            scores.add(input.nextInt());
        }
        input.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

    DescriptiveStats stat = new DescriptiveStats();
    System.out.println("Min = " + stat.getMin(scores));
    System.out.println("Max = " + stat.getMax(scores));
    System.out.println("Median = " + stat.getMedian(scores));
    System.out.println("Mean = " + stat.getMean(scores));
    int Mean = stat.getMean(scores);
    //System.out.println("Standard Deviation = " + stat.getStandardDev(scores, Mean));
}


public int getMin(ArrayList<Integer> lst)
{
    int min = 0;
    int d = 0;
    for(int i=0;i<lst.size();i++)
    {                         
        d = lst.get(i);
        if(min>d)
        {
            min=d;
        }
    }
    return min;
}

public int getMax(ArrayList<Integer> lst)
{
    int max = lst.get(0);
    for(int i=0;i<lst.size();i++)
    {
        if(max<lst.get(i))
        max=lst.get(i);
    }
    return max;
}

public int getMedian(ArrayList<Integer> lst)
{
    Collections.sort(lst);
    int middle = lst.size()/2;
    if(lst.size()%2==1)
    {
        return lst.get(middle);
    }
    return (lst.get(middle-1) + lst.get(middle));
}


public int getMean(ArrayList<Integer> lst)
{
    Collections.sort(lst);
    int mean = 0;
    int sum = 0;
    int count = 0;
    for(int i=0;i>lst.size();i++)
    {
        sum = sum + lst.get(i);
        count++;
    }
    mean = sum/count;
    return mean;
}
/**
public int getStandardDev(ArrayList lst, int m)
{
    int mean = m;
    int [] array = lst;
    int total = 0;
    for(int i =0; i < array.length; i++)
    {
        int result = array[i]-mean;
        int [] all = Math.pow(result, 2);

    }
    total = result/array.length;
    int standev = Math.sqrt(total);
    return standev;
}**/

}

As you can see, the standard deviation method and its reference in the main method are made into comments. I haven't tried to convert those to array lists yet, since I'm not sure I did the right thing to the others.

Finally, When I run what I have, the compiler doesn't return any errors. Instead, It just hangs, probably having crashed. I'm not sure why. When I use the 'void main(String[] args' option in BlueJ, I submit the name of the text file(Which is in the project directory. theres even one in the main directory just in case that's what's being referenced.

Thank you all.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文