[英]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.不需要另一个类,但需要静态导入 isDigit 和 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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.