Выход из цикла while после того, как метод выполняет итерацию по файлу строк и находит соответствующий входной ответ - PullRequest
0 голосов
/ 10 июня 2018

Я создаю страницу входа для назначения класса и испытываю трудности с выходом из цикла while после того, как метод получает имя пользователя и пароль, а затем ищет в многострочном текстовом файле совпадение.Он может найти совпадение, но возвращается в область ввода в методе main и снова запрашивает имя пользователя.Надеюсь, что это имеет смысл.

Любая помощь будет принята с благодарностью.Как вы можете сказать, я новичок в Java, так как этот код повсюду и, вероятно, куча ошибок.Я не спал всю ночь, пытаясь понять это, но безуспешно.Спасибо!

package course.registration;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class Welcome {

public static void main(String[] args) throws FileNotFoundException {
    Scanner input = new Scanner(System.in);
    System.out.println("Welcome to the Course Registration System" + "\n");
    System.out.print("Please type Login or Register: ");
    String choice = input.nextLine();

    while (choice.equalsIgnoreCase("Login")){
        System.out.print("Please enter email address to log in: ");
        String email = input.nextLine();
        System.out.print("Please enter password: ");
        String password = input.nextLine();

        //goes to method to search and match inputs
        VerifyLogin verify = new VerifyLogin();
        verify.VerifyInfo(email, password);
        }

    if (choice.equalsIgnoreCase("Register")) {
        System.out.println("Going to registration Page...");
        }
    input.close();
    }
}

Вот метод, который ищет текстовый файл и пытается найти соответствие для входных данных.Я чувствую, что проблема в том, когда метод завершается и возвращается к циклу while в основном методе.Я не могу найти способ выхода из цикла while.Вот как выглядят строки в файле "Students_logins.txt":

jthomas@gmail.com,1234
kwatson@time.com,3333
legal@prog.com,d567
lavern@shirley.com,34
kwatson@gmail.com,12200

package course.registration;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class VerifyLogin {
    private String tempUsername;
    private String tempPassword;

    public void VerifyInfo(String email, String password) throws FileNotFoundException {
        boolean login = false;
        File file = new File("student_logins.txt");
        Scanner info = new Scanner(file);
        info.useDelimiter("[,\n]");

        while (info.hasNextLine()) {
            tempUsername = info.next();
            tempPassword = info.next();

            if (tempUsername.trim().equals(email.trim()) && (tempPassword.trim().equals(password.trim()))) {
                System.out.println("Email Address or Password Works!!");
                break;
            }
        }

        if (!login) {
            System.out.println("Email Address or Password is Invalid.");
        }
        info.close();
    }

}

Ответы [ 2 ]

0 голосов
/ 11 июня 2018

Просто переместите условие в цикл while, и если выбранное условие является окончательным, например, пользователь ввел действительные логин и пароль, затем используйте break для выхода из цикла.В противном случае цикл будет продолжен:

public class Welcome {

    public static void main(String... args) throws IOException {
        final LoginValidator loginValidator = new LoginValidator(Welcome.class.getResourceAsStream("student_logins.txt"));

        try (Scanner scan = new Scanner(System.in)) {
            System.out.println("Welcome to the Course Registration System");

            int choice = 0;

            while (choice >= 0) {
                System.out.println();
                System.out.println("1: LoginPlease");
                System.out.println("2: Register");
                System.out.print("Your choice: ");

                choice = scan.nextInt();
                scan.nextLine();

                if (choice == 1) {
                    System.out.print("Please enter email address to log in: ");
                    String email = scan.nextLine();
                    System.out.print("Please enter password: ");
                    String password = scan.nextLine();

                    if (loginValidator.isValid(email, password)) {
                        System.out.println("Email Address or Password Works!!");
                        break;
                    } else
                        System.out.println("Email Address or Password is Invalid.");
                } else if (choice == 2) {
                    System.out.println("Going to registration Page...");
                    break;
                }
            }
        }
    }
}

Для Проверка , лучше загрузить все логины из файла при запуске приложения, а затем использовать его, просто отметив Map:

final class LoginValidator {

    private final Map<String, String> map = new HashMap<>();

    public LoginValidator(InputStream in) {
        try (Scanner scan = new Scanner(in)) {
            scan.useDelimiter("[,\n]");

            while (scan.hasNextLine()) {
                map.put(scan.next(), scan.next());
                scan.nextLine();
            }
        }
    }

    public boolean isValid(String email, String password) {
        return map.containsKey(email) && map.get(email).equals(password);
    }
}
0 голосов
/ 10 июня 2018

В основном методе вы всегда остаетесь в цикле while, потому что вы никогда не получаете ввод снова.

До цикла while вы получаете:

String choice = input.nextLine();

Так что, когда вы предоставляете Вход в качестве входа, когда условие всегда true , поэтому вы остаетесь в этом цикле while.

Если вы хотите запросить у пользователя правильный ввод Вход/ Зарегистрируйтесь пока он не предоставит ее, вы можете попробовать использовать мою версию Welcome class:

public class Welcome {

public static void main(String[] args) throws FileNotFoundException {
    Scanner input = new Scanner(System.in);
    System.out.println("Welcome to the Course Registration System" + "\n");
    System.out.print("Please type Login or Register: ");
    String choice = input.nextLine();

    while (!choice.equalsIgnoreCase("Login") && !choice.equalsIgnoreCase("Register")) {
        choice = input.nextLine();
    }

    if(choice.equalsIgnoreCase("Login")){
        System.out.print("Please enter email address to log in: ");
        String email = input.nextLine();
        System.out.print("Please enter password: ");
        String password = input.nextLine();

        //goes to method to search and match inputs
        VerifyLogin verify = new VerifyLogin();
        verify.VerifyInfo(email, password);
    }

    if (choice.equalsIgnoreCase("Register")) {
        System.out.println("Going to registration Page...");
    }
    input.close();
}

}

...