Hi everyone I am taking a Java class and this is my first assignment involving object oriented programming. I am getting issues with the SimpleCalc portion and am wondering if my work should be two separate files or if I am missing a component that allows the StatCalc part and SimpleCalc part to speak with one another. Please keep in mind that I am new to Java so I might need this spelled out a bit more then I have seen on stack over flow in the past at times, however, I will appreciate any help so thank you in advance. Here is my code:
package tutorial;
/*
* An object of class StatCalc can be used to compute several simple statistics
* for a set of numbers. Numbers are entered into the dataset using
* the enter(double) method. Methods are provided to return the following
* statistics for the set of numbers that have been entered: The number
* of items, the sum of the items, the average, the standard deviation,
* the maximum, and the minimum.
*/ public class StatCalc {
private int count; // Number of numbers that have been entered.
private double sum; // The sum of all the items that have been entered.
private double squareSum; // The sum of the squares of all the items.
private double max = Double.NEGATIVE_INFINITY; private double min = Double.POSITIVE_INFINITY;
/**
* Add a number to the dataset. The statistics will be computed for all
* the numbers that have been added to the dataset using this method.
*/
public void enter(double num) {
count++;
sum += num;
squareSum += num*num;
if (count == 1){
max = num;
min = num;
}
else {
if (num > max)
max = num;
if (num < min)
min = num;
}
}
/**
* Return the number of items that have been entered into the dataset.
*/
public int getCount() {
return count;
}
/**
* Return the sum of all the numbers that have been entered.
*/
public double getSum() {
return sum;
}
/**
* Return the average of all the items that have been entered.
* The return value is Double.NaN if no numbers have been entered.
*/
public double getMean() {
return sum / count;
}
/**
* Return the standard deviation of all the items that have been entered.
* The return value is Double.NaN if no numbers have been entered.
*/
public double getStandardDeviation() {
double mean = getMean();
return Math.sqrt( squareSum/count - mean*mean );
}
public double getMin(){
return min;
}
public double getMax(){
return max;
} }// end class StatCalc
public class SimpleCalc {
public static void main(String[]args){
Scanner in = new Scanner(System.in);
SimpleCalc calc;
calc = new SimpleCalc();
double item;
System.out.println("Enter numbers here. Enter 0 to stop.");
System.out.println();
do{
System.out.print("? ");
item = in.nextDouble();
if (item != 0)
calc.enter(item);
}while (item != 0);
System.out.println("\nStatistics about your calc:\n");
System.out.println(Count: "+calc.getCount"());
System.out.println(Sum: "+calc.getSum"());
System.out.println("Minimum: "+calc.getMin());
System.out.println("Maximum: "+calc.getMax());
System.out.println("Average: "+calc.getMean());
System.out.println("Standard Deviation: "+calc.getStandardDeviation());
}// end main
}//end SimpleCalc
In Java a public class must be in a file with the same name as the class. So since you have a public class named StatCalc then the filename must be StatCalc.java. Similarly the second class is also public therefore it must be in its own file.
Yes, it needs two files.
Java's contract is that every "top level" public class requires it's own file.
Related
I'm trying to create a program that will take a user input, input that data into an dynamic array, and then recursively finds the average. The first part of my code works. This allows the newly created array to be passed to the method.
public static void main(String args[])
{
int i = 0;
int sum = 0;
double runningTotal = 0;
int classSize;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the class size: ");
classSize = keyboard.nextInt();
int newClassSize[] = new int[classSize];
for (i=0; i < newClassSize.length; i++)
{
System.out.println("Please enter the grade of the user at: " + (i + 1));
newClassSize[i] = keyboard.nextInt();
}
findAverage();
for (i=0; i < newClassSize.length; i++){
sum = sum + newClassSize[i];
}
System.out.println(Arrays.toString(newClassSize));
keyboard.close();
}
}
This is where I'm getting confused and confusing myself however. How would I pass the newly created array to the findAverage() method? I would then need to also have that be saved to an accumulator and then devided. Is there a better way to do this? This is my current findAverage() method but I'm confusing myself on my implementation.
public double findAverage(int classAverage, int baseCase, double runningAverage)
{
runningAverage = 0;
int sum = 0;
if (newClassSize.length - 1 > baseCase)
runningAverage = newClassSize.length;
return findAverage();
System.out.println("The class average is " + classAverage);
}
Hopefully I understood your question correctly but heres how to do it below.
The basic idea is that when the index reaches the length of the array in the
recursive function that's the base case. So all you have to do is add to the sum at each index point in the array, and just keep passing in the updated index and sum into the recursive function.
class Main {
public static void main(String[] args) {
int newClassSize[] = {1,2,3}; // User Input let say
double average = findAverage(newClassSize);
System.out.println(average);
}
public static double findAverage(int[] arr){
// Avoid division by zero error
if (arr.length==0){
return 0;
}
return findAverageHelper(arr,0,0);
}
public static double findAverageHelper(int[] arr, int index,int sum){
if (index==arr.length){ // Base Case
return (double) sum/arr.length;
}
// Increase index and add current value at index to sum
return findAverageHelper(arr,index+1,sum+=arr[index]);
}
}
So currently, I'm struggling to make one particular program in eclipse for an assignment, while I am able to make most of the program, I seem to struggle with the no argument part of the program as well as bringing the pieces of the first class into the second for a brief moment. Here is my code for the first class
// Preparation of the input
import java.util.Scanner;
public class primarySetUp {
public static void main(String[] args) {
// Variable Declaration
double userBagNumber;
double userBagWeight;
// Create Scanner
Scanner input = new Scanner(System.in);
java.util.Date date = new java.util.Date();
// Opening Statement
System.out.println("Welcome to the Coffee Sales Simulation!");
// Get User Input
System.out.println("How heavy do you want the bags to be?");
userBagWeight = input.nextDouble();
System.out.println("How many bags do you want?");
userBagNumber = input.nextDouble();
// Get output
// Date
System.out.println("Todays date: ");
System.out.printf("%tB %<te, %<tY", date);
System.out.println(""); // spacer
// Original Inputs
System.out.printf("\nNumber of Bags: %3.0f", userBagNumber);
System.out.printf("\nWeight of Each Bag: %3.2f", userBagWeight);
System.out.print(" lbs");
// Calling of the Class
secondarySetUp mysecondarySetUp = new secondarySetUp(userBagWeight, userBagNumber);
// End Program
System.out.println("\nThank you for shopping with us!");
}
}
and here is my code for the second class, which is full of errors in this case.
public class secondarySetUp {
// Constants
static double pricePerPound = 5.99;
static double taxRate = 0.0725;
int singleBagger, pounderBagger;
public secondarySetUp(double userBagWeight, double userBagNumber) {
// A method named getTaxRate() that returns the tax rate.
System.out.printf("\nPrice per Pound: $%2.2f", getPrice());
System.out.printf("\nSales Tax: $%2.2f", getTaxRate());
System.out.print(" %");
System.out.printf("\nPrice of one bag weighing one pound: %3.2f", getSale());
}
// No argument pricing
public Sale() {
singleBagger = 1;
pounderBagger = 1;
}
// First constructor receiving No argument pricing
public Sale(int w, int n) {
singleBagger = w;
pounderBagger = n;
}
// Sale without tax
public double getSale() {
return userBagWeight * singleBagger * pounderBagger;
}
// Get Sale Tax
public double getSaleTax() {
return (getSale() * taxRate);
}
// Get total pricing
public double getTotalPrice() {
return (getSale() + getSaleTax());
}
public double getPrice() {
return pricePerPound;
}
public double getTaxRate() {
return taxRate * 100;
}
}
If you have any sort of fixes I could apply, please let me know; I am planning on adding the print statements for the rest of the arguments as well, but I'd like to get Sale() fixed up first.
I see a problem in getSale() where you are trying to use userBagWeight, but that variable doesn't exist outside the constructor parameters, which could create a lot of problems since other methods are calling on it. The constructor taking
double userBagWeight, double userBagNumber, yet it's not assigning them to any fields or doing anything with them.
I missed the part where you are treating Sale() as a constructor, but those are no constructors. The constructor is named after your class name.
public secondarySetUp(double userBagWeight, double userBagNumber)
change Sale() to secondarySetUp and you will be fine.
here how your class should be like :
public class secondarySetUp {
// Constants
static double pricePerPound = 5.99;
static double taxRate = 0.0725;
int singleBagger, pounderBagger;
double userBagWeight, userBagNumber;
public secondarySetUp(double userBagWeight, double userBagNumber) {
this.userBagWeight = userBagWeight;
this.userBagNumber = userBagNumber;
singleBagger = 1;
pounderBagger = 1;
// A method named getTaxRate() that returns the tax rate.
System.out.printf("\nPrice per Pound: $%2.2f", getPrice());
System.out.printf("\nSales Tax: $%2.2f", getTaxRate());
System.out.print(" %");
System.out.printf("\nPrice of one bag weighing one pound: %3.2f", getSale());
}
// First constructor receiving No argument pricing
public secondarySetUp(int w, int n) {
singleBagger = w;
pounderBagger = n;
}
// Sale without tax
public double getSale() {
return userBagWeight * singleBagger * pounderBagger;
}
// Get Sale Tax
public double getSaleTax() {
return (getSale() * taxRate);
}
// Get total pricing
public double getTotalPrice() {
return (getSale() + getSaleTax());
}
public double getPrice() {
return pricePerPound;
}
public double getTaxRate() {
return taxRate * 100;
}
}
this is a keyword to tell the program that we want to use the field "instance variable", if we have a method with parameter that have same name as a field name, then to tell them apart we tell the program this.fieldName to know which one we talking about.
My main program will create a DataSet object, read in values and call the addValue instance method until it encounters a negative value. Then it will call the getAverage and getStandardDeviation methods and print out the return results. the average is 3.28
the Standard Deviation is 1.972815247
this is my code. I'm basically stuck right now.
import java.util.Scanner;
public class DataSet {
private double value;
private double count;
private double sum;
private double sumofSquares;
public void addValue(double value) {
while (value >= 0) {
count++;
sum += value;
sumofSquares += (value * value);
}
}
public double getAverage() {
return sum / count;
}
public double getStandardDeviation() {
return Math.sqrt(((count * sumofSquares) - (sum * sum)) / (count * (count - 1)));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Value");
double value = sc.nextDouble();
DataSet j1 = new DataSet();
j1.addValue(value);
System.out.println("The average of the value " + j1.getAverage());
System.out.println("The Standard Deviation of the value" + j1.getStandardDeviation());
}
}
There seems to be a lot wrong with this code. Firstly, your input code is not inside of a while loop, so you are not going to intake any new values. Secondly, your addValue function invokes an infinite loop upon entering a positive value, because the while loop will continue to run and add to your DataSet members.
I've refactored your code to make more sense, ask if you have any questions on any specific areas.
import java.util.Scanner;
public class DataSet {
private double value;
private double count;
private double sum;
private double sumofSquares;
public int addValue(double value) {
if(value >= 0) {
count++;
sum += value;
sumofSquares += (value * value);
return 0;
}else{
System.out.println("The average of the value " + this.getAverage());
System.out.println("The Standard Deviation of the value " + this.getStandardDeviation());
return -1;
}
}
public double getAverage() {
return sum / count;
}
public double getStandardDeviation() {
return Math.sqrt(((count * sumofSquares) - (sum * sum)) / (count * (count - 1)));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Values");
double value = 0;
DataSet j1 = new DataSet();
while(true){
value = sc.nextDouble();
if(j1.addValue(value) == 0){
//continue
}else{
return;
}
}
}
}
I have an object of StatCalc which uses getMethods to display in a driver class under main methods. However instead of modyfing StatCalc which has sourcecode. getAvg, getSum, getCount etc...
I have another class which purely getmin() and getmax()
public class StatCalcWithMinMax extends StatCalc {
private double max = Double.NEGATIVE_INFINITY; // Largest item seen.
private double min = Double.POSITIVE_INFINITY; // Smallest item seen.
public void enter(double num) {
// Add the number to the dataset.
super.enter(num); // Call the enter method from the StatCalc class.
if (num > max) // Then do the extra processing for min and max.
max = num;
if (num < min)
min = num;
}
public double getMin() {
// Return the smallest item that has been entered.
// Value will be infinity if no items have been entered.
return min;
}
public double getMax() {
// Return the largest item that has been entered.
// Value will be -infinity if no items have been entered.
return max;
}
}
so the main is this however i can't access getMix and getmax from class above.
public class driver {
public static void main(String[] args) {
StatCalc calc; // Object to be used to process the data.
calc = new StatCalc();
boolean isZero = false;
while (isZero != true) {
Scanner inputer = new Scanner(System.in);
int numEntered = inputer.nextInt();
if (numEntered == 0) {
//isZero = true;
break;
}
calc.enter(numEntered);
}
System.out.println("The numbers entered were: "+ calc.getCount());
System.out.println("The mean of the numbers entered:" + calc.getMean());
System.out.println("The Standard deviation of the numbers entered: "+ calc.getStandardDeviation());
// System.out.println("The minimum number encountered was: "+ calc.getMin());
// System.out.println("The maximum number encountered was: "+ calc.getMax());
}
}
The problem is that you are still using
StatCalc calc; // Object to be used to process the data.
change to
StatCalcWithMinMax calc; // Object to be used to process the data.
calc = new StatCalcWithMinMax ();
Alright, so I'm trying to create a "sales tax program' where the user can input the items and it adds it to an array, called "costArray". I only know how to do it, almost, with a String (since I need costArray.length for the loop) but I'm kind of lost. Can anyone help point me in the right direction so I can: Take an array of numbers (doubles) and apply a multiplier to it (0.08 for sales tax percentage) and output a total number (double)? Here is what I have so far, can you tell me if I'm close? Thanks!:
public class Input
{
private Scanner keybd;
private String item;
private double cost;
private String[] costArray;
private String[] itemArray;
/**
* Constructor for objects of class Scanner
*/
public Input(int anyAmountofItems)
{
keybd = new Scanner(System.in);
costArray = new String[anyAmountofItems];
itemArray = new String[anyAmountofItems];
}
/**
* Mutator method to set the item names and costs
*/
public void setArray(){
for(int index=0; index < itemArray.length; index++){
System.out.println("Enter the item name: ");
itemArray[index] = keybd.next();}
for(int indexa=0; indexa < itemArray.length; indexa++){
System.out.println(itemArray[indexa]);
}
for(int indexb=0; indexb < costArray.length; indexb++){
System.out.println("Enter the item cost: ");
costArray[indexb] = keybd.next();}
for(int indexc=0; indexc < costArray.length; indexc++){
System.out.println(costArray[indexc]);
}
}
/**
* Accessor method to return the items cost with tax
*/
public double getTax(){
return costArray.length;
}
// /**
// * Mutator method to calculate tax on each item
// */
// public void calculateTax(){
// for(int index=0; index < costArray.length; index++){
// System.out.println(0.08 * costArray[index]);
// }
// }
}
The number ist stored in a String and you have to "convert" it to a real number (a double value)
The way to do it is shown here:
String s = "-1.234";
double value = Double.parseDouble(s);
In Java 8:
import java.util.stream.DoubleStream;
double taxCoef = 0.08;
double[] prices = {10,20,30};
double total = DoubleStream.of(prices).map(p->p*(1+taxCoef)).sum();
System.out.println(total);
output: 64.80000000000001
(alternatively, can sum up first and then multiply)
Arrays are a bad idea, if you don't know before which size they will have. Why not use an ArrayList? If you don't know it right know: You'll really will need it often!
Names of indexes inside a loop are well with 'i', 'n', 'p, q, r' or 'x', and they only exist in their own loop, so you can define a new 'i' in the second loop - no need for indexa, indexb, ... .
For learning, a double might be sufficient, but in real world, you shouldn't use double for Money amounts, but BigDecimal. The bit-representation of fractions leads else to surprising effects.
And Scanner has already methods like scanner.nextDouble () to read a Number.