Getting 0.0 on NumberAnalyzer.java. Need helps - java

Write a class with a constructor that accepts a file name as its argument. Assume the file contains a series of numbers, each written on a separate line. The class should read the contents of the file into an array, and then displays the following data.
The lowest number in the array
The highest number in the array
The total of the numbers in the array
The average of the numbers in the array.
The file, Numbers.txt used for the above program contains these twelve numbers:
8.71
7.94
3.01
29.27
9.23
82.76
12.6
47.99
63.89
1.09
22.23
79.17
This is the main program: NumberAnalyzerDemo.java
import java.io.*; // Needed for IOException
/**
This program demonstrates a solution to the
Number Analysis Class programming challenge.
*/
public class NumberAnalyzerDemo
{
public static void main(String[] args) throws IOException
{
// Create a NumberAnalyzer object.
NumberAnalyzer na = new NumberAnalyzer("Numbers.txt");
// Display data about the numbers in the file.
System.out.println("The lowest number in the file is " +
na.getLowest());
System.out.println("The highest number in the file is " +
na.getHighest());
System.out.println("The total of the numbers in the file is " +
na.getTotal());
System.out.println("The average of the numbers in the file is " +
na.getAverage());
}
}
This is the class: NumberAnalyzer.java
import java.io.*;
import java.util.Arrays;
import java.util.Scanner;
import java.io.File;
/**
The NumberAnalyzer class is to searching the numbers in a file.
*/
public class NumberAnalyzer
{
private double[] numbers;
private int count;
File file;
Scanner scan;
/**
Constructer that accepts the file name as its argument.
*/
public NumberAnalyzer(String filename) throws IOException
{
count = 0;
file = new File("Numbers.txt");
scan = new Scanner(file);
numbers = new double[11];
}
/**
The getLowest() method to search the file and pull out the lowest
number in the file.
#return Return the lowest number.
*/
public double getLowest()
{
double low = numbers[0];
for (int i = 0; i < numbers.length; i++)
{
if (low > numbers[i])
{
low = numbers[i];
}
}
return low;
}
/**
The getHighest() method to search the file and pull out the highest
number in the file.
#return Return the highest number.
*/
public double getHighest()
{
double high = numbers[0];
for (int i = 0; i < numbers.length; i++)
{
if (high < numbers[i])
{
high = numbers[i];
}
}
return high;
}
/**
This method calculate the total of all the number in the file.
#return Adding all number in the file.
*/
public double getTotal()
{
double total = 0;
for (int i = 0; i < numbers.length; i++)
{
total += numbers[i];
}
return total;
}
/**
This method used to calculate the average of the numbers in the file.
#return Using the getTotal() divided to the length of the numbers.
*/
public double getAverage()
{
return getTotal() / numbers.length;
}
/**
This method to read all the file txt and get the right number.
*/
private void getNumbers(String filename)
{
while(scan.hasNext())
{
numbers[count] = scan.nextDouble();
count++;
}
scan.close();
}
/**
This method
*/
private int getNumberOfValues(String filename)
{
return count ;
}
}
I'm getting 0.0 for all the output. Please give me some suggestions. Thanks!

solution
change you method
private void getNumbers(String filename)
to
public void getNumbers()
and then do
NumberAnalyzer na = new NumberAnalyzer("Numbers.txt");
na.getNumbers();

You're not calling your getNumbers() method, and so haven't populated your numbers[] array.
Just make the call in your constructor, like this:
public NumberAnalyzer(String filename) throws IOException
{
count = 0;
file = new File("Numbers.txt");
scan = new Scanner(file);
numbers = new double[11];
getNumbers();
}
It looks like it doesn't need to have the String argument, so you could remove that, unless you're still planing to implement something with it.

Related

Standard Deviation and Median Takes Long to Load on Big File

