Calculation of pi with an infinite series - java

I approximate pi with this series:
pi = 4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ...
My code is in the loop. When I enter the first time in loop, the result is exactly what I want, but at the second time it is not.
package pi_number;
import java.util.Scanner;
public class Pi_number {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
double pi=0.0;
double termx=0.0;
System.out.print("Enter any key to start or E stop: ");
String Exit=input.next();
while (!Exit.equals("E"))
{
System.out.print("How many term do you want : ");
int term=input.nextInt();
for(int i=1;i<=term; i++)
{
if(i%2==0)
{
termx=(double)-4/(2*i-1);
}
else
{
termx=(double)4/(2*i-1);
}
pi+= termx;
}
System.out.println("Pi number equals="+pi);
System.out.print("Enter any key to start or E stop: ");
Exit=input.next();
}
}
}

You need to initialize termx and pi before calculation loop:
while (!Exit.equals("E"))
{
termx = 0.0; //initial
pi = 0.0; //initial
System.out.print("How many term do you want : ");
int term=input.nextInt();
for(int i=1;i<=term; i++)
{
if(i%2==0)
{
termx=(double)-4/(2*i-1);
}
else
{
termx=(double)4/(2*i-1);
}
pi+= termx;
}
System.out.println("Pi number equals="+pi);
System.out.print("Enter any key to start or E stop: ");
Exit=input.next();
}

Initialize your pi and terms before starting to calculate your pi.
Try this code :
package pi_number;
import java.util.Scanner;
public class Pi_number {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double pi,termx;
System.out.print("Enter any key to start or E stop: ");
String Exit = input.next();
while (!Exit.equals("E")) {
System.out.print("How many term do you want : ");
int term = input.nextInt();
pi=0.0;
termx=0.0;
for (int i = 1; i <= term; i++) {
if (i % 2 == 0) {
termx = (double) -4 / (2 * i - 1);
} else {
termx = (double) 4 / (2 * i - 1);
}
pi += termx;
}
System.out.println("Pi number equals=" + pi);
System.out.print("Enter any key to start or E stop: ");
Exit = input.next();
}
}
}

Related

Is there any way of making this method run more than twice

I was asked to write a simple calculator that could run many times as long as the user inputs 'yes' when asked "would you like to perform another operation".
so I did it using a separate method that would be used in a loop in the main method, the problem is it wont run more than twice if the answer is yes
import java.util.Scanner;
public class Calc2 {
// method to be called
static String calcmethod() {
#SuppressWarnings("resource")
Scanner Operation = new Scanner(System.in);
System.out.println("choose operation to perform");
float x, y, sum, sub, mul, div;
String g;
g = Operation.nextLine();
if (g.equals("addition")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
sum = x + y;
System.out.print(sum + "\n");
} else if (g.equals("subtraction")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
sub = x - y;
System.out.print(sub);
} else if (g.equals("multiplication")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
mul = x * y;
System.out.print(mul);
} else if (g.equals("division")) {
System.out.println("input the first number ");
x = Operation.nextFloat();
System.out.println("input the second number ");
y = Operation.nextFloat();
div = x / y;
System.out.print(div);
} else {
System.out.println("invalid input \n");
}
System.out.println("would you like to peform another operation \n");
Scanner Flow = new Scanner(System.in);
String w;
w = Flow.nextLine();
return w;
}
public static void main(String[] args) {
String z = calcmethod();
if (z.equals("yes")) {
calcmethod();
} else {
System.out.println("end of program");
}
}
}
Use do-while loop as shown in below example:
public static void main(String[] args) {
String z = "";
do {
z = calcmethod();
} while(z.equals("yes"));
System.out.println("end of program");
}

Java: how to repeatedly asks the user for Y or N

I am doing a JAVA project for newton iteration, but I am stuck in how to make the program keep asking the user if they want to keep going or not. And also how to make sure when the user entering negative numbers, the result is not showing the root is the negative number that user entered.
import java.util.Scanner;
/**
* Computes estimate of square root of x to within relative error 0.01%.
*
* #param x
* positive number to compute square root of
* #return estimate of square root
*/
public final class Newton1 {
private static double sqrt(double x) {
if (x < 0) {
System.out.println("Please enter a postive number.");
return x;
}
double Error = 0.0001;
double t = x;
while (Math.abs(t - x / t) > Error * t) {
t = (x / t + t) / 2.0;
}
return t;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Please enter a number: ");
double x = in.nextDouble();
System.out.println("Square root is " + sqrt(x));
System.out.println("Do you want to continue? (Enter Y or N): ");
String f = in.nextLine();
while (true) {
if (f.equalsIgnoreCase("Y")) {
} else {
break;
}
}
}
}
Your while statement appears to be in the wrong place. Try this:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
do {
System.out.println("Please enter a non-negative number: ");
double x = in.nextDouble();
} while (x < 0);
System.out.println("Square root is " + sqrt(x));
System.out.println("Do you want to continue? (Enter Y or N): ");
String f = in.nextLine();
if (!f.equalsIgnoreCase("Y")) {
break;
}
}
}
Note that until the user enters a non-negative number, they will continue to be prompted for a non-negative number.

Code is not printing results

