Beginner Using OOP in java how do I getAverage and getStandardDeviation() - java

Here's what I have so far from my code. this is an introductory course so we haven't covered more advanced topics yet. With what I gave so far I input number and press -1 but the program doesn't do anything.
WE HAVEN'T COVERED ARRAYS YET.
import java.util.Scanner;
public class DataSet {
private double value,count,sum, sumOfSquares, average;
public DataSet(double value)
{
this.value=value;
}
public double getAverage(){
int value=0;
int count=0;
double sum=0;
while(value != -1){
sum=sum+value;
average=sum/count;
}
return average;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a numbers to get average and standard deviation: ");
int value=input.nextInt();
DataSet s= new DataSet(value);
System.out.println(s.getAverage());
}
}

Try this below program. This class has only average method. You can add any number methods operating on values arraylist.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class DataSet {
private List<Integer> values;
public DataSet(List<Integer> values) {
this.values = values;
}
public double getAverage() {
int sum = 0;
double result = 0.0;
for (int value : values) {
sum = sum + value;
}
if (values.size() > 0) {
result = sum / values.size();
}
return result;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Integer> values = new ArrayList<Integer>();
System.out
.print("Enter a numbers to get average and standard deviation: ");
int value = input.nextInt();
while (value != -1) {
values.add(value);
value = input.nextInt();
}
DataSet s = new DataSet(values);
System.out.println(s.getAverage());
}
}

Related

Need to perform calculations on array within Object array

