簡體   English   中英

main 方法中使用的方法是否需要自己的類?

[英]Does a method used in main method need its own class?

我正在編寫一個檢查密碼條目的代碼。 主要方法檢查輔助方法並根據它是真還是假輸出一行。 我的問題是,當我編譯它時,第二種方法會出現預期的類錯誤,但是如果我嘗試使用與主類相同的類,則會出現重復的類錯誤。 我認為我不需要第二堂課。 有人願意幫我嗎?

import java.util.Scanner;

public class CheckPassword {
    public static void main(String[] args) {
        scanner input = new Scanner(System.in);
        System.out.println("Enter a password");
        password = input.nextLine();
        if (check(password)) {
           System.out.println("Valid Password");
        }
        else{
           System.out.println("Invalid Password");
        }
    }
}

public class CheckPassword {
    public static boolean check(String password) {
        boolean check = true;
        if(password.length() < 8) {
            check = false;
        }
        int num = 0;
        for(int x = 0; x < password.length(); x++) {
            if(isLetter(password.charAt(x)) || isDigit(password.charAt(x))){
                if(isDigit(password.charAt(x))){
                    num++;
                    if (num >=2){
                        check = true;    
                    } 
                    else{
                        check = false;
                    }
               }
           }
       }
    }  
}

不需要另一個類,但需要靜態導入 isDigit 和 isLetter。 我修復了你的代碼:

import java.util.Scanner;

import static java.lang.Character.isDigit;
import static java.lang.Character.isLetter;

public class CheckPassword {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a password");
        String password = input.nextLine();
        if (check(password)) {
            System.out.println("Valid Password");
        }
        else{
            System.out.println("Invalid Password");
        }
    }

    public static boolean check(String password) {
        boolean check = true;
        if(password.length() < 8) {
            check = false;
        }
        int num = 0;
        for(int x = 0; x < password.length(); x++) {
            if(isLetter(password.charAt(x)) || isDigit(password.charAt(x))){
                if(isDigit(password.charAt(x))){
                    num++;
                    if (num >=2){
                        check = true;
                    }
                    else{
                        check = false;
                    }
                }
            }
        }
        return check;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM