如何使代码循环回到Java的开头?

时间:2020-07-31 02:50:43

标签: java continue

我已经读到我需要在“ if”语句之后加上“ continue”,但是每当我用if语句尝试这样做时,它都指出“不能在循环外使用continue”。

2 个答案:

答案 0 :(得分:2)

在循环中设置它。例如:

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");
            }
        }
    }

查看更多:Java Break and Continute

答案 1 :(得分:1)

使用带有标签的外部无限循环,然后使用break loop_lable打破循环。检查直到输入有效。

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');
    }
}
相关问题