我试图让用户输入一个四位数的密码,但是我不希望在他们输入时将其打印在屏幕上。我试过这样使用System.console().readPassword();
:
import java.util.Scanner;
import java.io.*;
import java.util.InputMismatchException;
public class VirtualATM{
private static String Details;
public static void main(String [] args){
try{
//Create variables & scanner to be used throughout the program.
Scanner sc = new Scanner(System.in);
boolean RegisterOrExist = false;
int cardNo = 0;
String DirToWriteFile = System.getProperty("user.dir") + "/VirtualATM.txt"; //Get path to write text file to.
DirToWriteFile.trim();
File file = new File(DirToWriteFile);
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
//Create writer to write to files.
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
System.out.println("Enter card number, or type register to register a new card.");
String register = sc.nextLine();
if(register.equalsIgnoreCase("register")){
RegisterOrExist = false;
RegisterNewCard();
} else {
RegisterOrExist = true;
cardNo = Integer.valueOf(register);
}
bw.write(Details);
//Close the writer.
bw.close();
} catch(IOException e) {
e.printStackTrace();
}
}
/*** Method for registering a new card **/
public static void RegisterNewCard(){
Scanner sc = new Scanner(System.in);
System.out.print("Name: ");
String name = sc.nextLine();
int MaxVal = Integer.MAX_VALUE;
int CardNo = new java.util.Random().nextInt(MaxVal) + 1;
int balance = new java.util.Random().nextInt(10000) + 1;
boolean OverDraft = false;
int OverDraftLimit = 0;
if(OverDraft = true){
OverDraftLimit = 250;
}
char [] PIN = {};
System.out.println("Create a FOUR digit pin: ");
try{
PIN = System.console().readPassword();
}catch(InputMismatchException e){
e.printStackTrace();
}
int P1 = (int) PIN[0];
int P2 = (int) PIN[1];
int P3 = (int) PIN[2];
int P4 = (int) PIN[3];
int [] PinNo = {P1, P2, P3, P4};
Details = "Name: " + name + " CardNo: " + CardNo + " Current Balance: " + balance + " overdraft? " + OverDraft + " OverDraftLimit: " + OverDraftLimit + " pin: " + PinNo;
}
}
然后,我尝试使用将针脚写入int [] pinNo = {P1, P2, P3, P4}
文本文件BufferedWriter
。当我将别针输入为时,我在文本文件中得到以下文本2566
:[I@42a57993
是否存在另一种方式来读取密码,而无需在用户键入时在屏幕上打印密码?
好吧,这条线
bw.write(Details);
details
在文件中写入
Details = "..otherdetails..."+"pin: " + PinNo;
显示您正在写入数组的哈希。所以只需替换"pin: " + PinNo
为数组的实际元素
您可以按照罗德所说的简单尝试一下
Details = "..otherdetails..."+"pin: " + java.util.Arrays.toString(PinNo)
提示-使用此密码可让您更安全地尝试密码
char[] PIN = System.console.readPassword();
Arrays.fill(password, ' ');
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句