Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compiler 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) ;
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For checking errors in the name string input, I need to check if the string contains any whitespaces or not because the compiler throws java.lang.InputMismatchException 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading