javastringinputmismatchexception

Application throws InputMismatchException when string is assigned to double


I am writing a program where I need to check if a string (name) contains any whitespaces or not.

Here's part of my program :

    public static void main()
    {
        Scanner sc = new Scanner(System.in) ;
        String name = "" ;
        boolean error = false ;
        do {
            if(error) System.out.println("Sorry, error. Try again") ;
            error = false ;
            
            System.out.print("Enter your name : ") ;
            name = sc.next() ;
            if(name=="") error = true ;
        } while(error) ;
        
        double amount = 0.00 ;
        do {
            if(error) System.out.println("Sorry, error. Try again") ;
            error = false ;
            
            System.out.print("Enter amount of purchase : ") ;
            amount = sc.nextDouble() ;
            if(amount<=1) error = true ;
        } while(error) ;
    }
}

For checking errors in the name string input, I need to check if the string contains any whitespaces or not because otherwise java.lang.InputMismatchException is thrown when it accepts amount (and when the entered name contains whitespace with another string).

Is there any predefined function that does this?


Solution

  • You can use the following method to determine if a String contains a white-space character.

    boolean containsSpace(String string) {
        for (char character : string.toCharArray()) {
            switch (character) {
                case ' ', '\t', '\n', '\r', '\f' -> {
                    return true;
                }
            }
        }
        return false;
    }
    

    Also, you're going to want to test the name value using the String.equals method, as opposed to the == equality operator.

    if (name.equals("")) error = true;
    

    Furthermore, the main method requires a single String array, or String varargs parameter, to be valid.

    public static void main(String[] args)
    

    Here is a quick demonstration of how I would implement the task.

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        String name;
        while (true) {
            System.out.print("Name: ");
            name = scanner.nextLine();
            if (!containsSpace(name))
                break;
            System.out.println("Name contains white-space.  Re-enter.");
        }
        
        double amount;
        while (true) {
            System.out.print("Amount: ");
            try {
                amount = Double.parseDouble(scanner.nextLine());
                break;
            } catch (NumberFormatException exception) {
                System.out.println("Invalid amount.  Re-enter.");
            }
        }
        
        System.out.printf("Name is '%s'%n", name);
        System.out.printf("Amount is %,f%n", amount);
    }