Include a condition with an input - java

Scenario One: User is asked for 5 digit Input Number and 3 digit Code and then those are replaced in file name and inside the file.
Scenario Two: User is asked for 5 digit Input Number AND then ASKED if they want to input/change the 3 digit code. If yes then they can input a 3 digit code.
Current Code:
package blah blah
import all stuffs...
public class NumbChanger{
public static void main(String[] args) {
try {
Scanner user = new Scanner(System.in);
String inputCode= "";
System.out.print("Enter a xml file directory: "); // Enter xml file directory.
String directory = user.nextLine();
System.out.print("Enter the 5 digit starting Number: ");
int inputNumber = user.nextInt();
System.out.print("Do you want to change the code?");
boolean yesChange = user.hasNext();
if (!yesChange){
} else {
System.out.print("Enter the 3 character Code: ");
inputCode = user.next();
}
user.close();
Path folder = Paths.get(directory);
FilenameFilter xmlFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(".xml")) {
return true;
} else {
return false;
}
}
};
//this is the list of files
File[] allFiles = folder.toFile().listFiles(xmlFilter);
if (allFiles == null) {
throw new IOException("No files found");
}
String fileName;
for(File aFile : allFiles) {
if (aFile.isFile()) {
fileName = aFile.getName();
String oldNumber = fileName.substring(
((fileName.lastIndexOf(".")) - 12), (fileName.lastIndexOf(".")) - 4);
String oldCode = fileName.substring(
((fileName.lastIndexOf(".")) - 3), (fileName.lastIndexOf(".")));
if (!yesChange){
} else {
inputCode = fileName.substring(
((fileName.lastIndexOf(".")) - 3), (fileName.lastIndexOf(".")));
}
String newNumber = String.valueOf(inputNumber++);
String newFileName = fileName.replaceAll(
oldNumber, newNumber);
if (!yesChange){
} else {
newFileName = newFileName.replaceAll(oldCode, inputCode);
}
//renaming the file
Path newFilePath = Files.move(aFile.toPath(),
aFile.toPath().resolveSibling(newFileName));
//replacing the entry # within the XML
String content = new String(Files.readAllBytes(newFilePath),
StandardCharsets.UTF_8);
content = content.replaceAll(oldNumber, newNumber);
content = content.replaceAll(oldCode, inputCode);
Files.write(newFilePath, content.getBytes(StandardCharsets.UTF_8));
}
}
System.out.print(allFiles.length + " xml files were changed.");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
System.out.println(" Good Job!");
System.exit(0);
}
}
}
Reflection on above code.
Currently I make it work if they enter values for both. Where am I going wrong?
Further enhancements:
Check the length of code.
I understand I can do a simple
if (inputCode.length == 3){
}
else {
System.out.print ln ("Error")
}
But Im not to privy with booleans and while loops and if the user enters a different value I want them to prompt again versus having to run the program again.
thanks in advance! :)

Im not sure I understand your question, but wouldn't
System.out.print("Enter the 5 digit starting Number: ");
int inputNumber = user.nextInt();
while(String.valueOf(inputNumber).length() != 5) {
System.out.println("Please enter a 5 digit number.");
inputNumber = user.nextInt();
}
do the job?
If the number is not 5 digits long the user is asked to enter a new one.
You cant use .length() on an Integer, so you will have to convert it to a String first. Hence the line
String.valueOf(inputNumber).length()

Related

How to write on a .txt file? [duplicate]

