Emergency!: I need help with java!

HegemonKhan
Emergency!: I need help with java school work!

I only got until 12 noon (pacific time: aka: california's time zone) tues, 9-22-15, to get it done

here's the assignment:

You will write a program that reads integer values from a file named 'input.txt' 
All the integers will be on one line in the file, however the number of integers in the file may
vary.
Your program must contain the following two methods in addition to main
These should be public static methods that return double
•computeMean
• accepts a filename
• returns a double value
• The mean is computed by averaging all the integers in the input file; return this value
•computeStandardDeviation
• accepts a filename and a double value (the mean)
• computes and returns the double value that is the standard deviation
Standard Deviation is defined as (see p461 in the text, problem 15):
The square root of the average of the sum of the squared differences from the mean
Example, if you have 3 integers, with a mean of 2.5, compute as follows:
stdDev = sqrt( ( (n1 - 2.5)^2 + (n2 - 2.5)^2 + (n3 - 2.5)^2 ) / 3 )
Output:
Your program should print the numbers in the input file
Then print the mean, to 2 decimal places
Then print the standard deviation, to 2 decimal places
Example, input.txt contains 1 2 3 4 5, output is
Input: 1 2 3 4 5
Mean: 3.00
StdDev: 1.41
Example, input.txt contains 8 5 29 20 100 33 292, output is
Input: 8 5 29 20 100 33 292
Mean: 69.57
StdDev: 95.47

• You must use the output of the 'computeMean' function as the input mean value for the
'computeStandardDeviation' function (-2pts)
• You should read the file completely inside each of the functions
• this will result in a total of 3 file reads (one in the 'main' method, one each in the
computeMean and computeStandardDeviation method)
• You must use create and use the computeMean and computeStandardDeviation
methods, if you do all your work in 'main' you will get 0 points
• Console output ONLY happens in main
• do not print out to the console inside of the computeMean or
computeStandardDeviation methods (-1pt per method)


and here's what I've done:

(I don't know java well at all, as can see from all of my errors, sighs, and thus I don't know how, what, or even where to research~look, for how to deal with them. Is my program close to working (just have stupid errors to take care of: the program is logically~functionally fine otherwise), or am I completely off in my design of my program with using java? I really don't yet understand how java programs are structured, as it's very different to what limited coding I know)

// program header info:

// Program Purpose:

// Packages~Libraries~Modules:

import java.util.Scanner;
import java.io.FileReader;
import java.io.File;
import java.io.FileNotFoundException;

public class Lab04
{
// Class-Global Constants ~ Variables ~ Object Instantiation:

static Scanner console = new Scanner(System.in);

static double mean, standard_deviation;

static String file_data, file_name;

// Methods~Functions:

public static void main(String[] args) throws FileNotFoundException
{
// Local Variable Definitions ~ Initializations ~ Object Instantiating:

// program:

Header();
Purpose();
Program();
}

public static void Header()
{
// Header Info Displayment:

System.out.println("\n\n****************************************" +
"****************************************");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("****************************************" +
"****************************************\n\n");
}

public static void Purpose()
{
// Purpose Displayment:

System.out.println("xxx purpose xxx\n\n");
}

public static void Program() throws FileNotFoundException
{
// Local Variable Definitions ~ Initializations ~ Object Instantiating:

Scanner read_file = new Scanner(new FileReader("input.txt"));

// just for segmenting these file prompts from rest of program:

System.out.println("----------------------------------------" +
"----------------------------------------\n\n");

// prompting the user that the 'input.txt' file is opened, and being
// read by the program:

System.out.println("The \'input.txt\' file has been opened, and is " +
"being read by the program.\n\n");

// Get, Concatenate~Compute, and return new file data values, storing
// them into variables for the later-on displayment:

file_data = Concatenate_File_Data(read_file);

if (file_data != null)
{
mean = Compute_Mean(read_file);
standard_deviation = Compute_Standard_Deviation(read_file, mean);
}

// close the 'input.txt' File:

read_file.close();

// prompt the user that the 'input.txt' file has been closed:

System.out.println("The \'input.txt\' file's data has been read and \n"
+ "stored, and the file has been closed.\n\n");

// no simple way of clearing the console screen with java, so I am just
// separating the file prompts from actual stock ticker program:

System.out.println("----------------------------------------" +
"----------------------------------------\n\n");

// quick local variable to get the file name:
// (for the immediate next code lines' usage)

file_name = read_file.getName();

// checking+correcting variables for their displaying of the results,
// and the displayment of the results:

if (file_data == null)
{
System.out.printf("%s contains:%nInput: null (The file has no " +
"integer data that this program requires)%nMean: null%nStandard"
+ " Deviation: null%n%n", file_name);
}
else if (((mean == 0)||(mean >= 0))&&(standard_deviation == -1))
{
System.out.printf("%s contains:%nInput: %s%nMean: %.2f%nStandard "
+ "Deviation: (Error: imaginary numbers: square root of " +
"negative number)%n%n", file_name, file_data, mean,
standard_deviation);
}
else
{
System.out.printf("%s contains:%nInput: %s%nMean: %.2f%nStandard "
+ "Deviation: %.2f%n%n", file_name, file_data, mean,
standard_deviation);
}
}

public static String Concatenate_File_Data(read_file_parameter)
{
String local_string = read_file_parameter.hasNext();

if (!read_file_parameter.hasNext())
{
return (null);
}
else
{
while (read_file_parameter.hasNext())
{
local_string +=
(" " + String.valueOf(read_file_parameter.nextInt()));
}
return(local_string);
}
}

public static double Compute_Mean(read_file_parameter)
{
int local_sum = 0, local_counter = 1;

while (read_file_parameter.hasNext())
{
file_data += String.valueOf(read_file_parameter.nextInt());
local_sum += read_file_parameter.nextInt();
local_counter++;
}

if (local_sum == 0)
{
return(0);
}
else
{
return((double)(local_sum)/(double)(local_counter));
}
}

public static double Compute_Standard_Deviation(read_file_parameter,
mean_parameter)
{
double local_sum = 0.0;
int local_counter = 1;

for (local_counter; read_file_parameter.hasNext(); local_counter++)
{
local_sum += pow(((double)(read_file_parameter.hasNext()) -
mean_parameter), 2.0);
}

if (local_sum > 0)
{
return(sqrt((local_sum)/(double)(local_counter)));
}
else if (local_sum == 0)
{
return (0);
}
else
{
return (-1);
}
}
}


if anyone knows java well, any help today or tomarrow, would be greatly appreciated!

Pertex
Hmm, first try to use the camelcase notation for method names and variables - "concatenateFileData" instead of "Concatenate_File_Data"

You try to read all numbers from the file into a string
file_data = Concatenate_File_Data(read_file);


After that all numbers should be in the variable file_data (camelcase: fileData)
But after that you don't work with that string. You try to read the values from the file in computeMean and computeStandardDeviation again. fileData is never used again, so it is useless.

Here is the beginning of the method program as I would do it. It works with a double array.


public static void program() throws FileNotFoundException {

final String fileName = "c:\\temp\\input.txt";

Scanner readFile = new Scanner(new FileReader(fileName));
if (readFile ==null){
return;
}
String fileData = null;
if (readFile.hasNext()) {
fileData = readFile.nextLine();
}
readFile.close();

if (fileData != null) {
String[] values = StringUtils.split(fileData);
if (values == null){
return;
}
double[] numbers = new double[values.length];
for (int i = 0; i < numbers.length; i++) {
numbers[i] = Double.parseDouble(values[i]);
}
mean = computeMean(numbers);
standardDeviation = computeStandardDeviation(numbers, mean);
}

...

public static double computeMean(final double[] numbers) {
double sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return sum / numbers.length;
}

HegemonKhan
thank you very much Pertex for the rush help! I was desparate, as I was having a huge problem with troubleshooting all of my errors, so hoped I could get some help in time before assignment due, from anyone here, so thank you very much Pertex!

I got some help from a class~school mate and my java teacher, and I eventually got my program to work. Most of my mistakes were simple-stupid syntax, as I've not learned how to do them correctly yet, had to do a lot of research (which I now understand better how to look up the errors in the oracle java doc~resource).

I didn't define my Parameters, I got confused with how to do the Type Casting (Data Type Conversions), I used 'hasInt' where I was to use 'nextInt', and I was confused how to work with the Scanner File Object (didn't know what defining to do with it for my parameter variable for it, I tried 'string'... didn't know it was, the Class itself: Scanner), I think that was most of my syntax errors... Oh ya, I couldn't get the 'pow' and 'sqrt' to work... (you can see my comments in my post program below about this, if interested).

I then had some logic errors, I had to take care of...

and the big logic error was that I was getting '0' returned-displayed for my 'mean' and 'standard deviation', and it took me literally plugging in 'msg' [Java: System.out.print("HK_1......99"); ] everwhere to figure it out... as I looked and looked, totally baffled at why I was getting the zeroes.

the cause was that the Scanner was at the EoF (End of File)... so when it went to do the 'mean' and 'standard deviation' functions... there was no 'hasNext' (=true), so my 'mean' and 'standard deviation' functions were not running, thus the ' mean ' and 'standard deviation ' were still as their initial values of 0.

then, I had a small logic error with the mean and std dev functions, in using initial counter at 1 and counter++, when I needed to use counter at 0 and ++counter .... I hope anyways that my mean and standard dev are working correctly now... I hate math... I've no idea if my std dev is working right or not, laughs. I don't even know what standard deviation is, heh.

anyways, here's my working program:

// Packages~Libraries~Modules:

import java.util.Scanner;
import java.io.FileReader;
import java.io.FileNotFoundException;

import static java.lang.Math.pow; // this is for only needing to use ' pow() '
import static java.lang.Math.sqrt; // this is for only needing to use ' sqrt() '

// otherwise, I have to use ' Class_name.Function_name '
// aka for this case: ' Math.pow() ' and ' Math.sqrt() '
// the ' Math ' Class is apart of the ' lang ' package,
// which is auto-imported by the java program already

// Classes:

public class Lab04
{
// Class-Global Constants ~ Variables ~ Object Instantiation:

static Scanner console = new Scanner(System.in);

static double mean, standard_deviation;

static String file_data;

static final String file_name = "input.txt";

// Methods~Functions:

public static void main(String[] args) throws FileNotFoundException
{
Header();
Crediting_Helpers();
Purpose();
Program();
}

public static void Header()
{
// Header Info Displayment:
}

public static void Crediting_Helpers()
{
// Crediting Helpers Displayment:
}

public static void Purpose()
{
// Purpose Displayment:

System.out.println("The purpose of this program is to get input values "
+ "from a file and \ncalculate the mean and standard deviation, and"
+ " displaying the results \nto the user.\n\n");
}

public static void Program() throws FileNotFoundException
{
// Local Variable Definitions ~ Initializations ~ Object Instantiating:

Scanner read_file = new Scanner(new FileReader("input.txt"));

// just for segmenting these file prompts from rest of program:

System.out.println("----------------------------------------" +
"----------------------------------------\n\n");

// prompting the user that the 'input.txt' file is opened, and being
// read by the program:

System.out.println("The \'input.txt\' file has been opened, and is " +
"being read by the program.\n\n");

// Get, Concatenate~Compute, and return new file data values, storing
// them into variables for the later-on displayment:

file_data = Concatenate_File_Data(read_file);

// close the 'input.txt' File (due to being at the end of the file):

read_file.close();

if (file_data != null)
{
// re-create it, as now it's back to the beginning of file

Scanner read_file_again = new Scanner(new FileReader("input.txt"));

mean = Compute_Mean(read_file_again);

// close the 'input.txt' File (due to being at the end of the file):

read_file_again.close();

// re-create it, as now it's back to the beginning of file

Scanner read_file_again_again =
new Scanner(new FileReader("input.txt"));

standard_deviation =
Compute_Standard_Deviation(read_file_again_again, mean);

// close the 'input.txt' File:

read_file_again_again.close();
}

// prompt the user that the 'input.txt' file has been closed:

System.out.println("The \'input.txt\' file's data has been read and \n"
+ "stored, and the file has been closed.\n\n");

// no simple way of clearing the console screen with java, so I am just
// separating the file prompts from actual stock ticker program:

System.out.println("----------------------------------------" +
"----------------------------------------\n\n");

// checking+correcting variables for their displaying of the results,
// and the displayment of the results:

if (file_data == null)
{
System.out.printf("%s contains:%nInput: null (The file has no " +
"integer data that this program requires)%nMean: null%nStandard"
+ " Deviation: null%n%n", file_name);
}
else if (((mean == 0.0)||(mean >= 0.0))&&(standard_deviation == -1))
{
System.out.printf("%s contains:%nInput: %s%nMean: %.2f%nStandard "
+ "Deviation: (Error: imaginary numbers: square root of " +
"negative number)%n%n", file_name, file_data, mean,
standard_deviation);
}
else
{
System.out.printf("%s contains:%nInput: %s%nMean: %.2f%nStandard "
+ "Deviation: %.2f%n%n", file_name, file_data, mean,
standard_deviation);
}
}

public static String Concatenate_File_Data(Scanner read_file_parameter)
{
if (!read_file_parameter.hasNextInt())
{
return (null);
}
else
{
String local_string = String.valueOf(read_file_parameter.nextInt());

while (read_file_parameter.hasNextInt())
{
local_string +=
(" " + String.valueOf(read_file_parameter.nextInt()));
}
return(local_string);
}
}

public static double Compute_Mean(Scanner read_file_parameter)
{
int local_sum = 0, local_counter = 0;

while (read_file_parameter.hasNextInt())
{
local_sum += read_file_parameter.nextInt();
++local_counter;
}

if (local_sum == 0)
{
return((double)(local_sum));
}
else
{
return((double)(local_sum)/(double)(local_counter));
}
}

public static double Compute_Standard_Deviation(Scanner read_file_parameter,
double mean_parameter)
{
double local_sum = 0.0;
int local_counter = 0;

while (read_file_parameter.hasNextInt())
{
local_sum += Math.pow((double)(read_file_parameter.nextInt()) -
mean_parameter, 2.0);
++local_counter;
}

if (local_sum > 0.0)
{
return(Math.sqrt(local_sum/(double)(local_counter)));
}
else if (local_sum == 0.0)
{
return (local_sum);
}
else
{
return (-1);
}
}
}


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

this may be ignorant, but these languages (C++, Python, and Java), are horrible! Quest's XML~user_level, is so so so so wonderfully easy compared to these 3 languages. Alex and Co. have done such an amazing job with quest! :D

Now having experience with learning other languages, I can emphatically say that using quest to learn to program is much better than in trying to use at least these 3 languages to learn to program! :D

C++ and Python are easier for me, Java is the one I'm having most difficult with, so far. Though the classes are going at different speeds... so it's a bit unfair to compare the 3 languages, as I think we're the furthest into Java material vs the other 2.

This topic is now closed. Topics are closed after 60 days of inactivity.

Support

Forums