P
P
PRAIT2019-08-11 14:34:57
Java
PRAIT, 2019-08-11 14:34:57

How to cast integer to double type in conditional statement?

Hi guys! I already asked a similar question in this thread How to cast an integer to double and then times...
But how to do the same in this example:

package Tu;

import java.util.Scanner;

public class ComplexCalculator {

  public static void main(String[] args) {
    try (Scanner dev = new Scanner(System.in)) {
      int a, b, result = 1;
      char ch;
      System.out.println("Plese enter operator {+, -, *, /, %, ^, !, v, 2, 3}");
      ch = dev.nextLine().charAt(0);
      if (ch == '!') {
        System.out.println("Please enter A");
        a = dev.nextInt();
        for (int i = 1; i <= a; i++) {
          result = result * i;
        }
        System.out.println("a! = " + (result));
      } else if (ch == 'v') {
        System.out.println("Please enter A");
        
      }
    }
  }
}

This is a calculator that calculates the factorial of a number and the square root.
I have a variable of type Int (a) is it possible to cast it to double and calculate the square root in the condition?
else if (ch == 'v') {
        System.out.println("Please enter A");

After all, now it is necessary that the user enters a number and it is necessary that this number be transferred from int to double.
I can do like this:
else if (ch == 'v') {
        System.out.println("Please enter A");
        a = dev.nextInt();

But do you need a double type? Can you please tell me how to translate it into a condition? Or do you still need to declare a new variable in this case? Thanks!!!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
GavriKos, 2019-08-11
@PRAIT

Why do you need to declare a variable outside of ifs? Declare inside, in case of factorial int, in case of root - double. And read the input accordingly.
If you really need it outside, then you need to declare it as the maximum allowable type for all operations - i.e. double, and already in special cases (factorial) - lead to an int (with a check, and suddenly there is still not a whole).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question