How can I read numeric passwords in Java? - java

I am trying to get the user to enter a four digit pin but I don't want it to be printed out on the screen as they type it. I have tried using System.console().readPassword(); like so:
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;
}
}
I then try to write the pin int [] pinNo = {P1, P2, P3, P4} to a text file using the BufferedWriter. I get the following this text in the text file when I input the pin as 2566:
[I#42a57993
Is there another way to read a password without it printing on the screen as the user types?

well this line
bw.write(Details);
is writing the details in the file where
Details = "..otherdetails..."+"pin: " + PinNo;
shows that you are writing the hash of the array. So simply replace "pin: " + PinNo with
the actual elements of the array
You can simply follow what Rod said or try this
Details = "..otherdetails..."+"pin: " + java.util.Arrays.toString(PinNo)
Tip - using this makes you password more secure
try like this
char[] PIN = System.console.readPassword();
Arrays.fill(password, ' ');

problem:
pin: " + PinNo;
You are actually printing the memory location of the array object not the array elements itself
solution:
you can get each index of the PinNo array and append each of them to the string
"pin: " + PinNo[0] + PinNo[1] + PinNo[2] + PinNo[3]

If you are trying to run your code on Eclipse IDE console then it'll not work. It is bug System.console() (Java 6.0) returns null when running inside Eclipse.
You need to run from command prompt or teminal, etc.
For more on this see these post :-
Hide input on command line - stackoverflow
Masking password input from the console - stackoverflow

Related

how do I get data from a text file and save it into a string?

How do I get data from a text file and save it into a string?
For example, my text file has the numbers 1, 4, 5, 6, 8, and 10.4. These numbers can be on the same line or on separate lines. I want to concatenate them into a string, like so: 1 4 5 6 8 10.4
import java.io.File;
import java.io.FileNotFoundException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;
public class f {
public static void main(String args[]) {
int count = 0;
double totalcount = 0;
double average = 0;
Scanner read = new Scanner(System.in);
Scanner file;
String input = "";
String test = "";
double[] array1 = new double[100];
while (true) {
System.out.println("Enter name of file or enter quit to exit");
input = read.next();
if (input.equalsIgnoreCase("quit")) {
break;
}
try {
file = new Scanner(new File(input));
if (!file.hasNextLine()) {
System.out.println(input + " file is empty");
}
while (file.hasNext()) {
totalcount = totalcount + file.nextDouble();
count++;
}
while (file.hasNext()) {
test = test + (" ") + file.next();
}
System.out.println("bla" + test);
average = totalcount / count;
DecimalFormat df = new DecimalFormat("#.###");
df.setRoundingMode(RoundingMode.CEILING);
System.out.println("\nCount: " + count);
System.out.println("Total: " + df.format(totalcount));
System.out.println("Average: " + df.format(average));
System.out.println();
} catch (FileNotFoundException e) {
System.out.println(input + " doesn't exist");
}
}
}
}
My code does not work correctly.
Your code is working fine, the problem is, you trying to access content of your file two times.after first while loop , the hasnext() method will return false.because you already accessed all the element in first while loop.
so it will not execute -
while (file.hasNext()) {
test = test + (" ") + file.next();
}
Other than that your code is fine.
if you want store it in string also then do small modification in your first while loop as below-
while (file.hasNext()) {
Double d=file.nextDouble();
test = test + (" ")+d;
totalcount = totalcount + d;
count++;
}
I think this will give you what you want.
Hello i think below code will be useful for you ,as per your question i have txt file with data , first i am getting the location of file & then i am trying to get the content , at last i am printing it to the console
File f = new File("D:\\temp.txt");
String content11 = FileUtils.readFileToString(f);
System.out.println(content11);

Getting values from a text file then having them placed into a list with no duplicates?

What I have is a program that will read a text file that has data from a file that is in the format
`FootballTeamName1 : FootballTeamName2 : FootballTeam1Score : FootballTeam2Score
Currently it reads in the file and will split it at each colon what I want to know is how would I make it so that each time it comes across a name then it will add that name to the list if it doesn't already exist or if it does then it will not create a duplicate value rather it will add the values to the values that already exist for that teams name.
I currently have a program that can get the values for when you search for a team but what I want to do is make it so that it is possible when the user does not specify a team then it will make it so that it will return the results for all of the teams. Here is what I have currently which asks for the location of the file and asks the user for specifying a file which works but I'm not sure how to do what I want.
import java.awt.Desktop;
import java.io.*;
import java.util.*;
public class reader {
//used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
//checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
//also checks to make sure that there are no results that are just whitespace
public static boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
//checks to make sure that the data is an integer
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
while(true){ //Runs until it is specified to break
Scanner scanner = new Scanner(System.in);
System.out.println("Enter filename");
String UserFile = sc.nextLine();
File file = new File(UserFile);
if(!file.exists()) {
continue;
}
if(UserFile != null && !UserFile.isEmpty()){
System.out.println("Do you want to generate plain (T)ext or (H)TML");
String input = scanner.nextLine();
if ( input.equalsIgnoreCase("H") ) {
processFile(UserFile) ; }
else if ( input.equalsIgnoreCase("T")){
processFile(UserFile);
}
else{
System.out.println("Do you want to generate plain (T)ext or (H)TML");
}
}
}
}
//checks how the user wants the file to be displayed
private static void processFile(String UserFile) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
int gamesplayed = 0;
int gs = 0;
int gc = 0;
int w = 0;
int d = 0;
int l = 0;
String newLine = System.getProperty("line.separator");//This will retrieve line separator dependent on OS.
Scanner s = new Scanner(new BufferedReader(
new FileReader(UserFile))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the name of the team you want the results for");
String input = scanner.nextLine();
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
//splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
if ( input.equalsIgnoreCase(hteam)){
gamesplayed = gamesplayed + 1;
gs = gs + hscore;
gc = gc + ascore;
if (hscore > ascore)
w = w + 1;
else if (ascore > hscore)
l = l + 1;
else
d = d + 1;
}
else if (input.equalsIgnoreCase(ateam)){
gamesplayed = gamesplayed + 1;
gs = gs + ascore;
gc = gc + hscore;
if (hscore < ascore)
w = w + 1;
else if (ascore < hscore)
l = l + 1;
else
d = d + 1;
}
}
}
System.out.println(input + newLine + "--------------------------" + newLine + "Games played: " + gamesplayed + newLine + "Games Won: " + w + newLine + "Games Drawn: " + d + newLine + "Games Lost: " + l + newLine + "Goals For: " + gs + newLine + "Goals Against: " + gc);
}
}
If you want no duplicate elements in your collection use a Set. A Set is a collection that contains no duplicate elements (doc here).
Sounds like you want a Map from Team to Score, where if the team already exists, then get the value from the map, and and the score to that.
You can add the entries into a Set (or if you want them sorted - SortedSet). Since Set only holds unique values - you'll always have only one "copy" of each value.
For reference, the following code uses 5 values, but the set will have only 3 (unique) values:
String str = "A : B : C : B : A";
String[] vals = str.split(":");
SortedSet<String> myVals = new TreeSet<String>();
for(String val : vals)
{
myVals.add(val.trim());
}
System.out.println("Set size: " + myVals.size());

How would I change this code to make it so that it asks me the location of the file that I want to load?

So my code currently has the user specify the name of the file that they want to load within the code itself but how would I make it so that when the program is run then the user will enter the location of the file that they want to load?
import java.io.*;
import java.util.*;
public class reader {
static int validresults = 0;
static int invalidresults = 0;
//used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
//checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
//also checks to make sure that there are no results that are just whitespace
public static boolean isInteger( String input ) {
try {
Integer.parseInt( input );
return true;
}
catch( Exception e ) {
return false;
}
}
//checks to make sure that the data is an integer
public static void main(String[] args) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader("fbscores.txt"))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
//splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
validresults = validresults + 1;
System.out.println(hteam + " " + "[" + hscore + "]" + " " + ateam + " " + "[" + ascore + "]");
//output the data from the file in the format requested
}
else{
invalidresults = invalidresults + 1;
}
}
System.out.println("Total number of goals scored was " + totgoals);
//displays the the total number of goals
System.out.println("Valid number of games is " + validresults);
System.out.println("Invalid number of games is " + invalidresults);
System.out.println("EOF");
}
}
One approach would be to use a main loop asking for a file name and quitting program execution when no input is given.
Therefore I'd refactor most code of your main method into another function e.g. processFile(String fileName).
Then your main only deals with user input
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
while(true){ //keep running till we break
System.out.println("Enter filename or return blank line to quit");
String fileName = sc.nextLine();
if(fileName != null && !fileName.isEmpty()){
processFile(fileName)
}else{
break; //no user input => exit
}
}
System.out.println("bye");
}
private static processFile(String fileName){
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(fileName))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
… //rest of your original code
}

using Bufferdwriter why am I receiving main class not found or can't load?

I create a program that accepts user input. Based on the sales amount I am requesting the data go to either a low sales txt file or a high sales txt file. When I run the program I receive error Error: Could not find or load main class HighandLowSales. How can it not find or load the main class?
My previous post regarding the if else statement in case you would like to see: How to specify which file to write to?
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
public class HighandLowSales
{
public static void main(String[] args)
{
Scanner input1 = new Scanner(System.in);
Path highPerformer =
Paths.get("C:\\Users\\C\\Desktop\\IS103 "
+ "Programming Logic\\Week7\\HighSales.txt");
Path lowPerformer =
Paths.get("C:\\Users\\C\\Desktop\\IS103 Programming Logic\\"
+ "Week7\\LowSales.txt");
String delimiter = ",";
String s;
int id;
String firstName;
String lastName;
double currentSales;
final int QUIT = 999;
try
{
Scanner input = new Scanner(System.in);
OutputStream output = new
BufferedOutputStream(Files.newOutputStream(highPerformer, CREATE));
OutputStream output1 = new
BufferedOutputStream(Files.newOutputStream(lowPerformer, CREATE));
BufferedWriter writer = new
BufferedWriter(new OutputStreamWriter(output));
BufferedWriter writer1 = new
BufferedWriter(new OutputStreamWriter(output1));
System.out.print("Enter employee ID number >> ");
id = input.nextInt();
while(id != QUIT)
{
System.out.print("Enter first name for employee #" +
id + " >> ");
input.nextLine();
firstName = input.nextLine();
System.out.print("Enter last name for employee # " +
id + " >> ");
input.nextLine();
lastName = input.nextLine();
System.out.print("Enter current month sales in whole dollar "
+ "for employee #" + id + " >> ");
input.nextLine();
currentSales = input.nextDouble();
s = id + delimiter + firstName + delimiter + lastName + delimiter
+ currentSales;
if (currentSales>1000)
{
writer.write(s);
}
else
{
writer1.write(s);
}
writer.newLine();
writer1.newLine();
System.out.print("Enter next ID number or " + QUIT
+ "to quit");
id = input.nextInt();
}
writer.close();
writer1.close();
}
catch(Exception e)
{
System.out.println("Message: " + e);
}
}
}
The file HighandLowSales.java must be exactly in the same case, not for instance HighAndLowSales.java. Either that or you are not executing the application with the correct class path: java -cp . HighandLowSales. But as it seems you just clicked the jar, I guess it is the case-sensitive nature of java file names (in jars, under Linux, MacOSX).
(Also it is really customary to no longer use the default (=no) package.)

Having trouble scanning an Int

I'm new to Java, and struggling with something I've never had trouble with in the past. For whatever reason, I can't scan an int (or a double) in my code, but I can scan a string just fine. I'm posting the snippet where my scanner isn't functioning, please let me know if I should include the rest of the program.
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.IOException;
public class DZP3
{
public static void main(String[] args) throws IOException
{
announce();
Scanner scan = new Scanner(System.in);
//Prompt user for input file
System.out.println("Greetings! Please enter the filename of the plaintext olympics data file you'd like to open.");
String txtFilename = scan.nextLine();
//Opens olympics data txt file specified, exits if it does not exist
File medalsInput = new File (txtFilename);
if(!medalsInput.exists())
{
System.out.println("File not found. Reload and try again.");
System.exit(1);
}
//Prompt user for output file
System.out.println("Thanks. Please enter the filename of the plaintext data output file.");
String outputTxt = scan.nextLine();
//Create output file specified
File medalsOutput = new File (outputTxt);
//Prompt user for medal cutoff X value
System.out.println("Thanks. Please enter the minimum number of medals a nation must have earned to be counted for calculation 2 listed above. \nEnter the value, as an integer:");
int medalsCutoff = 0;
medalsCutoff = scan.nextInt();
fileProcessing(medalsInput, medalsOutput, medalsCutoff);
}
}
Near the bottom, medalsCutoff is not accepting any scanned value whatsoever. I've tried putting it in a method other than main, I've tried rearranging it, creating a separate scanner just for it, and a few other things. The debugger shows that, no matter what, I'm stuck on that line of code. What have I done wrong? I'm at a loss.
EDIT: Here's the fileProcessing method, and what comes after. The announce method is just system.out.println.
public static void fileProcessing(File medalsIn, File medalsOut, int medalsMin) throws IOException
{
//Initialize necessary variables and strings
int maxTotMedals = -1;
int natCountMedalsMin = 0;
int natHiScore = -1;
String natName;
String answerOne = "DEFAULT";
int answerTwo = 0;
String answerFour = "DEFAULT";
//Create Printwriter
PrintWriter pw = new PrintWriter(medalsOut);
//Create scanner to read from file, loop until end of file
Scanner filescan = new Scanner(medalsIn);
while (filescan.hasNext())
{
//Initializes medal counting variables at zero, resetting the values with each line
int gCount = 0;
int sCount = 0;
int bCount = 0;
natName = filescan.next();
int lineMedals = 0;
while (lineMedals < 4); //Runs 4 times to cover all four years
{
gCount += filescan.nextInt();
sCount += filescan.nextInt();
bCount += filescan.nextInt();
lineMedals++;
}
int totalMedals = gCount + sCount + bCount;
//Sees if this line's medals have exceeded previous total medal record, if yes, sets country name as answer to question one
if (totalMedals > maxTotMedals)
{
answerOne = natName;
maxTotMedals = totalMedals;
}
if (totalMedals >= medalsMin)
{
natCountMedalsMin++; //For answer two
}
//Score calculation
int natScore = gCount*3;
natScore += sCount*2;
natScore += bCount;
//Compares score to highest score, for answer four
if (natScore > natHiScore)
{
answerFour = natName;
natHiScore = natScore;
}
//Write nation name and score to file
pw.println(natName + " " + natScore);
}
//Define answer two after all countries have been counted
answerTwo = natCountMedalsMin;
//Close output file
pw.close();
//Send results to answer method
answerPrint(answerOne, answerTwo, answerFour, medalsMin, natHiScore);
}
//This method outputs the answers to the user.
public static void answerPrint(String answerEin, int answerZwei, String answerVier, int medalsMini, int HiScore)
{
System.out.println("File read successfully.");
System.out.println("The nation that earned the greatest number of medals is " + answerEin + ".");
System.out.println(answerZwei + " countries earned more than " + medalsMini + " medals.");
System.out.println("The nation with the highest score is " + answerVier + " with a score of " + HiScore + ".");
System.out.println("Thank you for using this program. Until next time!");
}
EDIT 2: This has been solved, I had a stray semicolon in my fileProcessing method that caused an infinite loop. Thank you all for your help.
while (lineMedals < 4);
Above line has a semicolon at the end. It is an infinite loop.
after file creation ,you use this below method
File medalsOutput = new File (outputTxt);
medalsOutput.createNewFile()
in ur code file not got created and exiting via syste.exit(1)

Categories

Resources