【问题标题】:Does a method used in main method need its own class?主方法中使用的方法是否需要自己的类?
【发布时间】:2018-03-17 21:34:35
【问题描述】:

我正在编写一个检查密码条目的代码。主要方法检查次要方法并根据它的真假输出一行。我的问题是,当我编译它时,它会为第二种方法提供预期的类错误,但是如果我尝试使用与我的 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;
                    }
               }
           }
       }
    }  
}

【问题讨论】:

  • 不要两次声明类
  • 您在同一个文件中有两个公共类,名称相同。这是java文件中的两个错误
  • 刚开始学java的时候坚持一堂课。当您了解面向对象编程时,您可以开始使用类。
  • 那么,你认为你不需要两个类,因此你定义了两个类?问题不在于您有两个类,而在于您在同一个包中具有相同名称和同一级别的两个类。而且,最有可能的是,您在同一个文件中有两个公共(非静态)类。
  • 如果我没有第二个类,它会给我一个错误“预期的类、接口或枚举”。这就是为什么我想我会尝试添加它。

标签: java class methods


【解决方案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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-11
    • 2015-04-21
    • 2011-06-17
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多