This question already has answers here:
Write to text file without overwriting in Java
(9 answers)
Closed 3 years ago.
I am new to java and I am working on a program that calculates a binary number to it's base 10 equivalent and saves each valid entry on a .txt file. Problem is that each entry is being overwritten that the only one that's saved is that last one entered. Can anyone point out what i'm doing wrong? and any tips on improving the syntax in general. Much appreciated.
import java.util.Scanner;
import java.io.*;
public class BinaryNum {
public static void main(String[] args) throws IOException //for file writing
{
Scanner keyboard = new Scanner(System.in);
String userEntry;// initial input by user for binary numbers
int ValidUserEntryNum;
int Decimal;
boolean decision = false; //bool to let user choose to continue
boolean bool; //variable to check if the valid string is a binary number
//loops for when the user names a choice
while(!decision)
{
//loops for when the user enters a binary number
do {
System.out.println("Please Enter a Binary Number: ");
userEntry = keyboard.nextLine();
//check to see if input is a string of numbers
userEntry = checkEntry (userEntry);
// convert string to int
ValidUserEntryNum = Integer.parseInt(userEntry);
//bool variable to see if the number is Binary
bool = CheckIsBinary (ValidUserEntryNum);
//check to see if the number is binary
if (!bool)
{
System.out.println("** Invalid.Input Must be a Binary number **");
}
} while(bool == false); //parameter for the loop (whether the number entered was binary)
//convert binary number to decimal number
Decimal = convert(ValidUserEntryNum);
//display on console
System.out.println("You Entered: " + ValidUserEntryNum);
System.out.println("It's base 10 equivilant is: " + Decimal);
System.out.println();
//creates the file name
File fileWR = new File("outDataFile.txt");
//creates the file object
fileWR.createNewFile();
BufferedWriter output = new BufferedWriter(new FileWriter(fileWR));
//to check if there is an existing file
if (fileWR.exists())
{
//writes in the file
output.write("You Entered: " + ValidUserEntryNum +"\r\n");
output.write("It's base 10 equivilant is " + Decimal +"\r\n");
output.close();
}
else //creates a new file if one doesnt already exist.
{
fileWR.createNewFile();
}
//option if the user wants to continue
System.out.println("Do you wish to continue?(yes or no):");
String st = keyboard.nextLine();
if (st.contentEquals("no"))
{
decision = true;
}
}
}
//to check if the user entered only a string of numbers (done)
public static String checkEntry (String userAnswer)
{
int UserLength = userAnswer.length();
int counter = 0;//to iterate through the string
// Create a Scanner object to read input.
Scanner keyboard = new Scanner(System.in);
while (UserLength == 0)
{
System.out.println("That is a blank");
System.out.println("Try again");
userAnswer = null;
userAnswer = keyboard.nextLine();
UserLength = userAnswer.length();
}
while (counter < UserLength)
{
if (!Character.isDigit(userAnswer.charAt(counter)))
{
System.out.println("That is not a binary number");
System.out.println("Try again");
userAnswer = null;
userAnswer = keyboard.nextLine();
UserLength = userAnswer.length();
counter = 0;
}
else
{
counter++;
}
while (UserLength == 0)
{
System.out.println("That is a blank, again");
System.out.println("Try again");
userAnswer = null;
userAnswer = keyboard.nextLine();
UserLength = userAnswer.length();
}
}
return userAnswer;
}
//method to check if the entered number is binary. (done)
public static boolean CheckIsBinary (int TrueBinary)
{
int temp;
while (TrueBinary > 0)
{
temp = (TrueBinary % 10);
if (temp != 1 && temp != 0)
{
return false;
}
TrueBinary = (TrueBinary/10);
}
return true;
}
//converts user binary to decimal
public static int convert(int ValidUserEntryNum)
{
//creating variables to convert binary to decimals
int temp = 0;
int Decimal = 0;
int power = 0;
//Convert the binary number to a decimal number
while (ValidUserEntryNum != 0)
{
temp = (ValidUserEntryNum % 10);
Decimal += temp * Math.pow(2, power++);
ValidUserEntryNum = (ValidUserEntryNum/10);
} return Decimal;
}
}
You are creating a new FileWriter and a new BufferedWriter each time inside the loop which is not necessary. You can move it outside the loop.
To make your existing code work, change
new FileWriter(fileWR)
to
new FileWriter(fileWR, true)
The second parameter passed is the append flag. From javadocs (emphasis mine)
boolean if true, then data will be written to the end of the file rather than the beginning.
It looks like you have fileWR.createNewFile(); both inside and outside the check.
//creates the file name
File fileWR = new File("outDataFile.txt");
//creates the file object
fileWR.createNewFile(); <--
BufferedWriter output = new BufferedWriter(new FileWriter(fileWR));
//to check if there is an existing file
if (fileWR.exists())
Change this line:
BufferedWriter output = new BufferedWriter(new FileWriter(fileWR));
To:
BufferedWriter output = new BufferedWriter(new FileWriter(fileWR), true);
Because the constructor you used for FileWriter defaults to overwriting.
http://tutorials.jenkov.com/java-io/filewriter.html#overwriting-vs-appending-the-file