I have an array of 15 Student objects that consist of an int (student ID) and an array (scores for 5 lab assignments). I am required to calculate the Low, High, and Avg scores for each of the 5 labs. The only way I can think of doing this is looking at all the arrays by columns, but my arrays are a row for each student. How would I go about doing these calculations on these arrays.
Included is a Util class which the Student object array comes from and a Student class to define the object. I only need help with the Statistics class provided.
Any help would be greatly appreciated!
Util.class:
import java.io.*;
import java.util.*;
import java.lang.*;
public class Util {
public static Student[] readFile(String fileName) {
Student studentArray[]=new Student[15];
try{
FileReader file = new FileReader("studentData.txt");
BufferedReader buff = new BufferedReader(file);
String line;
line = buff.readLine();
int index=0;
while(line != null){
System.out.println(line);
if(index>14){
break;
}
line = buff.readLine();
String[] result = line.split("\\s");
int sid = Integer.parseInt(result[0]);
int scores[] = new int[5];
for(int x=1;x<result.length;x++){
scores[x-1] = Integer.parseInt(result[x]);
}
Student myCSC20Student = new Student(sid, scores);
studentArray[index++] = myCSC20Student;
}
}
catch (IOException e){
System.out.println("Error: " + e.toString());
}
return studentArray;
}
}
Student.class:
import java.io.*;
import java.util.*;
public class Student {
final int LABS = 5;
private int SID;
private int scores[] = new int[LABS];
public Student(int sid, int[] scores)
{
this.SID=sid;
this.scores = scores;
}
//getters and setters for SID and scores
public int getID() {
return SID;
}
public void setID(int x) {
this.SID = x;
}
public int[] getScore() {
return scores;
}
}
Statistics.class:
import java.io.*;
import java.util.*;
public class Statistics {
final int LABS = 5;
public int[] lowscores = new int[LABS];
private int[] highscores = new int[LABS];
private float[] avgscores = new float[LABS];
public static void main(String args[]) {
Student[] studArr = Util.readFile("studentData.txt");
System.out.println("");
for(int i=0; i<=studArr.length-1; i++){
System.out.println(Arrays.toString(studArr[i].getScore()));
}
}
void calculateLow(Student[] a){
}
void calculateHigh(Student[] a){
}
void calculateAvg(Student[] a){
}
}
Output Class:
import java.util.*;
public class Output{
public static void main(String[] args){
Student[] studArr = Util.readFile("studentData.txt");
Statistics statistics = new Statistics();
statistics.calculateLow(studArr);
statistics.calculateHigh(studArr);
statistics.calculateAvg(studArr);
System.out.println("Low scores:");
System.out.println(Arrays.toString(statistics.getLowscores()));
System.out.println("High scores:");
System.out.println(Arrays.toString(statistics.getHighscores()));
System.out.println("Average scores:");
System.out.println(Arrays.toString(statistics.getAvgscores()));
}
}
Output of scores of all 15 students for the 5 labs
#Bogdan-Lukiyanchuk provided a solution that utilizes Java streams. I am of the impression the assignment is designed to only use loops and arrays. As such, a pointer to the solution is something along the lines of:
void calculateLow(Student[] a) {
// if we don't have any students, then just leave
if (a == null || a.length == 0) {
return;
}
// set to the maximum score one could possibly have
int lowScore = Integer.MAX_INT;
Student lowPersonOnTotem = null;
// process all of the students
for (Student student : a) {
int[] scores = student.getScore();
// loop over all of the scores; if the score is lower than any
// previous, update the lowScore and who had it
for (int score : scores) {
if (score < lowScore) {
lowScore = score;
lowPersonOnTotem = student;
}
}
}
System.out.printf("Lowest score of all students is %d achieved by %d\n",
lowScore, lowPersonOnTotem.getId());
}
Now, following from the critique by #markspace in the comments, I would think having calculateLow() return a value and then have the display elsewhere would be most appropriate, but the method was marked as void in the OP's example.
The other methods are essentially the same loop, but the math changes.
import java.util.*;
public class Statistics {
final int LABS = 5;
public int[] lowscores = new int[LABS];
private int[] highscores = new int[LABS];
private float[] avgscores = new float[LABS];
public static void main(String args[]) {
Student[] studArr = Util.readFile("studentData.txt");
System.out.println();
for(int i=0; i<=studArr.length-1; i++){
System.out.println(Arrays.toString(studArr[i].getScore()));
}
Statistics statistics = new Statistics();
statistics.calculateLow(studArr);
statistics.calculateHigh(studArr);
statistics.calculateAvg(studArr);
System.out.println("Low scores:");
System.out.println(Arrays.toString(statistics.getLowscores()));
System.out.println("High scores:");
System.out.println(Arrays.toString(statistics.getHighscores()));
System.out.println("Average scores:");
System.out.println(Arrays.toString(statistics.getAvgscores()));
}
public void calculateLow(Student[] a){
for (int i = 0; i < LABS; i++) {
final int lab = i;
lowscores[lab] = Arrays.stream(a)
.mapToInt(student -> student.getScore()[lab])
.min()
.orElse(0);
}
}
public void calculateHigh(Student[] a){
for (int i = 0; i < LABS; i++) {
final int lab = i;
highscores[lab] = Arrays.stream(a)
.mapToInt(student -> student.getScore()[lab])
.max()
.orElse(0);
}
}
public void calculateAvg(Student[] a){
for (int i = 0; i < LABS; i++) {
final int lab = i;
avgscores[lab] = (float) Arrays.stream(a)
.mapToInt(student -> student.getScore()[lab])
.average()
.orElse(0);
}
}
public int[] getLowscores() {
return lowscores;
}
public int[] getHighscores() {
return highscores;
}
public float[] getAvgscores() {
return avgscores;
}
}

<Why doesn't my mean increase above zero?> Convert to double

