1

I'm trying to write a code that checks your gender and the .length of your name. I'm getting an error that reads: "Exception in thread "main" java.util.NoSuchElementException: No line found." ...I need some help with the syntax, thank you.

   import java.util.Scanner;

public class nameEvaluator {
String gender = maleOrFemale();
int nameLength = lengthOfName();

public String maleOrFemale () {
        Scanner maleorfemale = new Scanner(System.in);
        System.out.println("Enter gender, male or female:");
        String gender = maleorfemale.nextLine();
        maleorfemale.close();
        return gender;
}        

public void confirmUserInput1 () {
    if (gender.equals("male")||gender.equals("female")){
    System.out.println("Thank you...");} else {System.out.println("Please, write male or female:");}    
    }

public int lengthOfName() {
        Scanner name = new Scanner(System.in);
        System.out.println("Enter your name, please:");
        String yourname = name.nextLine();
        name.close();
        return yourname.length();
}

 public static void main (String[]args) {
     nameEvaluator user = new nameEvaluator();
 }}
  • 1
    please understand the difference between scanner.next() and scanner.nextLine() methods.. Also, class variables should generally not be assigned with function calls. Create a constructor to do it. That way you don't have to declare so many scanner variables.. – whiplash Feb 20 '20 at 00:51
  • You should not be continually creating new Scanner objects. Create one near the beginning of your program and make it either an instance variable or pass it to your functions. – NomadMaker Feb 20 '20 at 01:10
  • When y o u close a scanner, it closes the underlying stream. So the next time you try to use a scanner, the stream is closed, so it thinks there is no input. – NomadMaker Feb 20 '20 at 01:12
  • Have you seen this SO question: [Close a Scanner linked to System.in](https://stackoverflow.com/questions/14142853/close-a-scanner-linked-to-system-in) – Abra Feb 20 '20 at 02:57

0 Answers0