0

Hello again fellow programmers. I have another problem that's puzzling me. I am trying to receive input from a user but always receive an "java.util.NoSuchElementException: No line found". I have tried all the methods I've searched with no luck. Here is my code:

import java.util.Scanner;
import java.io.*;

public class UserLog {
    static String username;
    static String password;
    static String passcompare;
    static File name;
    static String Userfile = "username-";
    static String Passfile = "password-";

    public static void main(String[] args) {
        menu();
    }

    public static void menu(){
        boolean call = false;
        try (Scanner in = new Scanner(System.in)) {
            do {
                System.out.println("Select an option: ");
                System.out.println("1: New account \n"
                                 + "2: Existing account");
                System.out.print("-");
                int choice = in.nextInt();
                in.nextLine();

                 switch(choice) {
                     case 1:
                         call = true;
                         System.out.println("\nNew account called\n");
                         userCreate();
                         break;
                     case 2:
                         call = true;
                         System.out.println("\nExisting account called\n");
                         login();
                         break;
                     default:
                         System.out.println("\nNot a valid option\n");
                 }
            } while(!call);
            in.close();
        }
        catch(Exception ex) {
            System.out.println("Exception Text: " + ex);
        }
    }

    static void login(){       
        try (Scanner in = new Scanner(System.in)) {
            System.out.println("LOGIN SCREEN\n");
            System.out.print("Username: ");

            username = in.nextLine();
            name = new File("user-" + username + ".txt");
            if(name.exists()) {
                System.out.println("Username exists");

                System.out.print("Password: ");

                password = in.nextLine();
                //scans userfile for password
                if(password.length() != 0 && password.length() >= 8 /* and password-username match */) {
                    System.out.println("Login successful");
                    in.close();
                }
            }

            else {
                System.out.println("Username doesn't exist in system");
                System.out.println("Would you like to create this user? (y/n)");
                System.out.print("-");

                char choice = (char)System.in.read();

                switch(choice) {
                    case 'Y':
                    case 'y':
                        System.out.println("Creating user " + username);
                        name = new File("user-" + username + ".txt");
                        name.createNewFile();
                        System.out.println("User created");
                        passCreate(name);
                        in.close();
                        break;
                    case 'N':
                    case 'n':
                        System.out.println("Denied creation of user");
                        in.close();
                        break;
                    default:
                        System.out.println();
                }
            }
            in.close();
        } catch (IOException ex) {
            System.out.println("Exception Text: " + ex);
        }
    }

    private static File nameCreate() {
        try (Scanner user = new Scanner(System.in)) {
            System.out.print("Enter Username: ");

            username = user.nextLine();
            name = new File("user-" + username + ".txt");

            if(!name.exists()) {
                name.createNewFile();
                try (FileWriter fw = new FileWriter(name)) {
                        fw.write(Userfile + username + "\n");
                        fw.write(Passfile);
                        fw.flush();
                        fw.close();
                }
                catch(Exception ex) {
                    System.out.println("Exception Text: " + ex);
                }

                //puts lines of text in the file-
                //username-"username"
                //password-
                //
                System.out.println("User Created\n");
            }
            else if(name.exists()) {
                System.out.println("User already exists\n");
                nameCreate();
            }
            user.close();
        }
        catch(Exception ex) {
            System.out.println("Exception Text: " + ex);
        }
        return name;
    }

    private static void passCreate(File user) {
        username = user.toString();
        System.out.println(username + "\n");

        boolean code = false;

        try (Scanner pass = new Scanner(System.in)) {
            do{
                //opens file and reads until line "password-" and appends it with created password once confirmed
            System.out.println("Create a password");
            System.out.print("Password: ");
            password = pass.nextLine(); 

                if(password.length() >= 8) {
                    System.out.print("Confirm Password: ");
                    passcompare = pass.nextLine();

                    if(password.equals(passcompare)) {
                        code = true;
                        System.out.println("Passwords match\n");
                        //stores password
                    }
                    else {
                        System.out.println("Passwords don't match\n");
                    }   
               }
               else {
                   System.out.println("Password needs to be longer than 8 characters\n");
               }

            }while(!code);
            pass.close();
        }
        catch(Exception ex) {
            System.out.println("Exception Text: " + ex);
        }     
    }

