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;
}
}
}
}
Related
I'm new to java and I'm tinkering with my code and decided to create an input validation method, my problem is how am I going to loop the input through the validations.
First I decided to take the input as string to do a try/catch with a double, no problem with that, now I need to test the input if it's in the range of 0-100. Of course I wanted to check if the user will type in a double in the "range check". What I wrote somewhat worked but when the input passed the data type validation but not the range check, it will still return the first double, whatever I typed next.
public static double check(String n){
boolean done = false;
double i=0.0;
Scanner beep = new Scanner(System.in);
while (!done) {
try {
i = Double.parseDouble(n);
done = true;
} catch (Exception e) {
System.out.print("Please input a valid grade (0-100): ");
n = beep.nextLine();
}
}
double b = rangetest(i);
return b;
}
public static double rangetest (double n){
if (n > 100 || n < 0){
System.out.print("0-100 only ");
Scanner beep = new Scanner(System.in);
check(beep.next());
}
return n;
}
public static void main(String[] args) {
Scanner beep = new Scanner(System.in);
double ave = 0.0;
int rounded;
for (int i = 1; i <= 5; i++)
{
System.out.print("Input grade number " + i + " : ");
ave += rangetest(check(beep.next()));
}
ave /= 5;
rounded = (int)Math.round(ave);
}
Is there any easier methods or workarounds? Or am I doing it all wrong? Cheers!
Beware of Scanner#next, this can leave a dangling new line character in the buffer which can mess with your workflows, however, the core issue is with your rangetest
public static double rangetest (double n){
if (n > 100 || n < 0){
System.out.print("0-100 only ");
Scanner beep = new Scanner(System.in);
check(beep.next());
}
return n;
}
Here, if the value is not within the specified range, you're calling check again, but you're ignoring the result, so you end up returning the original value of n
It would seem that instead, you want to do...
n = rangetest(check(beep.next()))
within the if block.
You could accomplish something similar using do-while loops, for example...
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Double value = getDoubleWithinRange(scanner, "Make me an offer ([X] to exit): ", "That's not a reasonable offer", "X", 0, 100, "Value is not within a valid range (0-100)");
if (value != null) {
System.out.println("You mad an offer of " + value);
}
}
public static Double getDoubleWithinRange(Scanner input, String prompt, String errorMessage, String exitValue, double min, double max, String rangeErrorMessage) {
boolean done = false;
Double value = null;
do {
value = getDouble(input, prompt, errorMessage, exitValue);
if (value != null) {
if (isWithinRange(value, 0, 100)) {
done = true;
} else {
beep();
System.out.println(rangeErrorMessage);
}
} else {
done = true;
}
} while (!done);
return value;
}
public static void beep() {
java.awt.Toolkit.getDefaultToolkit().beep();
}
public static boolean isWithinRange(double value, double min, double max) {
return value >= min && value <= max;
}
public static Double getDouble(Scanner input, String prompt, String errorMessage, String exitValue) {
Double value = null;
boolean exit = false;
do {
System.out.print(prompt);
String nextLine = input.nextLine();
Scanner parser = new Scanner(nextLine);
if (parser.hasNextDouble()) {
value = parser.nextDouble();
} else if (nextLine.equals(exitValue)) {
exit = true;
} else {
beep();
System.out.println(errorMessage);
}
} while (!(value != null || exit));
return value;
}
}
nb: I have a exit condition available, you don't need it, but it's nice as a demonstration
I fashioned myself a function from #MadProgrammer's code (Thanks man!), this somehow works a wee bit simpler.
public static double getValue() {
Scanner beep = new Scanner(System.in);
boolean flag = true;
double value=0.0;
while(flag==true){
if(beep.hasNextDouble()){
value = beep.nextDouble();
if(value>=0&&value<=100){
flag=false;
}
else{
System.out.print("Invalid input, 0-100 only: ");
beep.nextLine();
}
}
else{
System.out.print("That's not a numerical value, try again: ");
beep.nextLine();
}
}
return value;
}
Feel free to comment, make a correction and/or suggest anything that would make this better.
So I'm trying to write a program that stimulates the rise and fall of the Stock market 5 times.The user inputs a value to create a new Stock Market Object then with the value from the user, the stock market either is a bust(decrease) or a boom( increase). The issue I'm having is passing the value to each if statement with the change within the loop.When I run the program, It uses the same value I entered instead of using the value that was created after calling boom or bust. I'm thinking I should create a value outside the loop that holds it but I'm not sure how to do that with the user input.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a Starting Market Value:");
double mv = in.nextDouble();
StockMarket u = new StockMarket(mv);
for (int i = 0; i < 5; i++) {
System.out.println("Boom (1) or Bust(2)? ");
int t = in.nextInt();
if (t == 1) {
System.out.println("Enter a percentage of increase as a decimal ( eg .5 ):");
double r = in.nextDouble();
if (t == 1) {
double e = u.boom(r);
System.out.println("The Stock Market is now at: " + e);
}
} else if (t == 2) {
System.out.println("Enter number of points lost:");
double l = in.nextDouble();
if (t == 2) {
double f = u.bust(l);
System.out.println("The Stock Market is now at: " + f);
}
}
}
}
}
Below is the class
public class StockMarket {
//Instance Variable Points
private double Points;
// Default no Argument Constructor
public StockMarket(){
this(0.0);
}
// Constructor #2
public StockMarket(double Points){
this.Points = Points;
}
//
public double getPoint(){
return Points;
}
public double boom(double x){
x = Points * (1 + x);
return x;
}
public double bust( double h){
h = Points - h;
return h;
}
}
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();
}
EDIT: HERE IS A SCREENSHOT OF THE OUTPUT
https://www.dropbox.com/s/93d09a627se3b1u/Screenshot%202015-09-16%2019.08.19.png?dl=0]
I was recently asked to make a program that can calculate and display...
1 / (1!) + 1 / (2!) + . . . 1 / (n!)
using the Scanner utility. I seem to be having a lot of trouble with this. the program itself works, but it somehow gives the same answer no matter what number I input. Here's what I have so far (And yes, it is purposely incomplete, I'm stumped).
import java.util.Scanner;
class Power2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . +
1/(n!)\nWhat is the value of n?");
Double n = input.nextDouble();
Math(n);
System.out.println("e = " + Math.E);
}
public static void Math(Double E)
{
Double product = 1.0;
int x = 0;
while (E > 0)
{
product = product * E;
E--;
}
Can anyone give me a way to finish/solve this problem? Thanks a ton.
~Andrew
EDIT: This code works fine for just finding the extreme. I will work on a way to add the preceding components of the equation to this, but It's a bit tricky for me.
import java.util.Scanner;
class Power2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . +
1/(n!)\nWhat is the value of n?");
Double n = input.nextDouble();
Math(n);
System.out.println("e = " + Math(n));
}
public static Double Math(Double E)
{
Double product = 1.0;
while (E > 0)
{
product *= E;
E--;
}
return product;
}
}
You are confused with too much Math.
You've got your method Math with a parameter E and the Java Math class with a constant E. You're mixing them up.
Try
public static double factorial(double v)
{
double product = 1.0;
while (v > 0)
{
product *= v;
v--;
}
return product;
}
Your code:
System.out.println("e = " + Math.E);
Math.E is a constant - it will always print the euler number hence your output.
To call the the method correctly it should be
System.out.println("e = " + math(e)"
Input 1 - Output 1
Input 2 - Output 1.5
Input 3 - Output 1.66666667
import java.util.Scanner;
class MyClass
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("I will calculate 1/(1!) + 1/(2!) . . . + 1/(n!)\nWhat is the value of n?");
double n = input.nextDouble();
double solution = doMath(n);
System.out.println("e = " + solution);
}
public static double doMath(double n) {
double ret = 0;
// the number of terms we add
for (int i = 1; i <= n; i++) {
ret += calcFaculty(i);
}
return ret;
}
// calculate every single term
public static double calcFaculty(double d){
double calc = 1;
for (int i = 1; i <= d ; i++) {
calc = calc* 1/i;
}
return calc;
}
}
Hi Andrew the program always return the same number
e = 2.718281828459045
Because the line System.out.println("e = " + Math.E); is not calling the method Math but calling to the class java.lang.Math. I dont know if is this what you find dubious.
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 ();