I'm running into an issue where both my standard dev. and my median are taking too long to get printed but everything else prints quickly. This only occurs when I have a larger list, I am not understanding the problem, as the numbers are not too large it should fit into both double or integer form, its just not getting displayed at a buttons click like the other values.
Current Code
package Labs;
import java.util.*;
import java.text.DecimalFormat;
/**
*
* #author nick a
*/
public class Practice {
/**
* #param args the command line arguments
*/
private static final DecimalFormat df = new DecimalFormat("0.00");
public static void main(String args[]) {
Double[] dataArray = {16500.0, 304000.0, 384500.0, 431500.0, 681500.0, 348500.0, 282500.0, 327000.0, 182500.0};
List<Double> data = new ArrayList<>(Arrays.asList(dataArray));
System.out.println("StDev Value from list: " + df.format(stdev(data)));
System.out.println("Median Value from list: " + df.format(median(data)));
}
public static double stdev(List<Double>values){
double sumOfDiff = 0;
for(int i = 0; i < values.size(); i++){
sumOfDiff += Math.pow(Math.abs(values.get(i)) - mean(values), 2);
}
double resultant = sumOfDiff/values.size();
return Math.sqrt(resultant);
}
public static double median(List<Double>values){
List<Double>sorted = new ArrayList<>(values);
Collections.sort(sorted);
if(sorted.size() % 2 == 0){
int evenMid = sorted.size()/2;
double sumEven = sorted.get(evenMid-1) + sorted.get(evenMid);
return sumEven/2;
}
int oddMid = (sorted.size()+1)/2;
return sorted.get(oddMid-1);
}
}
The problem happens when the list becomes super large (400,000) entries... I have other things printed out like mean, range, min, max etc. but as soon as its time for standard deviation and median to be printed out it takes its sweet time unlike the rest. How might I fix this?

need assistance with a input issue in java [duplicate]