validate an integer AND make it 5 digits

I'm taking my very first java class. I need to ask for a zip code. I know how to ask for new input if they don't enter 5 digits, but how do I also ask for new input if they enter a non-integer?
Here is what I have:
import java.util.Scanner;
public class AndrewDemographics {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
int zip; // 5 digit zip
System.out.print("Enter your 5 digit zip code: ");
zip = stdIn.nextInt();
while ((zip < 10000) || (zip > 99999)) {
// error message
System.out.println("Invalid Zip Code format.");
System.out.println("");
System.out.println("Enter your 5 digit zip code: ");
zip = stdIn.nextInt();
} //end if zip code is valid
}
}
To support zip codes starting with 0, you need to store the zip code in a String, and then it's easiest to validate it using a regex:
Scanner stdIn = new Scanner(System.in);
String zip;
do {
System.out.print("Enter your 5 digit zip code: ");
zip = stdIn.next();
} while (! zip.matches("[0-9]{5}"));
If you want to print error message, you can do it like this, which uses nextLine() so simply pressing enter will print error message too:
Scanner stdIn = new Scanner(System.in);
String zip;
for (;;) {
System.out.print("Enter your 5 digit zip code: ");
zip = stdIn.nextLine().trim();
if (zip.matches("[0-9]{5}"))
break;
System.out.println("Invalid Zip Code format.");
System.out.println();
}
As the comment suggests, you will need to take into account zip code starting with zero. I guess for that, you'll need to consider the input as a String:
check if the String is 5 characters long (to match the 5 digits)
String does not contain + sign as +1234 would work
check if the String is a valid integer
check if the Integer is positive as -1234 would be still valid
you now have something between 00000 and 99999
In practice
public static void main(String[] args){
Scanner stdIn = new Scanner(System.in);
String userInput;
int zipCode = -1;
// flag to stop spamming the user
boolean isValid = false;
while (!isValid) {
// ask the user
System.out.print("Enter your 5 digit zip code: ");
userInput = stdIn.next();
// it should be 5 digits so 5 charaters long:
if (userInput.length() == 5 && !userInput.contains("+")) {
try {
zipCode = Integer.parseInt(userInput);
if (zipCode > 0) {
isValid = true;
}
}
catch (NumberFormatException e) {
// do nothing
}
}
System.out.println("Zip code is invalid!");
}
System.out.println("You have selected the zip code: " + zipCode);
}
There is an issue with zip codes with leading zeros in previous. There needs to be a check if both is a number and is 5 characters in length. A zero leading zip would be 4 digits in length if read in as a number type.
Top of my head:
String zip = null;
do {
zip = stdIn.next();
try {
Integer.parseInt(zip); // this will throw exception if not a number
} catch (NumberFormatException e) {
continue; // this will start the next loop iteration if not a number
}
} while (zip.length() != 5); // this will start the next iteration if not 5 characters
I took the input as a String using nextLine() rather than an int because it accounts for zip codes starting with 0, and a zip code, although written numerically, isn't really a numerical value. I felt that the easiest way to structure the if/else statements determining if the zip code was valid was to use return statements that would break out of the checks at the return, so I wrote a method that would check for the validity of the zip code:
public static boolean checkValidZip(String zip) {
if (zip.length() != 5) { //invalid if not 5 chars long
return false;
}
for (int i=0; i<zip.length(); i++) { //invalid if not all digits
if (!Character.isDigit(zip.charAt(i))) {
return false;
}
}
return true; //valid if 5 digits
}
The main method then, looks like this:
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
String zip = ""; //5 digit zip
boolean valid = false;
boolean allNums = true;
while (!valid) {
System.out.print("Enter your 5 digit zip code: ");
zip = stdIn.nextLine();
valid = checkValidZip(zip);
if (!valid) {
System.out.println("Invalid Zip Code format.");
System.out.println("");
}
}
//end if zip code valid
}