    private static void userCreate() {
        nameCreate();
        passCreate(name);
    }
}

It's ugly and incomplete, I know, but this problem has kept me from going further. I am able to get to the password creation if I go through existing user option and create a user that way, but if I try to go through the create new user, I get the no line exception. My question is: how do I create more lines for the scanner to use to be able to create a password, or what other options do I have for completing this task. I've tried hasNextLine() and that's what made me realize that there are no more lines. Thanks

FThompson
  • 28,352
  • 13
  • 60
  • 93
  • Is it possible to only show us the part of the code that is relevant to the `NoSuchElementException`? – Dennis Meng Jul 17 '13 at 06:50
  • Relevant, and may answer your question: http://stackoverflow.com/questions/13042008/java-util-nosuchelementexception-scanner-reading-user-input – Dennis Meng Jul 17 '13 at 06:53
  • yes, but it only happens when going through option 1 at the beginning of the program. it's in the passCreate function – TechnicalCustoms Jul 17 '13 at 06:54
  • Sure. In option 2 (user already existing), you don't appear to be trying to close the `Scanner` until after the username is inputted. But in option 1, you get the username, close the `Scanner`, then try to make another `Scanner` with `System.in` for the password. – Dennis Meng Jul 17 '13 at 06:57
  • I see. Thanks for the link. It clarified it a alot – TechnicalCustoms Jul 17 '13 at 06:59

1 Answers1

2

Closing the Scanner instances causes the underlying InputStream to be closed and causes a NoSuchElementException to be thrown on subsequent reads. There's no need to close Scanner unless you wish subsequent reads to fail.

  • Create a single Scanner instance are use for all methods.
  • Don't close Scanner
  • Java is an OO language. Use non-static methods.

The result:

public class UserLog {
   private String username;
   // more variables...

   private final Scanner in;

   public UserLog() {
      in = new Scanner(System.in);
   }

   public static void main(String[] args) {
      UserLog userLog = new UserLog();
      userLog.showMenu();
   }

   public void menu() {
      boolean call = false;

      do {
         try {
            System.out.println("Select an option: ");
            System.out.println("1: New account \n" + "2: Existing account");
            System.out.print("-");
            int choice = in.nextInt();
            in.nextLine();

            switch (choice) {
            case 1:
               call = true;
               System.out.println("\nNew account called\n");
               userCreate();
               break;
            case 2:
               call = true;
               System.out.println("\nExisting account called\n");
               login();
               break;
            default:
               System.out.println("\nNot a valid option\n");
            }

         } catch (InputMismatchException e) {
            System.out.println("Invalid option " + in.nextLine());
         }
      } while (!call);
   }
   ...
} 
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Oh, never thought of this. So if we use a scanner to read from System.in, we shouldn't close scanner because the underlying stream would be closed too? – zEro Jul 17 '13 at 07:06
  • In that case, a silly follow up question: is there a way to reinitialize (reopen) `System.in` with the standard input stream? – zEro Jul 17 '13 at 07:09
  • No, just don't close the `Scanner` – Reimeus Jul 17 '13 at 07:11
  • so i basically removed all the .close() statments and it works. but so many exceptions needing to be thrown. is that due to the static methods, or just how it is? sorry, its late – TechnicalCustoms Jul 17 '13 at 07:13
  • how would you go about making this all non static? – TechnicalCustoms Jul 17 '13 at 07:20
  • Ive given you a template which can be applied to the other methods. See update. Re the exceptions, they dont arise due to the `static` methods but instead to the exceptions thrown by `Scanner` and `FileWriter` – Reimeus Jul 17 '13 at 07:36