How to Calculate the factorial of a decimal number in Java? - java

I did a function to calculate the factorial of a number , but when i writes a decimal number or a character the "mini-application" does not work. How can i calculate the factorial of a decimal and launch a message error to the user when he writes a character .?
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// BOTON CALCULAR
String valortextfield = jTextField1.getText();
int numero = Integer.parseInt(valortextfield);
Metodos metod = new Metodos();
BigInteger resultado = metod.factorial(numero);
String valorAmostrar= resultado.toString();
jTextArea1.setText(valorAmostrar);
}
the method :
public class Metodos {
public BigInteger factorial (int numero ){
if ((numero < 0)||(numero >50)) {
return BigInteger.ZERO;
} else if (numero==0){
return BigInteger.ONE;
} else {
return BigInteger.valueOf(numero).multiply(factorial(numero-1));
}
}
Thanks.

Use Scanner
java.util.Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt())
scanner.next();
System.out.println(scanner.next());

Put a try/catch block around your parseInt() call and look for NumberFormatException.
String valortextfield = jTextField1.getText();
try
{
int numero = Integer.parseInt(valortextfield);
Metodos metod = new Metodos();
BigInteger resultado = metod.factorial(numero);
String valorAmostrar= resultado.toString();
jTextArea1.setText(valorAmostrar);
}
catch (NumberFormatException e)
{
// Show an error message here or whatever is appropriate
}
This will not only catch numbers like "123.45", it will also catch other non-number input.

See this. it's an approximation

Your factorial method is fine for only integer number but there is a different approach for fraction values you have to use gamma function for it.
Approach:
First collect the input value
Validate the input, and there would be one of following three conditions :
non-numeric input: Show the error message.
integer number: populate factorial by same way as you have defined in the factorial method.
fraction number: populate factorial using gamma function as described bellow-
Following is a simple example to calculate factorial of a fraction number using gamma function
Example of factorial calculation of a fraction number:
Formula
Here taking a fraction number 1.5! as an example and apply above formula:
Useful url for Gamma Function

Related

I'm trying to write a program to determine if the input value is irrational or not by determining the number of digits. why won't it compile?

If the number of digits is infinite then I mark it as irrational and everything else is rational as it would be finite.
I tired input 3.14 but it crashed and didn't compile the output of irrational or rational.
import java.math.BigDecimal;
import java.util.Scanner;
public class non_terminating_decimals {
public static void main(String[] args) {
Scanner inputNumber = new Scanner(System.in);
System.out.println("input number : ");
BigDecimal inputnumber = inputNumber.nextBigDecimal();
BigDecimal numerofDigits = input(new BigDecimal(String.valueOf(inputnumber)));
BigDecimal infinity = BigDecimal.valueOf(Double.POSITIVE_INFINITY);
if (numerofDigits == infinity) {
System.out.println("Irrational");
}
else {
System.out.println("Rational");
}
}
static int integerDigits(BigDecimal number) {
return number.signum() == 0 ? 1 : number.precision() - number.scale();
}
static BigDecimal input(BigDecimal number) {
return BigDecimal.valueOf(0);
}
}
Let's unpack this statement:
BigDecimal infinity =
BigDecimal.valueOf(Double.POSITIVE_INFINITY);
Double.POSITIVE_INFINITY is some number.
Looking at the documentation for BigDecimal.valueOf, we see it uses Double.toString() to do the conversion.
Looking at the documentation for that, we see that a value of positive infinity results in the string "Infinity".
Thus, we're effectively left with trying to evaluate
BigDecimal("Infinity");
And if we look at the documentation for that particular constructor, there's no suggestion it can handle non-numeric string arguments.

How to Check if String contains decimal and convert to nearest Integer?

How do I check if a String contains Integer or Decimal Numbers in Java?
Further I want to round off the number to the nearest integer if it's a decimal number and then convert it back to string.
Say,I have a string called "amount" whose value can be like "23" or "33.42", In this case I would like to convert "33.42" to "33"
Below is what I tried:
// Assume amount String has already been declared
try{
Double number = Double.parseDouble(amount);
logger.info("Double Detected");
int integer = (int) Math.round(number);
logger.info("Converting to String Integer");
amount = Integer.toString(integer);
}catch(NumberFormatException e){
logger.info("Double NOT Detected");
}
I am getting Null Pointer Exception in the above code when I am trying to parse "Double", please also let me know if there's any easier way to do this.
Initialize amount to something like "" so that it won't be null if your algorithm doesn't find an Integer to convert to a string.
Try this:
amount = new BigDecimal(amount).setScale(0, BigDecimal.ROUND_HALF_UP).toString();
This will give you the output you are looking for.
To avoid the null pointer you can do a multi-catch statement, like this:
public static void main(String args[]){
String amount = "3.14159265";
try {
Double number = Double.parseDouble(amount);
System.out.println("Double Detected");
System.out.println(number);
int integer = (int) Math.round(number);
System.out.println("Converting to String Integer");
System.out.println(integer);
amount = Integer.toString(integer);
} catch (NumberFormatException | NullPointerException e1) { //catches both exceptions
System.out.println("Double NOT Detected: ");
System.out.println(e1);
}
}
Try changing amount to null or letters to see how the exception is caught.
Make sure you initialize amount also.