jump out of recursive function in a loop but let the loop continue

I am trying to read from a text file that have names and phone numbers that can also have other text files in it (including it self)
myBook.txt:
7
name1 123-456-7890
name2 098-765-4321
name3 135-792-4680
name4 246-801-3579
PHONEBOOK-FILE myBook2.txt
name5 147-025-8369
name6 150-263-7495
myBook2.txt:
1
Name7 000-222-3332
The first line is the number of items in the file, then it has PHONEBOOK-FILE to signify another file.
I cannot use arrays, I cannot change myBook.txt, I cannot use try / catch, and I have to use recursion
This is the code I have:
import java.util.*;
import java.io.*;
public class Phonebook
{
private boolean DEBUG = true;
private Scanner scan;
private Scanner input;
private File file;
private File holder;
private String query;
private boolean bottomOut;
private int nameCount;
private String fileNameHold;
// entry point for class
public void run()throws IOException
{
input = new Scanner(System.in);
//Gets file name and checks if it exists valid file
while(true)
{
System.out.print("Name of phone book to read in: ");
fileNameHold = input.next();
file = new File(fileNameHold);
if(file.exists())
break;
else
System.out.println("That file does not exist!");
}
System.out.println("Phonebook successfully read in!");
//Main control loop
while(true)
{
bottomOut = false;
System.out.print("Please enter person to search for: ");
query = input.next();
if(query.equals("."))
break;
file = new File(fileNameHold);
System.out.println(doWork(query, file, 0));
}
System.out.print("Thank you for using this program!");
}
//Does the searching and recursive stuff
private String doWork(String query, File fileName, int level)throws IOException
{
scan = new Scanner(fileName);
//Grabs item count fom begining of file
//if(!bottomOut)
nameCount = Integer.parseInt(scan.nextLine());
String line = "";
//Runs through entries
for(int i=0; i<nameCount; i++)
{
line = scan.nextLine();
debug("file: " +file);
debug("line: " + line);
debug("nameCount: " + nameCount);
if(line.toLowerCase().contains(query.toLowerCase()))
{
return line;
}
//Recursion is used to searth through linked files
else if(line.contains("PHONEBOOK-FILE"))
{
//System.out.println("Sanity Check");
holder = new File(line.replace("PHONEBOOK-FILE ", ""));
if(level < 2 || (level > 0 && bottomOut))
return doWork(query, holder, ++level);
else if(level >= 2 && !bottomOut)
bottomOut = true;
else
return "not found (REC)";
}
}
return "not found";
}
private void debug(String stuff)
{
if(DEBUG)
System.out.println("[[--DEBUG--]] " + stuff);
}
}
I assume the issue is in doWork but I could be wrong. What it is doing is it recurses through the file until it hits a specified bottom where if it hasn't found the name it should break out of the recursion and continue passed the PHONEBOOK-FILE line.
Currently if you search for a name passed that line if returns not found. It doesn't seem to be coming out of the recursion.
As you can probably tell I an not great with this.
Thanks for any help.
For each line in your file, you are going to compute a value. Either not found, or a line of your phonebook. If you get a line, you can break out of the loop. Either way, after the loop you return the value: either the line you got or not found;
What is trickier is how you compute a line which references another phonebook, the answer is that you just call your method with that phonebook. That's the recursion part.
import java.util.*;
import java.io.*;
public class Phonebook
{
private Scanner input;
private File file;
private String query;
// entry point for class
public void run()throws IOException
{
input = new Scanner(System.in);
//Gets file name and checks if it exists valid file
while(true)
{
System.out.print("Name of phone book to read in: ");
fileNameHold = input.next();
file = new File(fileNameHold);
if(file.exists())
break;
else
System.out.println("That file does not exist!");
}
System.out.println("Phonebook successfully read in!");
//Main control loop
while(true)
{
bottomOut = false;
System.out.print("Please enter person to search for: ");
query = input.next();
if(query.equals("."))
break;
file = new File(fileNameHold);
System.out.println(doWork(query, file));
}
System.out.print("Thank you for using this program!");
}
//Does the searching and recursive stuff
private String doWork(String query, File fileName)throws IOException
{
Scanner scan = new Scanner(fileName);
int nameCount;
File recurFile;
nameCount = Integer.parseInt(scan.nextLine());
String line = "";
String value = "Not found";
//Runs through entries
for(int i=0; i<nameCount; i++)
{
line = scan.nextLine();
// if the line is a file, then the value of that line
// is the result to your function applied to that new file
if(line.contains("PHONEBOOK-FILE")) {
recurFile = new File(line.replace("PHONEBOOK-FILE ", ""));
line = doWork(query, holder, ++level);
}
// the file will either return Not found or
// a line corresponding to your query
if(line.toLowerCase().contains(query.toLowerCase()))
{
// Your line is correct. The function doesn't care where it comes from
value = line;
break;
}
}
return value;
}
}

