javablank-line

read blank input and even the numeric input


I tried to make a coding about read the value o sign of numers,and also I have to include the blank space as input,I could read and identify the numers' value,but I could read the blank input and give the error (exception in thread "main" java.lang.numberformatexception: for input string: ")

import java.util.Scanner;

public class CheckingSign {
  public static void main (String[] args) {
    Scanner scanner = new Scanner(System.in);
      System.out.print("Enter floating point value: ");
        String number = scanner.nextLine();
        int n = Integer.parseInt(number);


              if ( n > 0 ) {
              System.out.print("DEBUG:the user input is <   " + number + "  >");
              System.out.println("DEBUG:the trimed input is <" + number + ">");
              System.out.println("The sign of the input is 1");
            } else if ( n < 0 ) {
              System.out.print("DEBUG:the user input is <   " + number + "  >");
              System.out.println("DEBUG:the trimed input is <" + number + ">");
              System.out.println("The sign of the input is -1");
            } else {
              System.out.print("DEBUG:the user input is <   " + number + "  >");
              System.out.println("DEBUG:the trimed input is <" + number + ">");
              System.out.println("Encountered blank input.");

            }
     }

}


Solution

  • Surround the parse with a try-catch statement

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter floating point value: ");
        String number = scanner.nextLine();
        
        try {
            
            float n = Float.parseFloat(number);
            
            if ( n > 0 ) {
              System.out.print("DEBUG:the user input is <   " + number + "  >");
              System.out.println("DEBUG:the trimed input is <" + number + ">");
              System.out.println("The sign of the input is 1");
            } else if ( n < 0 ) {
              System.out.print("DEBUG:the user input is <   " + number + "  >");
              System.out.println("DEBUG:the trimed input is <" + number + ">");
              System.out.println("The sign of the input is -1");
            }
            
        } catch (Exception e) {
            
            System.out.print("DEBUG:the user input is <   " + number + "  >");
            System.out.println("DEBUG:the trimed input is <" + number + ">");
            System.out.println("Encountered blank input.");    
            
        }