How do I read input that could be an int or a double? [duplicate]

This question already has answers here:
How to test if a double is an integer
(18 answers)
Closed 7 years ago.
I'm writing a program in which I need to take input from the keyboard. I need to take a number in, yet I'm not sure if it's an int or a double. Here's the code that I have (for that specific part):
import java.io.*;
import java.util.*;
//...
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
I know I can get a String and do parseInt() or parseDouble(), but I don't know which one it'll be.
Well, ints are also doubles so if you assume that everything is a double you will be OK with your logic. Like this:
import java.io.*;
import java.util.*;
Scanner input = new Scanner(System.in);
double choice = input.nextDouble();
It only get complex if you needed the input to be an integer for whatever reason. And then, parseInt() to test for int would be just fine.
Just use a double no matter what it is. There is no noticeable loss on using a double for integral values.
Scanner input = new Scanner(System.in);
double choice = input.nextDouble();
Then, if you need to know whether you've gotten a double or not, you can check it using Math.floor:
if (choice == Math.floor(choice)) {
int choiceInt = (int) choice);
// treat it as an int
}
Don't mess with catching NumberFormatException, don't search the string for a period (which might not even be correct, for example if the input is 1e-3 it's a double (0.001) but doesn't have a period. Just parse it as a double and move on.
Also, don't forget that both nextInt() and nextDouble() do not capture the newline, so you need to capture it with a nextLine() after using them.
What I would do is get String input, and parse it as either a double or an integer.
String str = input.next();
int i = 0;
double d = 0d;
boolean isInt = false, isDouble = false;
try {
// If the below method call doesn't throw an exception, we know that it's a valid integer
i = Integer.parseInt(str);
isInt = true
}catch(NumberFormatException e){
try {
// It wasn't in the right format for an integer, so let's try parsing it as a double
d = Double.parseDouble(str);
isDouble = true;
}catch(NumberFormatException e){
// An error was thrown when parsing it as a double, so it's neither an int or double
System.out.println(str + " is neither an int or a double");
}
}
// isInt and isDouble now store whether or not the input was an int or a double
// Both will be false if it wasn't a valid int or double
This way, you can ensure that you don't lose integer precision by just parsing a double (doubles have a different range of possible values than integers), and you can handle the cases where neither a valid integer or double was entered.
If an exception is thrown by the code inside the try block, the code in the catch block is executed. In our case, if an exception is thrown by the parseInt() method, we execute the code in the catch block, where the second try-block is. If an exception os thrown by the parseDouble() method, then we execute the code inside the second catch-block, which prints an error message.
You could try using the floor function to check if it is a double. In case you don't know, the floor function basically cuts off any decimal numbers. So you can compare the number with and without the decimal. If they are the same, then the number can be treated as an integer, otherwise a double (assuming you don't need to worry about large numbers like longs).
String choice = input.nextLine();
if (Double.parseDouble(choice) == Math.floor(Double.parseDouble(choice)) {
//choice is an int
} else {
//choice is a double
}

Java Exception Handling - ID Number Machine

I'm in the process of improvement my skills in Java, now I am doing some exercises of exceptions, but I am stuck in this exercise:
ID Number Machine: Ask a user for a ID number. The correct input for a
id number is 10 in length and they must all be numbers.
Input: 123456790 Output: correct
Input: 12eer12345 Output: incorrect
Input: 12345678901 Output: incorrect
I don’t know what exception use to make the program work, i know the NumberFormatException can be use to check if the string is numeric, but in general im stuck, thanks is anybody can help me.
I’m trying to make it work with the great help you give me guys, in the page where the exercises are they give you the problem some code and you have to complete that code, so far I make this code with the code they give you:
import java.util.Scanner;
class Challenge{
public static void main(String args[]){
Scanner scanner=new Scanner(System.in);
String input;
int num;
System.out.println("Enter the ID number:");
input = scanner.next();
///{Write your code here
try
{
num = Integer.parseInt(input);
}
catch(NumberFormatException nfe)
{
System.out.println("incorrect");
}
if(input.length()==10)
System.out.println("correct");
///}
}
}
I’m trying to run that and when I use the number 1234567890 the output is "correct", and if I use the string 123qwerqw the output is "incorrect" and this is correct behaviour. But when I use 1234 the program sticks and does not show anything.
The NumberFormatException is the exception that is thrown if an operation is attempted using an input value that does not match the expected form.
To see if a string is actually a number, the logic is to try to parse it to an integer.
If it throws a number format exception, it cannot be converted.
If you want to be able to deal with decimal numbers, you would need to parse to a Double using Double.ParseDouble.
Using Integer.ParseInt will fail if you enter any number that is not whole.
public boolean isValidNumber(String val) throws NumberFormatException {
try {
int i = Integer.ParseInt(val);
} catch (NumberFormatException nfe) {
//you know here that you have non numeric chars
return false;
}
//To check the length...
if (val.length > 10) {
return false;
}
return true;
}
To use the isValidNumber method....
String myNumber = "123456";
String myNotNumber = "a small town with views of the sea";
if (isValidNumber(myNumber)) {
System.out.Println(String.format("The number {0} is valid", myNumber).toString());
} else {
System.out.Println(String.format("The number {0} is not valid", myNumber).toString());
}
The logic of this is that if the number does contain any non-numeric values, the error is thrown when we try to convert the string to an int.
We catch the error, and return false from the method.
If the string does parse to an int, we know it's all numeric (and as we're using an integer, we know it's not a decimal).
The second test deals with the length - again, we return a false if the value does not match the criteria specified. Anything longer than 10 chars is invalid, so return a false.
The final return statement can only be reached if all the preceding checks have passed.
I'm not certain this will compile straight off (I'm writing it from memory having not used Java for about 2 years), but that is the basic logic for it.
Here is the code working for my problem:
import java.util.Scanner;
class Challenge{
public static void main(String args[]){
Scanner scanner=new Scanner(System.in);
String input;
int num;
System.out.println("Enter the ID number:");
input = scanner.next();
///{Write your code here
try
{
num = Integer.parseInt(input);
System.out.println(input.length()==10?"correct":"incorrect");
}
catch(NumberFormatException nfe)
{
System.out.println("incorrect");
}
///}
}
}