UPDATE: I've tried changing the return type on the getCalcMean() and calcMean() methods to double to make it more accurate, and everything inside the Person class works fine, but Inside the program class it's now saying "Incompatible Types: possible lossy conversion from double to int." at System.out.println(math1.calcMean(math1.getCalcMean())); I understand what the error means but I'm not sure how to fix it as the final result needs to be double and I thought java could calculate a double and int and get a double. What am I doing wrong?
<<>>
I'm trying to calculate the mean of the total after 999 is typed, but it keeps showing 0, and I can't see why.
Can someone tell me how to get my getCalcMean() method to show the mean as numTotal/count?
--- Class Program ---
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int num = 0;
int count = 1;
Math math1 = new Math(num, count);
while (num != 999) {
num = kb.nextInt();
if (num != 999) {
math1.adder(num);
count ++;
System.out.println("Total till now:" + math1.getNumTotal());
}
}
math1.setCount(count);
System.out.println(math1.getNumTotal());
System.out.println(math1.calcMean(math1.getCalcMean()));
//System.out.println(math1.getNum());
kb.close();
/*Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
Scanner scn = new Scanner(input);
int num = scn.nextInt();
Math math1 = new Math(num,0);
while(num != 999){
math1.adder(num);
input = kb.nextLine();
}
System.out.println(math1.getNumTotal());*/
} //main
}
---- Class Math ----
public class Math {
private int num;
private int numTotal;
private double mean;
private int count;
/*public Math(int num, int numTotal){
this.num = num;
}*/
public Math(int num, int count) {
this.num = num;
this.count = count;
}
//get//
public int getNum(){
return this.num;
}
public int getNumTotal(){
return this.numTotal;
}
public double getCalcMean(){
return this.mean;
}
//set//
public void setNumTotal(int value){
this.numTotal = value;
}
public void setNum(int value){
this.num = value;
}
public void setCalcMean(double value){
this.mean = value;
}
public void setCount(int value){
this.count = value;
}
//other
/*public void adder(int num){
numTotal = numTotal + num;
}*/
public void adder(int num) {
this.num = num;
numTotal = numTotal + this.num;
}
//added after//
public double calcMean(int num){
this.numTotal = numTotal;
mean = numTotal / this.count;
return mean;
}
}
counter ++ in your code is meaningless since you never pass it to Math object.
math1.getCalcMean() will return the mean in Math object but mean hasn't been calculated yet.
Advice:
Add getter and setter for counter in Math class.
Calculate the mean in getCalcMean() method.
Plese see the code below. I assume that you use 999 as the end flag so haven't took it into account. The counter is initialized with 0.
import java.util.Scanner;
public class Program {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
int num = 0;
int counter = 0;
Math math1 = new Math(num, counter);
while (num != 999) {
num = kb.nextInt();
if (num != 999) {
math1.adder(num);
counter ++;
math1.setCounter(counter);
System.out.println("Total till now:" + math1.getNumTotal());
}
}
System.out.println(math1.getNumTotal());
System.out.println(math1.getCalcMean());
//System.out.println(math1.getNum());
kb.close();
/*Scanner kb = new Scanner(System.in);
String input = kb.nextLine();
Scanner scn = new Scanner(input);
int num = scn.nextInt();
Math math1 = new Math(num,0);
while(num != 999){
math1.adder(num);
input = kb.nextLine();
}
System.out.println(math1.getNumTotal());*/
} //main
}
And also the Math class.
public class Math {
private int num;
private int numTotal;
private int mean;
private int counter;
/*public Math(int num, int numTotal){
this.num = num;
}*/
public Math(int num, int counter) {
this.num = num;
this.counter = counter;
}
//get//
public int getNum(){
return this.num;
}
public int getNumTotal(){
return this.numTotal;
}
public int getCalcMean(){
mean = numTotal / this.counter;
return mean;
}
public int getCounter(){
return this.counter;
}
//set//
public void setNumTotal(int value){
this.numTotal = value;
}
public void setNum(int value){
this.num = value;
}
public void setCalcMean(int value){
this.mean = value;
}
public void setCounter(int counter){
this.counter = counter;
}
//other
/*public void adder(int num){
numTotal = numTotal + num;
}*/
public void adder(int num) {
this.num = num;
numTotal = numTotal + this.num;
}
//added after//
public void calcMean(int num){
mean = numTotal / this.counter;
}
}

Cannot find Symbol - Variable, despite the variable being declared

