我在java中创建一个简单的登录程序.这是我到目前为止的代码.
import java.util.Scanner; import java.io.*; import java.util.Arrays; public class PasswordProgram { public static String user; public String password; public static boolean part1Finish = false; public File file = new File("D:/file.txt"); public FileWriter UsernameWrite; public char[] user1; public void part1() { System.out.println("Please create an account: "); Scanner input = new Scanner(System. in ); System.out.println("Type in a username: "); String user = input.next(); System.out.println("Type in a Password: "); String password = input.next(); try { UsernameWrite = new FileWriter(file); UsernameWrite.write(user); UsernameWrite.write(password); System.out.println(user); UsernameWrite.close(); part1Finish = true; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void part2() { Scanner scan = new Scanner(System. in ); System.out.println("Please confirm your username: "); String usercheck = scan.next(); int PassAttempts = 5; int UserAttempts = 5; user1 = user.toCharArray(); user1 = password.toCharArray(); char[] usernamecheck = java.util.Arrays.copyOfRange(user1, 0, user.length()); System.out.println(usernamecheck); do { if (usercheck.equals(usernamecheck)) { while (PassAttempts > 0) { System.out.println("Please confirm your password: "); String passcheck = scan.next(); if (passcheck.equals(password)) { System.out.println("Thank You "); } else if (passcheck != password && PassAttempts > 0) { PassAttempts--; System.out.println("That is incorrect. Please Try Again"); passcheck = scan.nextLine(); } else { System.out.println("You have run out of Password Attempts"); break; } } } else if (usercheck != user && UserAttempts > 0) { UserAttempts--; System.out.println("That is an incorrect username. Please Try Again"); usercheck = scan.nextLine(); } else { System.out.println("You have run out of Username Attempts"); break; } } while (UserAttempts > 0); } public static void main(String[] args) { // TODO Auto-generated method stub PasswordProgram login = new PasswordProgram(); login.part1(); if (part1Finish == true) { login.part2(); } } }
我得到的问题是在方法中part2
.在这里,当我尝试将保存在变量下的用户名添加user
到字符数组中以将其用作范围时,我得到了错误NullPointerException
.
调查后我发现当运行is part2
的值时,我得到了错误.user
null
有没有办法可以通过这个FileReader
方法来做到这一点,或者我如何解决我得到的当前错误?谢谢.
因为静态字段user
是从未分配的part1
,你得到一个NullPointerException
当您尝试使用它part2
.
发布的代码中还存在其他问题:
为什么涉及文件尚不清楚
你用!=
用String
,比如在passcheck != password
您使用之间平等String
和char[]
在usercheck.equals(usernamecheck)
passcheck
被约束但从未使用过
局部变量(因为它们的名称)隐藏了一些字段
UsernameWrite
并且UserAttempts
有非常规名称(应该是 usernameWrite
和userAttempts