I'm getting the prompt to enter an integer but nothing after that. Can someone tell me why my results are not printing?
import java.util.Scanner;
public class ChapterThreeQuiz {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("Enter a three-digit integer: ");
double answer = input.nextDouble();
double x = input.nextDouble();
double y = input.nextDouble();
double z = input.nextDouble();
if (x == z && y == y && z == x)
System.out.println(answer + " is a palindrome! ");
else
System.out.println(answer + " is not a palindrome");
}
}
double answer = input.nextDouble();
double x = input.nextDouble();
double y = input.nextDouble();
double z = input.nextDouble();
Your code is waiting for 4 different inputs. If you input all 4, it will run - but something is clearly wrong with your logic.
As others mentioned, you are a) working with doubles and b) trying to read too many numbers:
import java.util.Scanner;
public class ChapterThreeQuiz {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a three-digit integer: ");
// Read an int
int answer = 0;
try {
answer = input.nextInt();
}
catch (InputMismatchException ex) {
// Handle error
}
// Make sure it's 3 digits
if (answer < 100 || answer >= 1000) {
// Do something with bad input
}
else {
// Just need to check if first and third digits are equal.
// Get those values using integer math
int digit1 = answer / 100;
int digit3 = answer % 10;
if (digit1 == digit3) {
System.out.println(answer + " is a palindrome! ");
}
else {
System.out.println(answer + " is not a palindrome");
}
}
}
}
import java.util.*;
class Palindrome
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.print("Enter a string : ");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
}
}
/*
OUTPUT:
Enter a string : MADAM
Entered string is a palindrome.
Enter a string : 15351
Entered string is a palindrome.
*/
You are using wrong logic here.If you want to check for palindrome, you should not use double.Hope this code helps!

Why is my loop skipping my if/else statements after the first time?

the if statements get ignored after the first time
import java.util.Scanner;
public class practiceProgram3SecondTry
{
static Scanner scan = new Scanner(System.in);
public static void main (String[] args)
{
System.out.println("This program is intended to convert a temperature from Celcius to Fahrenheit, and other way around.");
int infiniteLoop = 0;
int oneLimitLoop = 0;
for(int x = 0 ; x < 1 ; x--)
{
//**System.out.println(infiniteLoop); // loop tester
System.out.println("Is it is Celcius, or Fahrenheit");
System.out.println("Please enter C/c frr celcius, or F/f for Fahrenheit");
String tempType = scan.nextLine();
scan.nextLine();
System.out.println("You may now enter the desisred temperature you would like to convert");
int tempNumber = scan.nextInt();
if (tempType.equalsIgnoreCase("c"))
{
int celcius = tempNumber;
int celciuscConverter = (9*(celcius)/5)+32;
System.out.println(celciuscConverter);
}
else if (tempType.equalsIgnoreCase("f"))
{
int fahrenheit = tempNumber;
int farenheitConverter = 5 * (fahrenheit-32)/9;
System.out.println(farenheitConverter);
}
}
}
}
Quick answer to your question: when you call scan.nextInt(), only the Integer you entered is read, the new line character '\n' is kept on the buffer, so the next scanNextLine will read that new line as an empty string in the following loop.
A quick fix would be to simple read the whole line and try to parse as int. Also you should really use a while(true) if you intend to do infinite loop.
public static void main(String[] args) {
System.out.println(
"This program is intended to convert a temperature from Celcius to Fahrenheit, and other way around.");
int infiniteLoop = 0;
int oneLimitLoop = 0;
for (int x = 0; x < 1; x--) {
// **System.out.println(infiniteLoop); // loop tester
System.out.println("Is it is Celcius, or Fahrenheit");
System.out.println("Please enter C/c frr celcius, or F/f for Fahrenheit");
String tempType = scan.nextLine();
//scan.nextLine();
System.out.println("You may now enter the desisred temperature you would like to convert");
int tempNumber = Integer.parseInt(scan.nextLine())
if (tempType.equalsIgnoreCase("c")) {
int celcius = tempNumber;
int celciuscConverter = (9 * (celcius) / 5) + 32;
System.out.println(celciuscConverter);
} else if (tempType.equalsIgnoreCase("f")) {
int fahrenheit = tempNumber;
int farenheitConverter = 5 * (fahrenheit - 32) / 9;
System.out.println(farenheitConverter);
}
}
}

Find High and Low Temp (JAVA) 1st Homework

I cant seem to figure it out. I need to ask the user for 3 floats, got it. Having trouble with the output of the high and low part. Any help would be awesome!
package temp;
import java.util.Scanner;
/**
*
* #author Pherman
*/
public class Temp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
float temp1;
float temp2;
float temp3;
float highTemp;
float lowTemp;
System.out.print("Please enter your first temperature");
temp1=scan.nextFloat();
System.out.print("Please enter your second temperature");
temp2=scan.nextFloat();
System.out.print("Please enter your third temperature");
temp3=scan.nextFloat();
}
}
Here is a tip for you.
http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html
float highTemp = Math.max(temp1, Math.max(temp2, temp3); // high
float lowTemp = Math.min(temp1, Math.min(temp2, temp3); // low
float middleTemp = (temp1 + temp2 + temp3) - highTemp - lowTemp; // middle
In this approach, there is no need to use if, switch, array or to sort.
I would use an array, and Arrays.sort(float[]) like so
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
float[] temp = new float[3];
for (int i = 0; i < temp.length; ) {
System.out.printf("Please enter your temperature #%d ", i);
if (scan.hasNextFloat()) {
temp[i] = scan.nextFloat();
i++;
} else {
scan.next();
}
}
java.util.Arrays.sort(temp);
System.out.println("Low = " + temp[0]);
System.out.println("High = " + temp[temp.length - 1]);
}
Using Collections to min/max
List<Float> myList = new ArrayList<Float>();
System.out.print("Please enter your first temperature");
myList.add(scan.nextFloat());
System.out.print("Please enter your second temperature");
myList.add(scan.nextFloat());
System.out.print("Please enter your third temperature");
myList.add(scan.nextFloat());
System.out.println(Collections.min(myList));
System.out.println(Collections.max(myList));
You can also use a loop to get your input instead of using System.out.print
Initialize highTemp and lowTemp whenever you can and update their values when necessary.
Use the if keyword.

Categories