简体   繁体   中英

How to tell if the user has inputted a string?

Java is pretty easily with whether you've entered a number such as .hasNextInt() but what about a String ?

do {
    System.out.println("Please enter the students name: ");
    String name = s.nextLine();

    if (name.equalsIgnoreCase("Done")) {
        finished = true;
    } else {
        System.out.println("Please input the students number");
        int studentNo = s.nextInt();
        System.out.println("Please enter that students subject:  ");
        String subject = s.next();
        System.out.println("Pleae enter that students level- ");
        int level = s.nextInt();

        StudentRecords newStudent = new StudentRecords(name, studentNo, subject, level);
        studentRecordList.add(newStudent);
    }
} while (!finished);

How would I get it to loop around to make sure the user enters a String for the students name, not int etc.

Thank you.

Try the following loop using Regex:

String name="";
while(!name.matches("[a-zA-Z \'\-ÄäÖöÜüßÉéæø]+")){
    System.out.println("Please enter the student name: ");
    name = s.nextLine();
}

This will ask for the user input, until a valid name is given.

Regards so my comment, something like this will do the work:

if(!name.matches(".*\\d.*")){
    //It is correct name, because it does not contain any integer.
} else{
    //retry getting name from user because it contains integer.
}

Edit regards to comment : the above code, will detect if the input contains any integer, but if you want to check if it just contains character you could use this :

!name.matches("[a-zA-Z ]+")

You could use a regular expression that only allows letters and spaces like so:

    boolean nameIsValid = false;
    while (!nameIsValid)//while name is not valid
    {
    System.out.println("Please enter the students name: ");
    String name = s.nextLine();
    if (name.matches("[A-Za-z ]*"))//match only letters/spaces
        nameIsValid = true;//we have a valid name, we may now break out of the loop
    else
        System.out.println("Please enter a valid name!");//invalid name, loop again
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM