2017-10-06 67 views
-6

我正在编写一个检查密码条目的代码。主要方法检查一个辅助方法并根据它是真还是假来输出一行。我的问题是,当我编译它给第二种方法预期的类错误,但如果我尝试使用相同的类作为我的主,它会给重复的类错误。我不认为我需要第二堂课。任何人都在帮助我?main方法中使用的方法是否需要自己的类?

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

不要声明类两倍 –

+0

你有一个名为同一个相同的文件两个公共类。这是一个java文件中的两个错误 – AxelH

+0

当你开始学习java时,坚持只有一个类。当你了解面向对象编程时,你可以开始玩类。 –

回答

-1

不需要另一个类,但需要静态导入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; 
    } 
}