Output prints first and part of second string. String sizes not set correctly

I've been writing this program that is supposed to build accounts for people inputted, saving their info all together in as one "superString" string, so it can be written and read from a txt file. I thought I had it all together correctly, but after testing various inputs and then reading back, it seems as though it isn't setting up the string lengths correctly.
If I only want account number 1, it will print out the account number 1.
If I put more accounts in and then try to only print out account 1, it'll print out account 1 and part of 2.
The output changes based on the size of the inputs, even though I put loops in there to have strict sizes.
I've been looking at the same problem for too long now and hopefully I'm just overlooking an easy fix. Can anyone help me out with this?
public class FirstTr {
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException, IOException
{
File loc = new File("C:\\Users\\Desktop\\Exc2.1.txt");
RandomAccessFile store = new RandomAccessFile(loc, "rw");
for(int i=0; i<20; i++)
{
String dummy = "12345678901234567890123456789012345678901234567890123456789012345678901";
store.writeUTF(dummy);
}
String userChoice = GettingUserInput();
System.out.println("The choice you entered: " +userChoice);
while(true){
if(userChoice.equals("new"))
{
String playerID = PlayerIDMethod();
System.out.println("The playerID you entered: " +playerID);
String playerName = PlayerNameMethod();
System.out.println("The playerName you entered: " +playerName);
String playerTeamName = PlayerTeamNameMethod();
System.out.println("The playerTeamName you entered: " +playerTeamName);
String playerSkillLevel = PlayerSkillLevelMethod();
System.out.println("The playerSkillLevel you entered: " +playerSkillLevel);
String todaysDate = TodaysDateMethod();
System.out.println("The date you entered: " +todaysDate);
String superString = "";
superString = playerID + playerName+ playerTeamName + playerSkillLevel + todaysDate;
//System.out.println("Combined string is: "+superString);
int playerIDDigit = Integer.parseInt(playerID);
store.seek((playerIDDigit-1)*73);
store.writeUTF(superString);
System.out.println("Length of string: " +superString.length());
userChoice = GettingUserInput();
}
if(userChoice.equals("old"))
{
System.out.println("Please enter player ID: ");
String desiredID = input.next();
int recLocation;
recLocation = Integer.parseInt(desiredID);
store.seek((recLocation-1)*73);
String printed = store.readUTF();
System.out.println("String: "+printed);
userChoice = GettingUserInput();
}
if(userChoice.equals("end"))
{
System.out.println("Program Closed.");
store.close();
System.exit(0);
}
}
}
public static String GettingUserInput()
{
System.out.println("Please type in a command: new, old, or end to exit");
String userChoice = input.next();
while(!userChoice.equals("New") && !userChoice.equals("new") && !userChoice.equals("Old") && !userChoice.equals("old") && !userChoice.equals("End") && !userChoice.equals("end"))
{
System.out.println("Looks like you didn't enter a correct choice.");
System.out.println("Please type in a command: new, old or end");
userChoice = input.next();
}
return userChoice;
}
public static String PlayerIDMethod()
{
String playerID = "";
Boolean loop = true;
while(loop)
{
try
{
System.out.println("Please input Player ID: ");
playerID = input.next();
int playerIDDigit = Integer.parseInt(playerID);
if (playerID.length()> 5){
playerID.substring(0,5);
}
if (playerID.length()< 5){
StringBuilder paddedName = new StringBuilder(playerID);
while(paddedName.length()<5){
paddedName.append(" ");
}
playerID = paddedName.toString();
}
while(Pattern.matches("[a-zA-Z]+", playerID)|| playerID.startsWith("-")|| playerIDDigit>20 || playerIDDigit<0)
{
System.out.println("Player ID cannot have characters, negatives, and must be within 1-20!");
System.out.println("Please input Player ID: ");
playerID = input.next();
}
loop = false;
}
catch(Exception e)
{
System.out.println("No way Hosay! Only Integers!");
}
}
return playerID;
}
public static String PlayerNameMethod ()
{
String playerName = "";
try{
System.out.println("Enter Player's Name: ");
playerName = input.next();
while(Pattern.matches("^\\d+", playerName))
{
System.out.println("No cool names include numbers! Try again.");
System.out.println("Enter Player's Name: ");
playerName = input.next();
}
if (playerName.length()> 26){
playerName.substring(0,26);
}
if (playerName.length()< 26){
StringBuilder paddedName = new StringBuilder(playerName);
while(paddedName.length()<26){
paddedName.append(" ");
}
playerName = paddedName.toString();
}
}
catch(Exception e){
System.out.println("ERROR PLEASE TRY AGAIN");
}
return playerName;
}
public static String PlayerTeamNameMethod ()
{
String playerTeamName = "";
try
{
System.out.println("Please enter Team name: ");
playerTeamName = input.next();
if (playerTeamName.length()> 26){
playerTeamName.substring(0,26);
System.out.print("The Player Name is" + playerTeamName);
}
if (playerTeamName.length()< 26){
StringBuilder paddedName = new StringBuilder(playerTeamName);
while(paddedName.length()<26){
paddedName.append(" ");
}
playerTeamName = paddedName.toString();
}
}
catch(Exception e)
{
System.out.println("ERROR PLEASE TRY AGAIN");
}
return playerTeamName;
}
public static String PlayerSkillLevelMethod ()
{
String playerSkillLevel = "";
Boolean loop = true;
while(loop)
{
try
{
System.out.println("Please enter player skill level between 0 and 99: ");
playerSkillLevel = input.next();
while(Pattern.matches("[a-zA-Z]+", playerSkillLevel))
{
System.out.println("Player skill level must be an integer!");
System.out.println("Please enter player skill level between 0 and 99: ");
playerSkillLevel = input.next();
}
loop = false;
}
catch(Exception e){
System.out.println("ERROR PLEASE TRY AGAIN ");
}
}
return playerSkillLevel;
}
public static String TodaysDateMethod (){
String todaysDate = "";
try{
System.out.println("Please enter todays date: ");
todaysDate = input.next();
if (todaysDate.length()> 9)
{
todaysDate = todaysDate.substring(1,9);
}
if (todaysDate.length()< 9)
{
StringBuilder paddedName = new StringBuilder(todaysDate);
while(paddedName.length()<26){
paddedName = paddedName.append(" ");
}
todaysDate = paddedName.toString();
}
}
catch(Exception e){
System.out.println("ERROR ");
}
return todaysDate;
}
//CONVERT TO STRING
public static String RecordtoFile (RandomAccessFile store){
return null;
}
//WRITE INTO FILE AT RECORD LOCATION INDICATED BY ID
public static String WriteToFile (RandomAccessFile store){
return null;
}
}
The way I see it resolved is creating a Person class with a constructor that would take an int id and a String name as parameters.
This class would have a private void recordToFile method and you would only record one person per line in the id space name format.
Aditionally, in the FirstTr class you would have a private Person retrieveFromFile(int id) that would verify every line in the file and would return the Person with the given id or null if no person was found. That method could get a String name too in the parameters but it's really your call.
The way using a String[ ] could be useful too but you should decide.
I found what was causing the problem. When parsing, three of the five values that make up the string had been set to length 26, so this already created a string of length 78. The desired size is 71, and when the other two values are added, it can reach to 80 or 81. Changing what the strings are parsed or added to changed the length of the super string and no longer run into any issues. Thanks for the help