This question already has answers here:
Error in System.out.println
(5 answers)
Closed 4 years ago.
My Task:
Create a class called Icosahedron which will be used to represent a regular icosahedron, that is a convex polyhedron with 20 equilateral triangles as faces. The class should have the following features:
A private instance variable, edge, of type double, that holds the
edge
length.
A private static variable, count, of type int, that holds the
number of Icosahedron objects that have been created.
A constructor that takes one double argument which specifies the edge length.
An
instance method surface() which returns the surface area of the
icosahedron. This can be calculated using the formula 5*√3 edge².
An
instance method volume() which returns the volume of the icosahedron.
This can be calculated using the formula 5*(3+√5)/12*edge³.
An
instance method toString() which returns a string with the edge
length, surface area and volume as in the example below:
Icosahedron[edge= 3.000, surface= 77.942, volume= 58.906]
The numbers in this string should be in floating point format with a field
that is (at least) 7 characters wide and showing 3 decimal places.
Please use the static method String.format with a suitable formatting
string to achieve this. A static method getCount() which returns the
value of the static variable count.
Finally, add the following main method to your Icosahedron class so that it can be run and tested:
public static void main(String[] args) {
System.out.println("Number of Icosahedron objects created: " + getCount());
Icosahedron[] icos = new Icosahedron[4];
for (int i = 0; i < icos.length; i++)
icos[i] = new Icosahedron(i+1);
for (int i = 0; i < icos.length; i++)
System.out.println(icos[i]);
System.out.println("Number of Icosahedron objects created: " + getCount());
}
Okay. so heres what i have started on:
import java.util.Scanner;
public class Icosahedron {
private double edge = 0;
private int count = 0;
Scanner input = new Scanner(System.in);
double useredge = input.nextDouble();
System.out.println("Enter Edge Length: ");
}
i receive an error on the last line. i cant use println() what am i doing wrong? or maybe im understanding the question wrong? any guidance would be appreciated.
thanks.
Your Icosahedron class should look like the following:
public class Icosahedron {
private double edge;
private int count;
public Icosahedron(int count) {
this.count = count;
}
public double getEdge() {
return edge;
}
public void setEdge(double edge) {
this.edge = edge;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
#Override
public String toString() {
return "Icosahedron{edge=" + edge + ", count=" + count + '}';
}
}
And your class containing the main method (I called it MoreProblem):
import java.util.Scanner;
public class MoreProblem {
public static void main(String[] args) {
Icosahedron[] icos = new Icosahedron[4];
for (int i = 0; i < icos.length; i++) {
icos[i] = new Icosahedron(i+1);
Scanner input = new Scanner(System.in);
System.out.println("Enter Edge Length: ");
double userEdge = input.nextDouble();
icos[i].setEdge(userEdge);
}
for (Icosahedron icosahedron : icos) {
System.out.println(icosahedron);
}
System.out.println("Number of Icosahedron objects created: " + icos.length);
}
}

So my NumberOperations class can't be found?

Here's the code (number operations class is the second listed):
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// declare and instantiate ArrayList with generic type <NumberOperations>
ArrayList<NumberOperations> numOpsList
= new ArrayList<NumberOperations>();
// prompt user for set of numbers
System.out.println("Enter a list of positive integers separated "
+ "with a space followed by 0:");
// get first user input using in.nextInt()
int number = in.nextInt();
// add a while loop as described below:
// while the input is not equal to 0
// add a new NumberOperations object to numOpsList based on user
input
// get the next user input using in.nextInt()
while (number != 0) {
numOpsList.add(new NumberOperations(number));
number = in.nextInt();
}
int index = 0;
while (index < numOpsList.size()) {
NumberOperations num = numOpsList.get(index);
System.out.println("For: " + num);
// add print statement for odds under num
// add print statement for powers of 2 under num
index++;
}
public class NumberOperations {
// instance variables
private int number;
// constructor
/**
* #param numberIn is number
*/
public NumberOperations (int numberIn) {
number = numberIn;
}
// methods
/**
* #return value
*/
public int getValue()
{
return number;
}
public String oddsUnder()
{
String output = "";
int i = 0;
while (i < number) {
if(i % 2 != 0) {
output += i + "\t";
}
i++;
}
return output;
}
public String powersTwoUnder()
{
String output = "";
int powers = 1;
while (powers < number) {
output += powers + "\t";
powers = powers * 2;
}
return output;
}
public int isGreater (int compareNumber)
{
if (number > compareNumber)
{
return 1;
}
else if (number < compareNumber)
{
return -1;
}
else
{
return 0;
}
}
public String toString()
{
String output = "";
return number + "";
}
}
The error I'm getting is that the compiler can't find "NumberOperations" anywhere. Its probably a very rudimentary issue I have, but I'm lost.
Edit: I added the class for numberoperations in case it helps. I thought I did everything right as far as this goes though.
Enter a list of positive integers separated with a space followed by 0:
1 2 3 4 0
For: 1
For: 2
For: 3
For: 4
I decorated the main method with a class
import java.util.*;
public class NumberOperationsTest {
yes, import was left to the helping User, too.
Closed the class just before the class NumberOperations, which I freed from the public declaration, to have it compilable in a single file.
In a different file, the public keyword is fine.
On compilation, you have to tell the classpath, to look in the current directory:
javac -cp . NumberOperationsTest.java

Getting ArrayOutOfBounds and NullPointerException But I don't Know Why

I am testing a program I wrote for an assignment, and right now it's testing at 50% against test cases. I get the following errors when I submit, but I can't figure out why. I tried changing some pieces of code and retesting, but no matter what I do I get the same errors, so I must be completely missing what I should be looking for. Here is the CSV file from which the data is being pulled -
CSV Data File. Here are the errors I get:
Here is my code:
Main class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package csc212hw04;
import java.io.File;
import java.util.Scanner;
/**
*
* #author Michal
*/
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception{
Scanner kb = new Scanner(System.in);
boolean flag = true;
System.out.println("Welcome to the Car Database");
System.out.println("Enter the size of the array:");
int size = Integer.parseInt(kb.nextLine());
CarDatabase db1 = new CarDatabase(size);
System.out.println("Enter the name of the input file:");
String userFile = new String(kb.nextLine());
db1.readFile(userFile);
while (flag) {
System.out.println("Enter make, mpg, weight, all, or quit:");
String command = kb.nextLine();
if (command.equals("make")) {
System.out.println("Enter the make:");
String make = kb.nextLine();
db1.displayMake(make);
} else if (command.equals("mpg")) {
System.out.println("Enter the mpg range:");
double mpgLow = Double.parseDouble(kb.nextLine());
double mpgHigh = Double.parseDouble(kb.nextLine());
db1.mpgRange(mpgLow, mpgHigh);
} else if (command.equals("weight")) {
System.out.println("Enter the weight range:");
double weightLow = Double.parseDouble(kb.next());
double weightHigh = Double.parseDouble(kb.next());
db1.weightRange(weightLow, weightHigh);
} else if (command.equals("all")) {
CarDatabase.displayAll();
} else if (command.equals("quit")) {
flag = false;
}
}
}
}
CarDatabase class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package csc212hw04;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
/**
*
* #author Michal
*/
public class CarDatabase {
private static Car[] database;
public CarDatabase(int s) {
this.database = new Car[s];
}
public boolean isFull() {
boolean full = true;
for (int i = 0; i < database.length; i++) {
if (database[i] == null) {
full = false;
}
}
return full;
}
public static void readFile(String f) throws FileNotFoundException {
File file = new File(f);
int lineNum = 0;
Scanner sc = new Scanner(file);
String csvSplitBy = ",";
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] carData = line.split(csvSplitBy);
String model = carData[0];
String make = carData[1];
double mpg = Double.parseDouble(carData[2]);
int weight = Integer.parseInt(carData[3]);
int year = Integer.parseInt(carData[4]);
database[lineNum] = new Car(model, make, mpg, weight, year);
lineNum++;
}
}
public static void displayMake(String m) {
for (int i = 0; i < database.length; i++) {
if (database[i].make.equals(m)) {
database[i].toString();
}
}
}
public static void mpgRange(double l, double h) {
for (int i = 0; i < database.length; i++) {
if (database[i].mpg >= l && database[i].mpg <= h) {
database[i].toString();
}
}
}
public static void weightRange(double l, double h) {
for (int i = 0; i < database.length; i++) {
if ((database[i].weight >= l) && (database[i].weight <= h)) {
database[i].toString();
}
}
}
public static void displayAll() {
for (int i = 0; i < database.length; i++) {
database[i].toString();
}
}
}
Car class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package csc212hw04;
/**
*
* #author Michal
*/
public class Car {
public String model, make;
public double mpg;
public int weight, year;
public Car(String md, String mk, double umpg, int w, int y) {
model = md;
make = mk;
mpg = umpg;
weight = w;
year = y;
}
public String toString() {
return "Model:" + model + " Make:" + make + " mpg:" + " weight:" + " year:" + year;
}
}
Here is a sample from the CSV file if you cannot see it:
You are probably getting to the End of File and you try to split. The array then doesn't have any value. Make sure there is no blank line at the end of your database, or put a check in your readfile to make sure that if the carData.length == NUMBER OF DATA FIELDS
Update
You also should check to make sure that you don't pass the total number of database entries you have. So do:
while(sc.hasNextLine() && lineNum < database.length) {
ArrayIndexOutOfBoundsException is thrown in very specific circumstances:
Thrown to indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or equal to the
size of the array.
In your code, you assume that each row in your csv has the same number of fields.
You're also assuming that the size of database array matches the number of cars in your file. Since you don't create your database array entries until you read them from the file - but you pre-initialize the size database array, you could end up reading past the end of your database if the number of records in the CSV is larger than the value you initialize for the database size.

Program reads in the contents of a file into an array, and display both the console and write to a file

I am writing a program that prompts the user for a file name. I have to assume that the file contains an integer representing the number of n data values, followed by a series of n floating numbers(which was given to me in a file called RandomFloats), each written on a separate line. This program should read in the contents of the RandomFloats file into an array, and then both display in the console and write to a file the following data: the number of floating point numbers in the array, the lowest and highest number in the array, the total and the average. Here is my code so far(I will put in a comment at the part that is not working)
import java.io.File;
import java.util.*;
public class Problem9 {
/**
* #param args
*/
public static void main(String[] args) {
File rf = new File("RandomFloats");
Scanner kb = new Scanner(rf); //Unhandled exception type FileNotFoundException
double[] numFloats = new double [4268];
for (int i = 0; i < numFloats.length; i++){
numFloats[i] = kb.nextInt();
}
System.out.println("Please enter a file name");
String fileName = kb.nextLine();
minValue (numFloats);
maxValue (numFloats);
totalValue (numFloats);
averageValue (numFloats);
}
public static void minValue (double[] numFloats){
double min = 0;
for(int i = 0; i < numFloats.length; i++){
if (numFloats[i] < min){
min = numFloats[i];
}
}
System.out.println("Min Value: " + min);
}
public static void maxValue (double[] numFloats){
double max = 0;
for(int i = 0; i < numFloats.length; i++){
if (numFloats[i] > max){
max = numFloats[i];
}
}
System.out.println("Max Value: " + max);
}
public static void totalValue (double[] numFloats){
double total = 0;
for (int i = 0; i < numFloats.length; i++){
total += numFloats[i];
}
System.out.printf("\nTotal1: %.1f" , total);
}
public static void averageValue (double[] numFloats){
double total = 0;
double average;
for (int i = 0; i < numFloats.length; i++){
total += numFloats[i];
}
average = total / numFloats.length;
System.out.printf("\nAverage: %.1f" , average);
}
}
I am unsure how to print out the sample size and the file RandomFloats I created isnt being read into the array. Please help me I am completely stuck, Thanks!!
The exception FileNotFoundException indicates that the file you specified was not found. Perhaps it's not in the same directory that your program is executing in? Perhaps it has some sort of suffix like .txt? Try providing the fully qualified path to the file, like:
"/Users/bob.bobberton/RandomFloats"
Looks like your problem starts with the line
File rf = new File("RandomFloats");
You're not passing a valid path to the File constructor, which is why the next line
Scanner kb = new Scanner(rf);
is throwing a filenotfound exception
You should check out these links
http://docs.oracle.com/javase/7/docs/api/java/io/File.html
http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
when you try to read a file, you need to provide it's extension so it is recognized as a file not a directory ... this happened to me several times
File rf = new File("RandomFloats.whatEver");

Categories

Resources