2017-10-06 62 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; 
    } 
}