Java inheritance and super method - java

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 ();

Related

Take Average of an Array using Recursion

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]);
}
}

Data sets with floating points

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;
}
}
}
}

Use scanner only from main method

I have this class (with setters, getters and one method) that asks from a user a number indefinitely until he types -1.
I've called the Scanner Method from both, the main method and the class itself, is there a way to call the Scanner method only once only from the main method and apply the input to the class every time it is needed? I really appreciate your help. If something is not clear, please contact me.
Here's the Class Code:
public class calculation {
int current = 0;
int maxNum = 0;
int minNum;
int counter=0;
float sum = 0;
float avg;
Scanner scan = new Scanner(System.in);
public void setMin(int min){
this.minNum = min;
}
public int getMin(){
return minNum;
}
public void setMax(int max){
this.maxNum = max;
}
public void setSum(float sum){
this.sum += sum;
}
public void minMax(int current){
setMin(current);
while(current!=-1){
setSum(current);;
if(current>getMin()){
setMax(current);
}else if(current<getMin()){
setMin(current);;
}
current = scan.nextInt();
counter++;
}
System.out.println("The smallest number you entered was: \n" + minNum);
System.out.println("The biggest number you entered was: \n" + maxNum);
System.out.println("The sum of all those numbers is: \n" + sum);
System.out.println("The avarege number is: \n" + (sum/counter));
}
}
And here's the main method code:
public class minusOne {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
calculation cal1 = new calculation();
System.out.println("Type numbers at will, when finish, type -1 and press enter");
cal1.minMax(scan.nextInt());
scan.close();
}
}
From what I understand, you don't want to have two call to new Scanner(System.in);
To avoid this, you can simply, in your class calculation, write :
Scanner scan;
And add a constructor :
public calculation(Scanner sc){
scan = sc;
}
Of course, in the main method you should write :
new calculation(scan)
I hope I answered your question
Note: in Java your classes name should start with uppercase letter, it should be Calculation
You have some alternatives for this, you can have your Calculator class with a constructor that takes a Scanner as a parameter and then store it in a field, or you cand have a public field in the Calculator class and in your main when you get the scanner just affect this field (but it should be private, you can change it via getters and setters methods).
/* This is the first option*/
public class Calculation {
int current = 0;
int maxNum = 0;
int minNum;
int counter=0;
float sum = 0;
float avg;
private Scanner scan;
public Calculation(Scanner scan){
this.scan = scan;
}
public int setCurrent(int current){
this.current = current;
return current;
}
public void setMin(int min){
this.minNum = min;
}
public int getMin(){
return minNum;
}
public void setMax(int max){
this.maxNum = max;
}
public void setSum(float sum){
this.sum += sum;
}
public void minMax(int current){
setMin(current);
while(current!=-1){
setSum(current);;
if(current>getMin()){
setMax(current);
}else if(current<getMin()){
setMin(current);;
}
current = setCurrent(current);;
counter++;
}
System.out.println("The smallest number you entered was: \n" + minNum);
System.out.println("The biggest number you entered was: \n" + maxNum);
System.out.println("The sum of all those numbers is: \n" + sum);
System.out.println("The avarege number is: \n" + (sum/counter));
}
}
/* Second option */
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
calculation cal1 = new calculation();
//if the field scan in Calculation is public
cal1.scan = scan;
//if it is private
cal1.setScan(scan);
System.out.println("Type numbers at will, when finish, type -1 and press enter");
cal1.minMax(scan.nextInt());
scan.close();
}

Does this Java program need to be two separate Files

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.

Basic Java questions Scanning

This is very basic java that i'm struggling with n00b style. it just prints out this
Please enter '.' when you want to calculate
1 2 3
.
Numbers are 1 2 3
The Sum is0The Product is1
when it is supposed to calculate the sum and product of those consecutive numbers. something is wrong id appreciate any help!
main method
import java.util.*;
public class NumberScanned {
public static void main(String[] args) {
System.out.println("Please enter '.' when you want to calculate");
Scanner keyboard = new Scanner(System.in);
String scannedString = keyboard.nextLine();
Scanning scanz= new Scanning(scannedString);
while(!keyboard.nextLine().equals("."))
{
scanz.set(scannedString);
}
keyboard.close();
System.out.println("Numbers are"+scannedString);
scanz.printState();
}
}
Class Scanning
public class Scanning {
int num;
int sum;
int product;
String userInput;
public Scanning(String userInput)
{
num=0;
sum=0;
product=1;
this.userInput=userInput;
}
public void set(String userInput)
{
for(int index=0; index<userInput.length(); index++)
{
if(Character.isDigit(userInput.charAt(index))==true)
{
num=userInput.charAt(index);
sum+=num;
product*=num;
}
else
{
index++;
}
}
}
public void printState()
{
System.out.println("The Sum is"+sum+"The Product is"+product);
}
}
A few things to look at:
We know keyboard.nextLine() gets the input from the console, but where are you checking it's validity (more importantly, when do you check it?). Are you looking at all input or just the last line?
isDigit will return true if the passed in character is a number. Do you want to operate on numbers or characters in your for loop?
(a side note, What happens if I enter "1 10" in the console?)
A for loop will automatically increment its index at the end of a loop, so an additional ++ is unnecessary
You might find this helful in case you just need the sum and product values of a user entered
values.
public class ProductSumCalculator{
private static List<Integer> numbers = new ArrayList<Integer>();
public static void main(String[] args){
getInputs();
calculateSumAndProduct();
}
private static void getInputs() {
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter numbers or ctrl+z to end inputs");
while(scanner.hasNext()){
numbers.add(scanner.nextInt());
}
}
private static void calculateSumAndProduct() {
Iterator<Integer> iterator = numbers.iterator();
int sum=0;
int product=1;
int nextVal;
while(iterator.hasNext()){
nextVal = iterator.next();
sum+=nextVal;
product*=nextVal;
}
System.out.println("Value entered are: "+numbers+".\nThe sum is "+
sum+".The product is "+product);
}
}
You can also try this. You can calculate the sum and product of all the int from your string line input like this:
import java.util.Scanner;
public class Scanning {
/*
* This method returns the integer. If while
* conversion an Exception is thrown it returns
* null. Otherwise the integer.
*/
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
/*
* Next String line is scanned. It is split by space.
* Stores String tokens in an String array from one String variable.
* Then passed to tryParse() class method. null or auto Boxed Integer
* is returned accordingly. It is auto unboxed from Integer
* object to int variable. Then sum and product is calculated and
* the final result is printed on the console Or Integrated
* Development Environment.
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner(System.in);
String strInts = keyboard.nextLine();
String[] splits = strInts.split("\\s+");
int i = 0;
Integer anInteger = null;
int total = 0;
int product = 1;
while((i < splits.length)) {
anInteger = tryParse(splits[i]);
if(anInteger != null) {
total = total + anInteger;
product = product * anInteger;
}
++i;
}
System.out.println("The sum is: " + total);
System.out.println("The product is: " + product);
}
}

Categories

Resources