samedi 1 mai 2021

While-Loop Repeating when program reaches else-statement

So im trying to have this code repeat as long as the user does not type the correct information with the message "incorrect username or password" as you would see on any typical site. when i put the if statement in the loop and run the program, the 'if' statement works fine, however the 'else' statement is spammed. I tried putting the getUsername(); and getPassword(); under 'while(true)' and it seemed to fix that issue however the 'Enter Username: ' and 'Enter Password: ' is repeated twice. What am i doing wrong?

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

public class Banking_App {


    public static void main(String[] args) throws IOException {
        Path path = Paths.get("/Users/Coding/Desktop/myFile.txt").toAbsolutePath();
        List<String> titles = Files.lines(path).collect(Collectors.toList());
        String searchUsername = getUsername();
        String searchPassword = getPassword();
        displayResults(searchUsername, searchPassword, titles);
    }

    private static String getUsername() {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter Username: ");
        return scan.nextLine();
    }

    private static String getPassword() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter Password: ");
        return scanner.nextLine();
    }


    public static void displayResults(String searchUsername, String searchPassword, List<String> titles) {

        boolean userInFile = titles.stream().anyMatch(p -> p.equalsIgnoreCase(searchUsername));
        boolean passInFile = titles.stream().anyMatch(p -> p.equalsIgnoreCase(searchPassword));

        while (true) {

            if (userInFile && passInFile) {
                System.out.println("yes");

            } else {
                System.out.println("Username or Password is Incorrect!");

            }
        }

    }
}

Aucun commentaire:

Enregistrer un commentaire