简体   繁体   中英

How do I make my code loop back to the beginning in Java?

I've read that I would need to put "continue" after an "if" statement, but every I tried this with my if statement and it states that "continue cannot be used outside of a loop."

Set it in the loop. EX:

public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        while (true){
            System.out.print("Enter a password: The password must have at least eight characters, only letters and digits, and at least two digits. ");
            String s = input.nextLine();
            if (thepassword(s)) {
                System.out.println("Valid Password");
                break;
            } else {
                System.out.println("Invalid Password");
            }
        }
    }

See more: Java Break and Continute

Use an outer infinite loop with a lable, then break the loop using break loop_lable . Check until a valid input is made.

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a password: The password must have at least eight characters, only letters and digits, and at least two digits. ");
        loop:for(;;)
        {
        String s = input.nextLine();
        if (thepassword(s)) 
        {
          
        System.out.println("Valid Password");
        break loop;
        } 
        else 
        {
        System.out.println("Invalid Password");
        continue loop;
        }
        }
        input.close();
    }
    public static boolean thepassword(String password) {
        boolean thepassword = true;
    if (password.length() < 8) {
        thepassword = false;
    } else { 
        int totaldigits = 0;
        for (int n = 0; n < password.length(); n++) {
            if (thedigit(password.charAt(n)) || theletter(password.charAt(n))) {
                if (thedigit(password.charAt(n))) {
            totaldigits++;
            }
            } else { 
            thepassword = false;
            break;
            }
        }
        if (totaldigits < 2) { 
            thepassword = false;
        }
    }
    return thepassword;
}
public static boolean theletter(char c) {
    return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'));
}
public static boolean thedigit(char c) {
    return (c >= '0' && c <= '9');
    }
}

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