Creating registration program in java?

I have a simple problem.
I'm trying to create a registration program using text files in java.
I wrote some code to do registration but at first my program should check if username is exists in text file or not.
If username is exists then the program asks user to enter new one.
But there is some error in my code i don't know, it is not checking if username exists or not.
here is my code:
System.out.println("Registration Page");
System.out.println("NOTE: your username is a unique one so it cannot be changed.");
System.out.printf("Username: ");
String user = input.next();
System.out.printf("Password: ");
String pass = input.next();
System.out.printf("Confirm Password: ");
String conf = input.next();
int length = pass.length();
int passInt = Integer.parseInt(pass);
int confInt = Integer.parseInt(conf);
if(length < 6)
System.out.println("Too short password, password must be 6 characters or more");
else
{
if(passInt == confInt)
{
Scanner z = null;
try{
z = new Scanner(new File("C:\\Users\\فاطمة\\Downloads\\accounts.txt"));
boolean checkname = false;
while(z.hasNext())
{
String a = z.next();
int b = z.nextInt();
if(a == null ? user == null : a.equals(user))
checkname = true;
}
if(checkname)
System.out.println("Username is already exists and used, please type another one");
else
{
Formatter x = null;
try{
FileWriter f = new FileWriter("C:\\Users\\فاطمة\\Downloads\\accounts.txt", true);
x = new Formatter(f);
x.format("%s %s%n",user.toUpperCase(),pass);
System.out.println("You registered succesfully");
x.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
catch(Exception e){}
}
else
System.out.println("Password and confirm password are not matching");
}
So instead of using Scanner to open and read the file, try using BufferedReader and Writer respectively for the reading and writing. In the code below we are reading through the file and if the name exists it will change your boolean to true and will then throw your error, otherwise it will complete the registration. It also will write the new information. Now one thing you may want to add is a way to loop back to the top if the information is invalid.
Also as a side not, for better cross OS functionality, you should use File.separator() which will do the same thing.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Registration Page");
System.out.println("NOTE: your username is a unique one so it cannot be changed.");
System.out.printf("Username: ");
String user = input.next();
System.out.printf("Password: ");
String pass = input.next();
System.out.printf("Confirm Password: ");
String conf = input.next();
int length = pass.length();
int passInt = Integer.parseInt(pass);
int confInt = Integer.parseInt(conf);
File file = new File("C:"+File.separator + "Users"+File.separator + "فاطمة"+File.separator + "Downloads"+File.separator + "accounts.txt");
if (length < 6) {
System.out.println("Too short password, password must be 6 characters or more");
} else {
if (passInt == confInt) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String current;
boolean checkname = false;
while ((current = br.readLine()) != null) {
if(current.equalsIgnoreCase(user)){
checkname = true;
}
}
if (checkname) {
System.out.println("Username is already exists and used, please type another one");
} else {
Formatter x = null;
try {
FileWriter f = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(f);
bw.write(user);
bw.close();
x = new Formatter(f);
x.format("%s %s%n", user.toUpperCase(), pass);
System.out.println("You registered succesfully");
x.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
catch (Exception e) {
}
} else {
System.out.println("Password and confirm password are not matching");
}
}
}
}
I have found what is the problem with my code:
the problem is that the username is found in the text file in this format:
JOHN 114477
SARAH 887755
The username is in uppercase letters and when i enter new username it's written in lower case letters so when searching for username in the text file the program compares name in lowercase letters with a name in uppercase letters that are not matching and so it allows me to enter the same username that exists before.
the correct solution is by editing this line and adding toUpperCase(); to it like this:
String user = input.next().toUpperCase();

Categories

Resources