The numThrows Variable is inciting an error of variable not found when used in the main method. even though i declare it in one of the methods.
I use the declare the variable in the void prompt method. This program is designed to calculate Pi using random coordinates then uses a formula to estimate pie over a user given amount of tries.
import java.util.Random;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
import java.io.IOException;
public class Darts
public static void prompt()
{
Scanner in = new Scanner(System.in);
System.out.println("How many throws per trial would you like to do?: ");
int numThrows = in.nextInt();
System.out.println("How many trials would you like to do?: ");
int numTrials = in.nextInt();
}
public static double[] randomX( int numThrows)
{
int darts = 0;
int i = 0;
double[] cordX = new double[numThrows];
while(darts <= numThrows)
{
cordX[i] = Math.random();
i++;
}
return cordX;
}
public static double[]randomY(int numThrows)
{
int darts = 0;
int i = 0;
double [] cordY = new double[numThrows];
while(darts <= numThrows)
{
cordY[i] = Math.random();
i++;
}
return cordY;
}
public static void getHits(int numThrows, double[] cordX, double[] cordY)
{
int ii = 0;
int i = 0;
double hits = 0;
double misses = 0;
for(i = 0; i <= numThrows; i++)
{
if( Math.pow(cordX[ii],2) + Math.pow(cordY[ii],2) <= 1)
{
hits++;
ii++;
}
else{
misses++;
}
}
}
public static double calcPi(int misses, int hits)
{
int total = hits + misses;
double pi = 4 * (hits / total);
}
// public static void print(double pi, int numThrows)
// {
// System.out.printf(" %-7s %3.1f %7s\n", "Trial[//numtrial]: pi = "
// }
public static void main(String[] args)throws IOException
{
prompt();
double[] cordX = randomX(numThrows);
double[] cordY = randomY(numThrows);
gethits();
double pi = calcPi(misses, hits);
}
}
If numThrows is declared within another function, then its scope does not extend to the main method.
Instead, if you want to use it in both the main method and the other one, make it a class instance.
For example:
class SomeClass {
public static int numThrows = 2;
public static void test() {
numThrows = 4; // it works!
}
public static void main(String[] args) {
System.out.println(numThrows); // it works!
}
}
Therefore, its scope will be extended to all the members of the class, not just the method.
numThrows is an instance variable to your prompt method. If you want to do what I think you want to do, make numThrows a static variable outside any methods.
It will look like this:
public class Darts {
public static int numThrows
public static int numTrials
These variables can be referenced from any method. This should fix it.
Try to remove the method prompt() it's unused, and put his block in the main method.
public static void main(String[] args)throws IOException
{
Scanner in = new Scanner(System.in);
System.out.println("How many throws per trial would you like to do?: ");
int numThrows = in.nextInt();
System.out.println("How many trials would you like to do?: ");
int numTrials = in.nextInt();
double[] cordX = randomX(numThrows);
...

For every services I'm getting same price (output)

import java.util.Scanner;
import java.util.Arrays;
public class CarCareChoice{
public static void main(String[] args) {
String[] choices=new String[5];
int j ;
boolean validItem=false;
double price=0.0;
int p;
String str;
//When i'm entering services I'm getting 5.o for all services plz help
String[] services={"Am","Bm","Cm","Dm","Em"};
double prices[]={1.0,2.0,3.0,4.0,5.0};
//Scanner
Scanner input = new Scanner(System.in);
System.out.println("enter");
str= input.nextLine();
for(j = 0; j < choices.length;j++){
if(Arrays.asList(services).contains(str)){
validItem=true;
price=prices[j];
}
}
if (validItem)
System.out.println("service"+""+price);
else
System.out.println("Invalis enter");
}
}
output
enter
Am
service5.0
output
enter
Bm
service5.0
when I enter Am i supposed to get 1.0 for "Bm 2.0 and etc but I'm getting only 5.0
You rather improve your code as following:
System.out.println("enter");
List<String> choiceList = Arrays.asList(services);
str= input.nextLine();
int index = choiceList.indexOf(str);
if ( index!=-1 )
{
price = prices[i];
validItem = true;
}
if (validItem)
System.out.println("service"+""+price);
else
System.out.println("Invalis enter");
You need not do this in for loop. Because when you have converted your array to a list then just find the index. If that is -1 then its definitely not a valid item else return the price at that index of the array. ArrayList is backed by an array internally.
import java.util.Arrays;
class Main {
public static final int INVALID_INDEX = -1;
public static void main(String[] args) {
String[] services={"Am","Bm","Cm","Dm","Em"};
double prices[]={1.0,2.0,3.0,4.0,5.0};
String input = "Em";
int index = Arrays.asList(services).indexOf(input);
System.out.println((index!=INVALID_INDEX)? prices[index]+"":"invalid input");
}
}
Use a Map<String,Double> instead if possible.

How to create dynamic array in java with unclear and diffrent inpu INDEXes?

I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?

Categories

Resources