简体   繁体   中英

Does a method used in main method need its own class?

I am writing a code that checks password entries. The main method checks a secondary method and outputs a line depending on whether it's true or false. My problem is when I compile it gives expected class error for the second method, but if I try to use the same class as my main it gives duplicate class error. I didn't think I needed a second class. Anyone care to help me out?

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

No need another class, but needed to static import isDigit and isLetter. I fixed your code:

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

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