Average, Standard Deviation, and mode from text file with integers - java

I need help on my program which takes calculates the average, standard deviation, and mode from a number of integers less than or equal to 1,000 in a text file. My program compiles, however, I end up with "null" as my output for both standard deviation and average, and "-1" for my mode.
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Statistics
{
/**default constructor for Statistics class*/
private static int [] unmodifiedNumbers, numbers;
public Statistics()
{
unmodifiedNumbers = new int [1000];
}
/**reads numbers from files and puts them into an array*/
public void readFromFile()
{
try
{
Scanner in = new Scanner(new File("numbers.txt"));
int x;
for(x = 0; in.hasNextInt(); x++)
unmodifiedNumbers[x] = in.nextInt();
numbers = new int [x];
for(int y = 0; y < x; y++)
numbers[y] = unmodifiedNumbers[y];
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
/**calculates and returns and prints average*/
public static double avg()
{
double average = 0;
try
{
Scanner in = new Scanner(new File("numbers.txt"));
double total = 0;
for(int x = 0; x < numbers.length; x++)
total += x;
average = (double)total/numbers.length;
System.out.println(average);
}
catch(Exception c)
{
System.out.println(c.getMessage());
}
return average;
}
/**calculates and displays mode*/
public static void mode()
{
int count = 0, mode = -1, maxCount = 0;
try
{
count = 0;
Scanner in = new Scanner(new File("numbers.txt"));
for(int x = 0; x < numbers.length; x++)
{
for(int y = 0; y < numbers.length; y++)
if(numbers[y] == numbers[x])
count++;
if(count > maxCount)
{
mode = numbers[x];
maxCount = count;
}
}
}
catch(Exception b)
{
System.out.println(b.getMessage());
}
System.out.println(mode);
}
/**calculates and displays standard deviation*/
public static void stddev()
{
double stddev = 0;
long total = 0;
double average = avg();
try
{
Scanner in = new Scanner(new File("numbers.txt"));
for(int x = 0; x < numbers.length; x++)
total += Math.pow((average - numbers[x]), 2);
System.out.println(Math.sqrt((double)total/(numbers.length - 1)));
}
catch(Exception d)
{
System.out.println(d.getMessage());
}
System.out.println(stddev);
}
}

I have made some changes to your code to test it, and make it work:
First I add a main to test:
public static void main(String args[]){
readFromFile();
avg();
mode();
stddev();
}
You can see that I call to readFromFile.
Because of that, I change readFromFile to be static.
/**reads numbers from files and puts them into an array*/
public static void readFromFile()
And I change this:
/**default constructor for Statistics class*/
private static int [] unmodifiedNumbers = new int [1000], numbers;
To initialize unmodifiedNumbers
Now it works.

Related

Program ignoring the last row in the file in calculation

I have a text file with data that looks like this (TestData.txt):
Name|Test1|Test2|Test3|Test4|Test5|Test6|Test7|Test8|Test9|Test10
John Smith|82|89|90|78|89|96|75|88|90|96
Jane Doe|90|92|93|90|89|84|97|91|87|91
Joseph Cruz|68|74|78|81|79|86|80|81|82|87
Suzanne Nguyen|79|83|85|89|81|79|86|92|87|88
Richard Perez|100|84|73|81|92|84|95|96|95|100
Ivan Dyer|77|91|90|75|97|94|76|89|90|92
Craig Palmer|91|84|98|89|82|75|78|96|100|97
Madeline Rogers|75|79|78|93|91|76|80|88|100|81
Chelsea Roxas|87|94|89|96|95|85|88|92|86|86
Jasper Bautista|100|83|93|100|98|97|96|97|97|98
Tyler Perez|82|89|90|78|89|96|75|88|90|96
My code parses the file and does some calculations with it.
However, in the method arrangeList() within which calls another method called getTestAvg() (calculates column means), the program ignores Tyler Perez's scores.
I noticed that the results I am getting were inaccurate so I went and printed the whole 2d array with all the test scores and the last column is nowhere to be found.
My entire code is below and I hope someone could point out what causes this.
I keep getting an IndexOutOfBounds error whenever I try to switch N (# of students) and M (# of tests) to see what happens. At first, I have 10 students and 10 tests, and all the calculations were correct, but when I added another student, the calculations became inaccurate.
I apologize in advance if my code isn't as well-designed as I'm not an experienced programmer.
import java.util.*;
import java.io.*;
public class TestAverages
{
private static int[] grades;
private static int[] testTotal;
private static int N;
private static double classTotal;
private static int M;
public static void main(String[] args) throws FileNotFoundException
{
File input = new File("TestData.txt");
Scanner in = new Scanner(input);
parseFile(in);
}
public static void parseFile(Scanner in) throws FileNotFoundException
{
TestAverages t = new TestAverages();
in.nextLine();
double total = 0.0;
ArrayList<Double> testScores = new ArrayList<Double>();
int index = 0;
while(in.hasNextLine())
{
String line = in.nextLine();
String[] data = line.split("\\|");
String name = data[0];
grades = new int[data.length - 1];
N = grades.length;
for(int i = 0; i < N; i++){
grades[i] = Integer.parseInt(data[i + 1]);
testScores.add((double)grades[i]);
}
System.out.println(name + "\t");
System.out.println("Student Average: " + t.getStudentAvg(grades) + "%\n");
total += t.getStudentAvg(grades);
M++;
}
t.arrangeList(testScores);
System.out.printf("\nClass Average: %.1f%%\n", t.getClassAvg(total));
}
public double getStudentAvg(int[] grades)
{
double total = 0.0;
double avg = 0.0;
int N = grades.length;
for(int i = 0; i < N; i++){
total += grades[i];}
avg = total / N;
return avg;
}
public double getClassAvg(double total)
{
double classAvg = total / M;
return classAvg;
}
public double[][] arrangeList(ArrayList testScores)
{
double[][] tests = new double[N][N];
int len = tests.length;
for(int i = 0; i < len; i++)
{
for(int j = 0; j < len; j++)
{
tests[i][j] = (Double) testScores.get(i*N + j);
}
}
for(int i = 0; i < len; i++)
{
double avg = getTestAvg(tests, i);
System.out.printf("\nTest " + (i + 1) + " Average: %.1f%%\n", avg);
}
return tests;
}
public double getTestAvg(double[][] testScores, int index)
{
double testAvg = 0.0;
for(int i = 0; i < N; i++)
{
testAvg += testScores[i][index];
}
return testAvg / N;
}
}
Here are the numbers I'm supposed to be getting (top) compared to what my program outputs (bottom).
As the other responses already stated, you had quite the issue with your variables and loops. I now changed N to # of students and M to # of tests to be as you stated in your question.
Next time, maybe try to improve your variable naming, so you don't get confused. (e.g. switch out n and m for s (students) and t (tests), if you like your variable names short).
This should work now. Just check against your code to see the changes.
import java.util.*;
import java.io.*;
public class TestAverages {
private static int[] grades;
private static int n = 0; // amount of students
private static int m; // amount of tests
public static void main(String[] args) throws FileNotFoundException {
File input = new File("TestData.txt");
Scanner in = new Scanner(input);
parseFile(in);
}
public static void parseFile(Scanner in) throws FileNotFoundException {
TestAverages t = new TestAverages();
in.nextLine();
double total = 0.0;
ArrayList<Double> testScores = new ArrayList<Double>();
while (in.hasNextLine()) {
String line = in.nextLine();
String[] data = line.split("\\|");
String name = data[0];
grades = new int[data.length - 1];
m = grades.length;
for (int i = 0; i < m; i++) {
grades[i] = Integer.parseInt(data[i + 1]);
testScores.add((double) grades[i]);
}
System.out.println(name + "\t");
System.out.println("Student Average: " + t.getStudentAvg(grades) + "%\n");
total += t.getStudentAvg(grades);
n++;
}
t.arrangeList(testScores);
System.out.printf("\nClass Average: %.1f%%\n", t.getClassAvg(total));
}
public double getStudentAvg(int[] grades) {
double total = 0.0;
double avg = 0.0;
for (int i = 0; i < grades.length; i++) {
total += grades[i];
}
avg = total / grades.length;
return avg;
}
public double getClassAvg(double total) {
double classAvg = total / n;
return classAvg;
}
public double[][] arrangeList(ArrayList<Double> testScores) {
double[][] tests = new double[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
tests[i][j] = (Double) testScores.get(i * m + j);
}
}
for (int i = 0; i < m; i++) {
double avg = getTestAvg(tests, i);
System.out.printf("\nTest " + (i + 1) + " Average: %.1f%%\n", avg);
}
return tests;
}
public double getTestAvg(double[][] testScores, int index) {
double testAvg = 0.0;
for (int i = 0; i < n; i++) {
testAvg += testScores[i][index];
}
return testAvg / n;
}
}
You need to account for the different sizes. I think you want primarily the number of TESTS (not students), but you can't just use len for both index bounds.
double[][] tests = new double[N][M];
for(int i = 0; i < N; i++)
{
for(int j = 0; j < M; j++)
{
tests[i][j] = (Double) testScores.get(i*N + j);
}
}
Note that it didn't just resize the array, but it changed the loop conditions to loop the proper amount for inner and outer loop.
In the line
double[][] tests = new double[N][N];
of function arrangeList
you make your test array as N X N.
I believe youh should do something like
double[][] tests = new double[M][N];
It's just a suggestion as in your code it seems M = number of students and N = number of tests, differently from what you write in your question.
In general you should review all the method arrangeList and probably getTestAvg too (loop on N, instead of M), as the loops on variable len are intended for a N X N array, which is not the case.

java, counting Standard Deviation. stuck in my last code

public int deviasi(){
//sum
int jumlah=0;
for (int i=0; i<banyak; i++){
jumlah = jumlah+nilai[i];
}
//mean
int rata2;
rata2=jumlah/banyak;
//menghitung deviasi
double deviasi = 0;
for (int i=0;i<banyak;i++){
deviasi += Math.pow(nilai[i] - rata2,2);
}
return
Math.sqrt (deviasi/banyak);
}
i got error in my last code. it told me the problem because of different data type between deviasi and banyak. but, i've changed the data type to make them have the same data type. but the error warning still told me the problem because of different data type between deviasi and banyak. i got stuck. T_T
Like mentioned in comments you need to work with double as variable type
public class StandDev {
public double standardDevioation(int[] numbers){
int count = numbers.length;
double sum = 0.0;
for (int i = 0; i < count; i++){
sum += numbers[i];
}
double mean = sum / count;
double sumDiff = 0.0;
for (int i = 0; i< count; i++){
sumDiff += Math.pow(numbers[i] - mean,2);
}
return Math.sqrt (sumDiff/count);
}
public static void main(String[] args) {
int[] numbers = {-5, 1, 8, 7, 2};
StandDev standDev = new StandDev();
System.out.println(standDev.standardDevioation(numbers));
}
}
// Code returns 3.7549966711037173
public class Devs {
public static double deviasi(){
//sum
int jumlah= 0;
int[] nilai = {4,7,6,3,9,12,11,12,12,15};
int banyak = 10;
for (int i=0; i<banyak; i++){
jumlah += nilai[i];
}
//mean
int rata2;
rata2=jumlah/banyak;
//menghitung deviasi
double deviasi = 0;
for (int i=0;i<banyak;i++){
deviasi += Math.pow(nilai[i] - rata2,2);
}
return Math.sqrt (deviasi/banyak);
}
public static void main(String args[]) {
System.out.println(deviasi());
}
}

Incompatible types: double[][] can not be converted to double

I am trying to resolve an issue for this assignment I was given for Homework. I am currently stuck and would appreciate any help that could guide me in correcting the program.
The original assignment is as follows:
Write a program that uses a two-dimensional array to store the highest and lowest temperatures for each month of the year. Write two methods : one to calculate and return the average high and one to calculate and return the average low of the year. Your program should output all the values in the array and then output the average high and the average low.
This is the code I have assembled so far and have an error that I am not able to resolve. It is " incompatible types: converting double[][] cannot be converted to double. The lines in question are Line 8, and Line 110 ( the last return in the program).
import java.util.*;
public class Weather
{
public static void main(String[] args)
{
double[][] tempData = getData();
printTempData(tempData);
double avgHigh = averageHigh(tempData);
double avgLow = averageLow(tempData);
int indexHigh = indexHighTemp(tempData);
int indexLow= indexLowTemp(tempData);
System.out.format("The average high temperature is %4.1f%n", avgHigh);
System.out.format("The average low temperature is %4.1f%n", avgLow);
System.out.format("The index of high temperature is %2d%n", indexHigh);
System.out.format("The index of low temperature is %2d%n", indexLow);
}
private static void printTempData(double[][] tempData)
{
System.out.format("%6s:%4s%4s%4s%4s%4s%4s%4s%4s%4s%4s%4s%4s%n","Month","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
System.out.format("%6s:","Low");
for (int i = 0; i < tempData[0].length;i++)
{
System.out.format("%4.1s", tempData[0][i]);
}
System.out.format("%n");
System.out.format("%6s: ","High");
for (int i = 0; i < tempData[1].length; i++)
{
System.out.format("%4.1f", tempData[1][i]);
}
System.out.format("%n");
}
private static int indexLowTemp(double[][] tempData)
{
int index = 0;
double temp = tempData[0][0];
for (int i = 0; i < tempData[0].length; i++)
{
if (temp > tempData[0][i])
{
temp = tempData[0][i];
index = i;
}
}
return index +1;
}
private static int indexHighTemp(double[][] tempData)
{
int index = 0;
double temp = tempData[1][0];
for(int i = 0; i< tempData[1].length; i++)
{
if ( temp < tempData[1][i])
{
temp = tempData[1][i];
index = i;
}
}
return index + 1;
}
private static double averageHigh(double[][] tempData)
{
double avg = 0.0;
for(int i=0; i < tempData[0].length; i++)
{
avg += tempData[0][i];
}
avg /= tempData[0].length;
return avg;
}
private static double averageLow(double[][] tempData)
{
double avg = 0.0;
for(int i=0; i > tempData[1].length; i++)
{
avg += tempData[0][i];
}
avg /= tempData[0].length;
return avg;
}
private static double getData()
{
double[][] tempData = new double[2][12];
Random r = new Random();
for (int j = 0; j < tempData[0].length; j++)
{
tempData[0][j] = 30 + Math.sqrt(j) - r.nextDouble();
tempData[1][j] = 30 + Math.sqrt(j) + r.nextDouble();
}
return tempData;
}
}
Your method private static double getData() should be private static double[][] getData()
You already declared an array
double[][] tempData = getData();
but you are trying to call
private static double getData()
thus the error "converting double[][] cannot be converted to double."
Hence change to
private static double[][] getData()
The method should be private static double[][] getData()

Java- Simple Neural Network Implementation not working

I'm trying to implement a neural network with:
5 input nodes(+1 bias)
1 hidden layer of 1 hidden node(+1 bias)
1 output unit.
The training data I'm using is the a disjunction of 5 input units. The Overall Error is oscillating instead of decreasing and reaching very high numbers.
package neuralnetworks;
import java.io.File;
import java.io.FileNotFoundException;
import java.math.*;
import java.util.Random;
import java.util.Scanner;
public class NeuralNetworks {
private double[] weightslayer1;
private double[] weightslayer2;
private int[][] training;
public NeuralNetworks(int inputLayerSize, int weights1, int weights2) {
weightslayer1 = new double[weights1];
weightslayer2 = new double[weights2];
}
public static int[][] readCSV() {
Scanner readfile = null;
try {
readfile = new Scanner(new File("disjunction.csv"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner delimit;
int[][] train = new int[32][6];
int lines = 0;
while (readfile.hasNext()) {
String line = readfile.nextLine();
delimit = new Scanner(line);
delimit.useDelimiter(",");
int features = 0;
while (delimit.hasNext() && lines > 0) {
train[lines - 1][features] = Integer.parseInt(delimit.next());
features++;
}
lines++;
}
return train;
}
public double linearcomb(double[] input, double[] weights) { //calculates the sum of the multiplication of weights and inputs
double sigma = 0;
for (int i = 0; i < input.length; i++) {
sigma += (input[i] * weights[i]);
}
return sigma;
}
public double hiddenLayerOutput(int[] inputs) { //calculates the output of the hiddenlayer
double[] formattedInput = new double[6]; //adds the bias unit
formattedInput[0] = 1;
for (int i = 1; i < formattedInput.length; i++)
formattedInput[i] = inputs[i - 1];
double hlOutput = linearcomb(formattedInput, weightslayer1);
return hlOutput;
}
public double feedForward(int[] inputs) { //calculates the output
double hlOutput = hiddenLayerOutput(inputs);
double[] olInput = new double[2];
olInput[0] = 1;
olInput[1] = hlOutput;
double output = linearcomb(olInput, weightslayer2);
return output;
}
public void backprop(double predoutput, double targetout, double hidout, double learningrate, int[] input) {
double outputdelta = predoutput * (1 - predoutput) * (targetout - predoutput);
double hiddendelta = hidout * (1 - hidout) * (outputdelta * weightslayer2[1]);
updateweights(learningrate, outputdelta, hiddendelta, input);
}
public void updateweights(double learningrate, double outputdelta, double hiddendelta, int[] input) {
for (int i = 0; i < weightslayer1.length; i++) {
double deltaw1 = learningrate * hiddendelta * input[i];
weightslayer1[i] += deltaw1;
}
for (int i = 0; i < weightslayer2.length; i++) {
double deltaw2 = learningrate * outputdelta * hiddenLayerOutput(input);
weightslayer2[i] += deltaw2;
}
}
public double test(int[] inputs) {
return feedForward(inputs);
}
public void train() {
double learningrate = 0.01;
double output;
double hiddenoutput;
double error = 100;
do {
error = 0;
for (int i = 0; i < training.length; i++) {
output = feedForward(training[i]);
error += (training[i][5] - output) * (training[i][5] - output) / 2;
hiddenoutput = hiddenLayerOutput(training[i]);
backprop(output, training[i][5], hiddenoutput, learningrate, training[i]);
}
//System.out.println(error);
}while(error>1);
}
public static void main(String[] args) {
NeuralNetworks nn = new NeuralNetworks(6, 6, 2);
Random rand = new Random();
nn.weightslayer2[0] = (rand.nextDouble() - 0.5);
nn.weightslayer2[1] = (rand.nextDouble() - 0.5);
for (int i = 0; i < nn.weightslayer1.length; i++)
nn.weightslayer1[i] = (rand.nextDouble() - 0.5);
nn.training = readCSV();
/*for (int i = 0; i < nn.training.length; i++) {
for (int j = 0; j < nn.training[i].length; j++)
System.out.print(nn.training[i][j] + ",");
System.out.println();
}*/
nn.train();
int[] testa = { 0, 0, 0, 0, 0 };
System.out.println(nn.test(testa));
}
}

I don't understand the specific variable type or type of utilization I should have when trying to get this array issue to work

I'm trying to get num to create multiple scenarios and get 10 inputed variables from the user which I will then utilize to print out. Once the variables are printed out I need to average them but I got stuck. Could you give me some tips?
final static int num = 10;
static Scanner scan = new Scanner(System.in);
public static void main (String[]args)
{
int[] list = new int [num];
for(int i = 0; i<=num; i++)
{
System.out.println("Enter an integer");
int num[] = scan.nextInt();
}
System.out.println(Print_it(list) / 10);
}
public static double Print_it(int[] list)
{
int number = 0;
for (int i = 0; i<10; i++)
{
number = number + list[i];
}
return(number);
}
The for loops should be using the correct test. 'i<=num' will cause an exception when i == num.
The "int num[] = scan.nextInt()" statement has illegal syntax.
You should be using 'num' wherever you currently use 10, and it should be named 'NUM' to conform to standard Java naming conventions for constants.
Print_it (which should be named more like 'printIt') is not printing anything.
Here is a better implementation:
import java.util.Scanner;
public class Main {
final static int NUM = 10;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
final int[] list = new int[NUM];
for (int i = 0; i < NUM; i++) {
System.out.println("Enter an integer");
list[i] = scan.nextInt();
}
printIt(list);
}
public static void printIt(int[] list) {
final int length = list.length;
int total = 0;
for (int i = 0; i < length; i++) {
final int n = list[i];
System.out.println(n);
total += n;
}
System.out.println("Average: " + (double)total / length);
}
}

Categories