I can not enter the if with a data entered by the user [closed]

0

My problem is that I am asking for a number by keyboard to get the square root, but if it is less than 0 the code should not be executed, I do it but it throws me this problem:

Problem

Ingrese el radicando
-9
La raíz de -9.0 es: NaN

Code

import java.util.Scanner;

public class RaizCuadrada {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    int num;
    float resultado;

    System.out.println("Ingrese el radicando");

    num = sc.nextInt();

    if(num <= 0) {
        System.out.println("Debe ingresar un numero mayor a 0");
    }else{
        resultado = (float) Math.sqrt(num);

        System.out.println("La raiz de " + num + " es: " + resultado);
    }
 }
}
    
asked by darioxlz 29.01.2018 в 23:03
source

1 answer

1

I think the code can be improved, leading the user to enter only what is required for the calculation: a positive number .

This program will determine if the entry is a valid number (in case the user enters otherwise), and then determine if that number is positive:

    int num;
    float resultado;
    Scanner sc = new Scanner(System.in);

    do {
        System.out.print("Por favor entre un número positivo: ");
        while (!sc.hasNextInt()) {
            String input = sc.next();
            System.out.printf("\"%s\" No es válido. Por favor entre un número positivo: ", input);
        }
        num = sc.nextInt();
    } while (num <= 0);

    resultado = (float) Math.sqrt(num);
    System.out.println("La raiz de " + num + " es: " + resultado);
    sc.close();

Test:

Por favor entre un número positivo: f
"f" No es válido. Por favor entre un número positivo: -6
Por favor entre un número positivo: 0
Por favor entre un número positivo: m
"m" No es válido. Por favor entre un número positivo: 44
La raiz de 44 es: 6.6332498
    
answered by 30.01.2018 / 00:18
source