0

I am pretty new to Java, for starters, I tried to make this script, where it will say if the length of a line is possible. Everything but isNaN part is working. If i typed for the length of the line "a", to check if everything works, then it gave error. I read some other topics about isNaN but, nothing solved my problem.

P.S. When i typed if(a == false).... then it understood the command and gave me no error.

import java.util.Scanner;

public class Length {

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);
        System.out.println("length to a line");
        double length= input.nextInt();
        boolean a = Double.isNaN(length);


        if(a == true){
            System.out.println("Please enter a number, not a letter etc");
    }           
        else if (length >= 0){
            System.out.println("You entered length that is not negative, which is good");
            if(length > 0){
                System.out.println("The length of this line is " + length);
            } if(length==0){
                System.out.println("The length is zero, that means that this isn't line, but a dot");
            }
        }

        //////with a letter it desn't give the right value

        else{
            System.out.println("Negative length of a line is not possible");

        }


        input.close();
    }

}
Madhawa Priyashantha
  • 9,208
  • 7
  • 28
  • 58
LauritsT
  • 3
  • 1
  • 6
    What exactly is the question? `input.nextInt()` will never return NaN (that cannot even be represented by an `int`). Do you want to check if the user entered a number or not? – Thilo Oct 22 '15 at 07:58
  • 2
    You are rather running into a `InputMismatchException` instead of instead of going anywhere nere your `NaN` check, if you enter a non numeric value. – SomeJavaGuy Oct 22 '15 at 07:59
  • 2
    Side note: boolean comparisons in Java can be shortened to `if (a) {` and `if (!a) {` - you don't need to explicitly compare to `true` or `false`. – JonK Oct 22 '15 at 08:02

0 Answers0