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.
Related
import java.util.Scanner;
public class Prac3_Q2_JasmineLimSmith {
Scanner scan;
String set;
int setA = 0, setB = 0, setC = 0, setD = 0;
void createFile() throws Exception {
File file = new File("orders.txt");
scan = new Scanner(file);
}
void readData() {
setA = scan.nextInt();
setB = scan.nextInt();
setC = scan.nextInt();
setD = scan.nextInt();
if (scan.hasNextLine())
scan.nextLine();
}
void calcOrder() {
double order = ((setA * 9.90) + (setB * 10.90) + (setC * 11.90) + (setD * 12.90));
double totalOrder = (order);
System.out.println("Set A " + setA);
System.out.println("Set B " + setB);
System.out.println("Set C " + setC);
System.out.println("Set D " + setD);
System.out.printf("Total price: %.2f", order);
System.out.println();
}
public static void main(String args[]) throws Exception {
Prac3_Q2_JasmineLimSmith cc = new Prac3_Q2_JasmineLimSmith();
cc.createFile();
for (int cnt = 1; cnt <= 10; cnt++) {
cc.readData();
cc.calcOrder();
}
}
}
This is the sample output
Set A 1
Set B 4
Set C 3
Set D 2
Total price: 115.00
Sorry, Im new to java, This is my code so far.
In total there would be 10 outputs like that one.
how would i take all the total prices and calculate it into 1 grand total at the very end?
Any help would be appreciated, Thank you
Welcome to StackOverflow! Are you allowed to change the return types of any methods, or add new parameters/methods? Since this seems like homework, I'll give you a general idea of two possible similar approaches.
One way to do this would be to return the total price from calcOrder (by changing the void return type to double). You can then declare an double sumOfOrders = 0 variable outside of your loop where you call calcOrder and then keep adding the return value of calcOrder to it. At the end of the loop, you will have the sum of all orders which you can print out.
For example:
double calcOrder() { // note that the return type has been changed from 'void' to 'double'
double order = ((setA * 9.90) + (setB * 10.90) + (setC * 11.90) + (setD * 12.90));
// print statements
return order;
}
Then, in your main function, you can use the return value when calling calcOrder():
double sumOfOrders = 0;
for (int cnt = 1; cnt <= 10; cnt++) {
cc.readData();
// The following can alternatively be written as
// sumOfOrders += cc.calcOrder();
sumOfOrders = sumOfOrders + cc.calcOrder();
}
System.out.printf("Sum of all orders: %.2f", sumOfOrders);
If you are not allowed to change the return types of existing methods, you could:
Make order an instance variable (e.g. private double orderPrice;
Set order to the sum of all prices (e.g. this.orderPrice = ((setA * 9.90) + ...);)
Add a getter for the orderPrice variable (e.g. by adding a double getOrderPrice() { return this.orderPrice; } method in your Prac3_Q2_JasmineLimSmith class)
Sum the orders in the same way as above:
double sumOfOrders = 0;
for (int cnt = 1; cnt <= 10; cnt++) {
cc.readData();
cc.calcOrder();
sumOfOrders = sumOfOrders + cc.getOrderPrice();
}
System.out.printf("Sum of all orders: %.2f", sumOfOrders);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
public static void inputThenPrintSumAndAverage (){
Scanner scanner = new Scanner(System.in);
int count =0;
int sum =0 ;
long average = 0;
boolean isAnInt = scanner.hasNextInt();
while (true) {
count++;
int number = scanner.nextInt();
if (isAnInt) {
sum+=number;
average = Math.round((sum/count));
} else {
break;
}
scanner.nextLine();
}
System.out.println("SUM = "+sum+ " AVG = "+average);
scanner.close();
}
When I am giving it a string it gives exception and doesn't even execute the "sum and avg" values. How can I change the code to make it work? If I have some wrong conceptual knowledge please help me understand the concept. Thank you.
You do not need Scanner#hasNextInt for Scanner(System.in). Also, you do not need the check, if (isAnInt). Instead, you should put a try-catch block.
You should not close Scanner(System.in); otherwise, there is no way to open it again without restarting the JVM.
Both the above thing are required when you use the Scanner for a File.
Demo:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Test
inputThenPrintSumAndAverage();
}
public static void inputThenPrintSumAndAverage() {
Scanner scanner = new Scanner(System.in);
int count = 0;
int sum = 0;
long average = 0;
while (true) {
try {
int number = scanner.nextInt();
sum += number;
count++;
} catch (InputMismatchException e) {
break;
}
}
average = Math.round((sum / count));
System.out.println("SUM = " + sum + " AVG = " + average);
}
}
A sample run:
2
3
5
8
abc
SUM = 18 AVG = 4
Note: you can get a better precision for average if you declare it as double and store the floating-point calculation into it without rounding e.g.
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Test
inputThenPrintSumAndAverage();
}
public static void inputThenPrintSumAndAverage() {
Scanner scanner = new Scanner(System.in);
int count = 0;
int sum = 0;
double average = 0;
while (true) {
try {
int number = scanner.nextInt();
sum += number;
count++;
} catch (InputMismatchException e) {
break;
}
}
average = (double) sum / count;
System.out.println("SUM = " + sum + " AVG = " + average);
}
}
A sample run after this change:
2
3
5
8
abc
SUM = 18 AVG = 4.5
It will also be useful for you to understand this concept.
I am going to post my code below because this is kind of hard to describe. The code below works, but it is using Math.pow in the main method rather than in the helper, so if someone could show me a way to move the power to the helper method without messing up the program that would be much appreciated.
Main method:
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer: ");
double input = keyboard.nextInt();
double x = Math.pow(2.0, input);
int n = (int)x;
System.out.println(starStr(n));
Helper method:
public static String starStr(int n)
{
if (n >= 1) {
return ("*" + starStr(n-1));
}
else {
return "";
}
}
EDIT:
if(n == 0) {
return "*";
}
else {
return starStr(n - 1) + "**";
}
Something like this would work. You don't really need to use a power function at all. Just start with 1 star and double the number of stars in every step of the recursion.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter an integer for the number of stars: ");
int input = keyboard.nextInt();
System.out.println(doStars(input));
}
public static String doStars(int n)
{
//If n == 0 the recursion is done
//Otherwise, reduce n by 1 and double the number of stars
if(n == 0)
return "*";
else
{
String output = doStars(n - 1);
return output + output;
}
}
I think this is what you are looking for. Not sure if you have learned the tree data-structure, but that's the purpose of my variable names.
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
// 1 + (2^n)-1 = 2^n
System.out.println("*" + doStars(i));
}
}
public static String doStars(int n)
{
if (n == 0) {
return "";
}
else {
String subTree = doStars(n - 1);
return subTree + "*" + subTree; // length = (2^n)-1
}
}
}
Output
*
**
****
********
****************
Visualization - read clockwise in triangles from little to big
"*"
+
doStars(2)
"*"
doStars(1) + doStars(1)
"*" "*"
doStars(0) + doStars(0) doStars(0) + doStars(0)
"" "" "" ""
So, I'm trying to create a driver for my method. I apologize in advance, I know very little about what I'm talking about. What the program does, is it calculates sine, cosine, and the exponential function by means of taylor series for a number that the user inputs. The use of Math.pow and Math.fact were not allowed. My compiler isn't giving me any errors, and I'm all out of ideas at this point. In addition, the scanner doesn't seem to stop accepting input after I press enter. It continues to take numbers, but doesn't do anything else. It gives an exception when I type a letter. High possibility of ID10T error. I know that the output isn't well formatted yet, but that's because I haven't had a chance to see it yet. If someone could help me figure this out, I would be very greatful. Thanks in advance!
-An aspiring code monkey
Driver (Lab4.java)
/*
This program is being created to solve Lab 4.
*/
import java.util.*;
public class Lab4
{
public static void main(String[] args)
{
String again, more = "y";
while (more.toUpperCase().charAt(0) == 'Y')
{
Scanner keyboard = new Scanner (System.in);
System.out.println("Input X: ");
Function number = new Function();
double x = number.x();
System.out.println("x = " + x);
Function sine = new Function();
double mySin = sine.funcSine();
Function cosine = new Function();
double myCos = cosine.funcCos();
Function expo = new Function();
double myExp = expo.funcExp();
System.out.println("\t\t\t\tLibraryResult My Result");
System.out.println("\n\t\tsin(" + Function.x() + ")" + " = " + "\t\t\t" + Math.sin(Function.x()) + "\t" + mySin);
System.out.println("\n\t\tcos(" + Function.x() + ")" + " = " + "\t\t\t" + Math.cos(Function.x()) + "\t" + myCos);
System.out.println("\n\t\texp(" + Function.x() + ")" + " = " + "\t\t\t" + Math.exp(Function.x()) + "\t" + myExp);
System.out.println("\n\t\t\tDo more (Y/N) ? ");
more = keyboard.next();
String junk = keyboard.nextLine();
}
}
}
Method (Function.java)
/*
This class provides the information for the parent to use in order to solve Lab 4.
*/
import java.util.*;
public class Function
{
Scanner keyboard = new Scanner(System.in);
public static int number;
private double temp = 1;
private double last = 1;
public static double x()
{
Scanner keyboard = new Scanner(System.in);
double x = keyboard.nextDouble();
return x;
}
public static double pow(double value, double power)
{
if(power == 0)
{
return 1;
}
double result = value;
for(int i = 0; i < power -1; i++)
{
result = result * value;
}
return result;
}
public static double getFact()
{
while (number < 0)
{
number =(number * -1);
}
double factorial = 1;
if (0 == (number % 1))
{
do
{
factorial = factorial * number;
--number;
} while (number >= 1);
}
else //Stirling's Approximation
{
double e = 2.718281828459;
double part1 = Math.sqrt(2 * 3.141592653589 * number);
double part2a = (number / e);
double part2b = (pow(part2a,number));
factorial = (part1 * part2b);
}
return factorial;
}
public static double funcSine()
{
int place = 0;
double next = x()*1;
for(number = 3; number <= 30; number = number + 2)
{
next = next + ((pow((-1),place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double mySin = next * 1;
return mySin;
}
public static double funcCos()
{
int place = 0;
double next = 1;
for(number = 2; number <= 30; number = number + 2)
{
next = next + ((pow(-1,place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double myCos = next * 1;
return myCos;
}
public static double funcExp()
{
int place = 0;
double next = 1 + x();
for(number = 1; number <= 30; number++)
{
next = next + ((pow(-1,place))*((pow(x(),number))/(getFact())));
place = place + 1;
}
double myExp = next * 1;
return myExp;
}
}
Check the syntax of your while loop:
while (more.toUpperCase().charAt(0) == 'Y')
Think about when the program will ever not satisfy this expression.
Also you have multiple Scanners all over your code. ITs not clear why you need to keep reading inout over and over again.
While doing an assignment for a BMI calculator I keep running into problems with the compiler and the method being used.
The assignment requires me to call a function double bmi to calculate the bmi. I am having problems getting the calling of the function correct. Any help would be great.
One of the errors:
Prog5.java:44: error: illegal start of expression
public static double calculateBmi(double height, double total) {
^
Code:
import java.util.Scanner;
public class Prog5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double avgweight,bmi,total,wReading;
int heightft,heightin,height,k;
String category,weightreading;
System.out.print("Enter the height(in feet and inches separated by spaces): ");
heightft = sc.nextInt();
heightin = sc.nextInt();
height = ((heightft*12)+heightin);
System.out.print("Enter the weight values separated by spaces followed by a negative number: ");
wReading = sc.nextDouble();
While (wReading >=0);
{
total = wReading+total;
Count++;
wReading = sc.nextDouble();
}
avgweight = 0;
total = 0;
weightreading = "Weight readings: " + wReading;
avgweight = total/Count;
public static double calculateBmi(double height, double total) {
{
double bmi = 0;
double total = 0;
double height = 0;
bmi = (height*703) / (total*total);
}
return bmi;
}
if ( bmi > 30)
category=("Obese");
else if (bmi >= 25)
category=("Overweight");
else if (bmi >= 18.5)
category=("Normal");
else {
category=("Underweight");
}
System.out.println("");
System.out.println("Height: "+ heightft + " feet " + heightin + " inches" );
System.out.println("Weight readings: "+ count);
System.out.println("Average weight: " + avgweight + "lbs");
System.out.println("");
System.out.printf("BMI: " + "%.2f", bmi);
System.out.println("");
System.out.println("Category: " + category);
System.out.println("");
}
private static void ElseIf(boolean b) { }
private static void If(boolean b) { }
}
The problem you mention is due to you beginning another method inside main. You instead want a structure something like:
public class Prog5
{
public static void main(String[] args)
{
// code here
}
public static double calculateBMI(double height, double total)
{
//other code
}
}
Your problem is that you are attempting to define a method (namely, public static double calculateBMi) inside a method (public static void main), and Java does not let you do that. (Basically, methods that aren't main need to be attached to a class.)
In the future, you may want to look around before asking this kind of question, since duplicate versions of this have been asked. Your question is basically: Function within a function in Java