-1

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.");

            }
     }

}

timrau
  • 22,578
  • 4
  • 51
  • 64
Alex H.
  • 3
  • 1
  • `Enter floating point value` - For this, you need `float n = Float.parseFloat (number);` instead of `int n = Integer.parseInt (number);` – Kitswas Oct 31 '22 at 16:08
  • It still giving me the same error when I try to put blank space as input – Alex H. Oct 31 '22 at 16:11
  • Exception in thread "main" java.lang.NumberFormatException: empty String at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842) – Alex H. Oct 31 '22 at 16:11

1 Answers1

0

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.");    
        
    }
mmartinez04
  • 323
  • 1
  • 1
  • 4