Java -- How to make a continous counter (1 + 2 = 3; + 3 = 6) etc

I'm not sure if this is possible in Java. I just finished Python and I've taken a webdesign course, so my brain isn't synced with Java yet.
I want it to be something like this
double yourInput = input.nextDouble();
double numCount = (numCount + yourInput);
For example, if I entered 2, 7, and 9 (it would loop) I would want it to do something like this: numCount = 0; then numCount = 0 + 2; then numCount = 2 + 7; then numCount = 9 + 9.
Is this possible in Java? If so, how?
Just loop using input.hasNextDouble():
//give default value
double numCount = 0;
//while user is still giving input
while(input.hasNextDouble()) {
//get input
double yourInput = input.nextDouble();
//add input
numCount += yourInput;
}
//output
System.out.println("total = " + numCount);
Algorithm CONTINOUS_COUNTER()
BEGIN
DECLARE inputReader : java.util.Scanner(System.in);
DECLARE numCount : Double;
SET numCount := 0.0; //Setting the default value to the counter;
LOOP until inputReader.hasNextDouble() returns TRUE
numCount := numCount + inputReader.nextDouble();
END LOOP;
print "Num count = " + numCount;
END;
Dear Katy, this is the logic you should use to develop this program. This is just an algorithm. I don't think it's good to post the real program here, since you are learning Java. Try to convert this algorithm to the Java code. Learn it. :)
Here a working example:
import javax.swing.JOptionPane;
public class DoubleCounter {
private static double total = 0.0;
public static void run(){
while(true){
String input = JOptionPane.showInputDialog("Total Count: "+ total+" add next double: ");
try{
double next = Double.parseDouble(input);
total+=next;
}catch(NumberFormatException nfe){
JOptionPane.showMessageDialog(null, "Wrong input! You must get a valid number!");
continue;
}
}
}
public static void main(String[] args) {
DoubleCounter.run();
}
}
You define a class DoubleCounter with a static member total count.
This class has a run() method that infinitly loop and show ad InputDialog.
The input dialog alway return a string that we 'try' to parsed in a double.
If parsed without problem, we add the result to the total count.
The class has a main method that is the application entry point that 'statically' call run() method of DoubleCounter.
I suggest you to see how 'static' modifier work on class member (total) and on methods (run()).
Hope helped you!
Katy, this is the real program.
import java.util.Scanner;
public class ContinousCounter{
public static void main(final String [] args){
double numCount = 0.0;
Scanner inputReader = new Scanner(System.in);
System.out.println("Enter the values : ");
while(inputReader.hasNextDouble()){ numCount += inputReader.nextDouble();}
System.out.printf("The value for numCount = %f",numCount);
}
}
In order to do what I think you're saying here, you should be using a while loop. It is fairly simple, just think about how you want it to work. It will loop a block of code that adds the scanner's next line to a sum
double mySum = 0;
while(input.nextDouble() != 0){
double myInput = input.nextDouble();
mySum += myInput;
}
In the above loop, we are assuming that when the scanner's next line is 0 there are no more numbers to add, but that can be adjusted so that it stops at other times.
I can see that since you have completed a course in Python programming that you are able to come up with the logic for this and are only looking for convention or proper syntax, so let's explain how the above works:
A while loop will run as long as the statement you let it handle evaluates to true, if you want it to do something while false you can put use an exclamation point before your statement and encase your parameters in parentheses such as the following : while (!(x<=2))
A while loop has the following syntax (in logical form):
while (boolean) {run this code}
You can use the shorthand for adding myInput to your mySum:
+= will add the righthand side to the lefthand side and save that value
If you want to run the code at least once despite the value, you can use a do while loop. The logic behind it is: do {this} while (boolean);

Categories