Hi guys need help for my mini project for schools. How do i compare the user input and match to my database in text file. this is like validity for username and password. I want to call the second line on my data base using account Number and pin.
this is my data base.
0,admin,adminLastName,123456,123456
1,user,userLastName,1234567,123456
0 = id
admin = name
adminLastName = Last Name
1234567 = accountNumber
123456 = pin
and this is my code.
package atm;
import java.io.File;
import java.util.Scanner;
public class Login {
static void verifyLogin(String name, String lastName, String userAccountNumber, String userPin, String filePath){
Scanner inputData = new Scanner(System.in);
boolean isFound = false;
String tempAccountNumber = "";
String tempPin = "";
System.out.print("\nAccount Number: ");
userAccountNumber = inputData.next();
System.out.print("\nPIN: ");
userPin = inputData.next();
try{
Scanner readTextFile = new Scanner(new File("myDataBase.txt")).useDelimiter("[,\n]");
while (readTextFile.hasNext() && !isFound){
tempAccountNumber = readTextFile.next();
tempPin = readTextFile.next();
if (tempAccountNumber.trim().equals(userAccountNumber.trim()) && tempPin.trim().equals(userPin.trim())){
isFound = true;
System.out.println("Welcome " + name+ " " +lastName);
System.out.println("\nLogin Successfully!");
}
else {
System.out.println("You have entered your PIN or ACCOUNT NUMBER incorrectly. Please check your PIN or ACCOUNT NUMBER and try again.\n If you don't have account yet please go to SignUp page!\n");
myMain mainMenu = new myMain();
mainMenu.inputKeyboard();
}
}
readTextFile.close();
}
catch (Exception e){
}
inputData.close();
}
}
If your textfile contains 1 user per line, and you split it with ',' then you can take each line like you do, then split that line into a string[] array and check if i.e. the name corresponds to 'admin'.
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Boolean loggedin = false;
String fileName = "accounts.txt";
String line = null;
System.out.println("What's your username?");
String tempUsername = input.nextLine();
System.out.println("What's your password?");
String tempPassword = input.nextLine();
try {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
String[] currAccount = line.split(",");
if (currAccount[1].equals(tempUsername) && currAccount[4].equals(tempPassword)) {
loggedin = true;
System.out.println("You have successfully logged in!");
}
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
ex.printStackTrace();
// Let's create it if file can't be found or doesn't exist, but let's ask first.
String answer;
System.out.print("File not found, do you want to create it? [Y/n]: ");
answer = input.nextLine();
if (answer.equalsIgnoreCase("y")) {
try {
FileWriter fileWriter = new FileWriter(fileName);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
System.out.println("File has been created!");
} catch (IOException exc) {
exc.printStackTrace();
}
} else {
System.out.println("File was not created!");
}
}
catch(IOException ex) {
ex.printStackTrace();
}
if (!loggedin) {
System.out.println("Your login combination did not exist.");
}
}
}
Please note, I haven't commented a lot, but it should still make sense.
After splitting remember that you start at array index 0, and not 1. So at index 1 the name on the account will be.
Goodluck.
Related
I am new to java and i'm trying to fetch the contents of the file and the type contents are
Nameofuser:DateOfBirth:Nationality
I want to ask users which name to find and the name should search the first field and again ask for dob and get results so on.
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.next());
input = new Scanner(file);
String newInput = input.nextLine();
while (input.hasNext()) {
String line = input.next();
String delims = "[:]";
String[] tokens = line.split(delims);
System.out.println(tokens);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
System.out.print("Error Occured ");
}
}
}
How do i go about displaying the search.
you need to get target name and dob, then try to find that record in the while loop
import java.io.File;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
String dob="",name="";
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.next());
//get person name and dob to search for:
System.out.print("Enter Person name : ");
name = input.next();
System.out.print("Enter Person DOB : ");
dob = input.next();
input = new Scanner(file);
String newInput = input.nextLine();
boolean found = false;
while (input.hasNext()) {
String line = input.next();
String delims = "[:]";
String[] tokens = line.split(delims);
//check if this line matches target record
if(tokens[0].equals(name) && tokens[1].equals(dob)){
System.out.println(String.format("Found Record, name: %s DOB: %s Nationality: %s",tokens[0],tokens[1],tokens[2]));
found=true;//mark as a record found
//no need to loop further
break;
}
}//while loop
if(!found){
System.out.println("No match records found!");
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
System.out.print("Error Occured ");
}
}
}
This is my current output:
********MENU********
1. UNIT
2. EXIT
*********************
Select your option from 1 or 2: 1
********MENU********
1. VIEW LIST
2. BACK TO MAIN
*********************
Select your option from 1 or 2: 1
This are the list of the units:
[1] Asero/California
[2] Captain America/Pennsylvania
What unit do you want to modify? 1
Asero/California
Asero/California
Unit Name: Iron Man
Unit Location: California
Return to menu? Select 1: 1
********MENU********
1. VIEW LIST
2. BACK TO MAIN
*********************
Select your option from 1 or 2: 1
This are the list of the units:
[1] Asero/California
[2] Captain America/Pennsylvania
What unit do you want to modify?
Process interrupted by user.
What I wanted is the "Asero/California" is modified and replaced into "Iron Man/California".
The original output is still:
[1] Asero/California
[2] Captain America/Pennsylvania
My desired output is when I modify the data it should now be:
[1] Iron Man/California
[2] Captain America/Pennsylvania
I have a textfile = "practice.txt", which is where the data is stored.
I also have another text file = "tempPractice.txt", which is used just for putting a temporary data.
public class Practice
{
List<String> lines = new ArrayList<String>();
public Practice()
{
try
{
String line = "";
System.out.println("********MENU********");
System.out.println("1. UNIT");
System.out.println("2. EXIT");
System.out.println("*********************");
System.out.print("Select your option from 1 or 2: ");
Scanner sc = new Scanner(System.in);
line = sc.next();
if(line.equals("1"))
{
unitMenu();
}
else if(line.equals("2"))
{
System.exit(0);
}
else
{
System.out.println("Incorrect code, please select from 1 or 2.");
new Practice();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void unitMenu()
{
try
{
String line = "";
System.out.println("********MENU********");
System.out.println("1. VIEW LIST");
System.out.println("2. BACK TO MAIN");
System.out.println("*********************");
System.out.print("Select your option from 1 or 2: ");
Scanner sc = new Scanner(System.in);
line = sc.next();
if(line.equals("1"))
{
updateData();
}
else if(line.equals("2"))
{
new Practice();
}
else
{
System.out.println("Incorrect code, please select from 1 or 2.");
unitMenu();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void updateData()
{
lines = new ArrayList<String>();
File f = new File("practice.txt");
BufferedReader bR, bR2;
BufferedWriter bW;
Scanner sc, sc2;
String str = "", scanLine, oldFile, newFile, tmpFile, uName, uLoc;
int numLine;
try
{
if(!f.exists())
{
System.out.println("File not found!");
}
else
{
bR = new BufferedReader(new FileReader("practice.txt"));
while((str = bR.readLine()) != null)
{
lines.add(str);
}
System.out.println();
System.out.println("This are the list of the units:");
for(int i=0,j=1;i<lines.size();i++,j++)
{
System.out.println( "[" + j + "] " + lines.get(i).toString());
}
System.out.print("What unit do you want to modify? ");
sc = new Scanner(System.in);
numLine = sc.nextInt();
int count = numLine;
--count;
for(int k=0;k<lines.size();k++)
{
if(count == k)
{
System.out.println(lines.get(k).toString());
//used for checking to know what data it returns
oldFile = lines.get(count).toString();
System.out.println(oldFile);
//method to replace a data --> not working/trial and error?
bW = new BufferedWriter(new FileWriter("tmpPractice.txt"));
System.out.print("Unit Name: ");
sc = new Scanner(System.in);
uName = sc.nextLine();
bW.write(uName);
bW.append('/');
System.out.print("Unit Location: ");
sc2 = new Scanner(System.in);
uLoc = sc2.nextLine();
bW.write(uLoc);
bW.newLine();
bW.close();
System.out.print("Return to menu? Select 1: ");
sc = new Scanner(System.in);
scanLine = sc.next();
if(scanLine.equals("1"))
{
unitMenu();
}
else
{
System.out.println("Error. Select only 1.");
updateData();
}
bR2 = new BufferedReader(new FileReader("tmpPractice.txt"));
while((newFile = bR2.readLine()) != null)
{
tmpFile = newFile;
oldFile = tmpFile;
bW = new BufferedWriter(new FileWriter("practice.txt", true));
bW.write(oldFile);
bW.close();
}
System.out.println(oldFile);
bR2.close();
}
bR.close();
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] a)
{
new Practice();
}
}
How would I do it? What should I do or what should I use in my code?
Is there any simplier way to do this? Any feedback/suggestion/remarks/help would be deeply much appreciated.
I'm still new to Java, and I'm doing a lot of practice for myself, I reached up to the point where I can append a data to a file with IO, however, I still dont know how to modify/replace a specific data in the file without deleting all of its contents.
Please help me, I really want to learn more.
Take a look at this and modify accordingly.
public static void replaceSelected(String address) {
try {
String x = "t";
System.out.println("started searching for line");
File inputFile1 = new File(old file where line is to be updated);
File tempFile = new File(address+"/myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(old file "));
String lineToRemove = "add line to remove as a variable or a text";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove) && x.contentEquals("t")) {
x ="f";
} else if(trimmedLine.equals(lineToRemove) && x.contentEquals("f")) {
System.out.println("removed desired header");
System.out.println("Line"+trimmedLine);
continue;
}
FileWriter fw = new FileWriter(new file address,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(currentLine);
System.out.println(currentLine);
bw.write("\n");
bw.close();
}
// writer.close();
reader.close();
boolean success3 = (new File (old file address)).delete();
if (success3) {
System.out.println(" Xtra File deleted");
}
} catch (Exception e){
}
I have worked out this code. In my code I have not used the temp file instead used the arraylist in to replace the old value with the new one.And After that I have write down the arraylist to the file. Please see below the changed code. I have only included the changed code here. This is working for me now.
for(int k=0;k<lines.size();k++)
{
if(count == k)
{
System.out.println(lines.get(k).toString());
//used for checking to know what data it returns
oldFile = lines.get(count).toString();
System.out.println(oldFile);
System.out.print("Unit Name: ");
sc = new Scanner(System.in);
uName = sc.nextLine();
System.out.print("Unit Location: ");
sc2 = new Scanner(System.in);
uLoc = sc2.nextLine();
String replaceString = uName+"/"+uLoc;
lines.set(k, replaceString);
FileOutputStream fop = null;
fop = new FileOutputStream(f);
for(String content:lines){
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.write("\n".getBytes());
}
fop.flush();
fop.close();
System.out.print("Return to menu? Select 1: ");
sc = new Scanner(System.in);
scanLine = sc.next();
if(scanLine.equals("1"))
{
unitMenu();
}
else
{
System.out.println("Error. Select only 1.");
updateData();
}
}
bR.close();
}
You used String replaceString = ...? Is the replaceString a value or a variable??
replaceString is a variable that contains the user enterd value to
replace the desired string value in the file
Another is this: lines.set(k, replaceString) -> can I also declare this as public void replaceString??? or is this the easier way?
here we are replacing the indexed(k) value in the arraylist(lines)
that contains the input file values, with the user enterd value.
And also, may I ask, what is the use of byte[], is it like charAt[] or more like Tokenizer?
now the replaced content is writing back to the file. For this we are
converting the string value to the byte array(byte []) and writing
using the FileOutputStream
Hi guys please is there anyone can help me out with this program?
write a program that asks the user to enter a postcode and returns the city for that
postcode. If the postcode in not in the list then it should return city not found.
The find city code must be in a separate method findCity()
The user should be able to continue entering postcodes until they enter 9999 to indicate they
are complete (9999 should not appear as “city not found”)
================================================
in the txt file:
Dandenong 3175
Frankstone 3199
Berwick 3816
Cranbourne 3977
Rosebud 3939
Thats what i've done so far.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test2 {
public static void main(String[] args) throws FileNotFoundException
{
try
{
File f = new File("Files\\cities.txt");
Scanner input = new Scanner(f);
String text;
while(input.hasNextLine())
{
text = input.nextLine();
process(text);
}
}
catch (FileNotFoundException ex)
{
System.out.println(ex.getMessage());
}
}
public static void process(String text)
{ String name = null;
int id;
Scanner code = new Scanner(System.in);
System.out.println("enter the postcode");
id = code.nextInt();
Scanner data = new Scanner(text);
if(code.equals(0))System.out.println(name);
name = data.next();
id = data.nextInt();
while(data.hasNextDouble())
{
}
System.out.println(name+ " ");
// System.out.println(id+ " ");
}
}
File f = new File("d:\\cities.txt");
Scanner input = new Scanner(f);
Map<Integer,String> cityCode = new HashMap<Integer,String>();
String text;
while(input.hasNextLine())
{
text = input.nextLine();
Scanner data = new Scanner(text);
String name = data.next();
int id2 = data.nextInt();
cityCode.put(id2, name);
}
System.out.println("enter the postcode");
Scanner code = new Scanner(System.in);
int id = code.nextInt();
if(cityCode.containsKey(id)) {
System.out.println(cityCode.get(id));
} else {
System.out.println("City Not found");
}
Here's a straight forward approach:
First, you want user to enter a passcode. If passcode is lesser than 9999, you want to search the text file to find a city with that passcode. This thing can be implemented as:
int passcode = 5; // Suppose passcode is 5. You may suppose any value lesser than 9999
Scanner input = new Scanner(System.in);
// Ask user to enter a passcode. If user enters 9999 the while loop is exited
while(passcode < 9999)
{
System.out.println("Enter passcode: ");
passcode = input.nextInt();
// donot search if passcode is greater than or equal to 9999
if(passcode < 9999)
searchCity(passcode);
}
searchCity() method works like:
public static String searchCity(int passcode) {
Scanner citiesScanner = new Scanner(new File("Files\\cities.txt"));
while(citiesScanner.hasNext()) {
String city = citiesScanner.next();
String pass = citiesScanner.next();
if(Integer.parseInt(pass) == passcode) {
return city;
}
}
return "City not found";
}
Just try to break your problem into sub problems. Do some paper work before starting typing code. Things become a lot simpler this way.
My issue is simple. And I am sure the solution is simple too. But my attempts have failed. I looked on every question on here that relates to this but it does not contain the solution I am looking for. I am using a ReadGameFile() method and a WriteToGameFile() method that is in my class VideoGameManager. I have a class that contains a method that outputs data in the following way :
this class is called VideoGameManager
which has a method that is called public void printSearchCriteria(String nameInput,String consoleInput);
name (tab space) platform
name " " platform
name " " platform
....etc.
then in a main class I have a new instance of VideoGameManaer
VideoGameManager vG = new VideoGameManager();
I then call the method that outputs the data with the following parameters
in which the user inputs
nameInput = keyboard.next();
consoleInput = keyboard.next();
vG.printSearchCriteria(String nameInput, String consoleInput);
This results in the data being printed in the way which was stated above.
I now need to find a way to take that output. and store it in new file in which the user will name.
System.out.println("Enter the file name to print out.");
String fileNamePrintToFile = keyboard.next();
//Some way that takes the data from the output of printSearchCriteria and stores it in a new file from the user input -fileNamePrintToFile.
VideoGameManager File
public class VideoGameManager {
Scanner keyboard = new Scanner(System.in);
//array list
private ArrayList<VideoGame> games;
//tab
private static final String delim = "\t";
//constructor
public VideoGameManager(){
games = new ArrayList<VideoGame>();
}
public void ReadGameFile(String fileName)
{
//This reconstructs a new instance of the VideGame array list.
//This is done to clear the array list
games = new ArrayList<VideoGame>();
try
{
//Create a new file Scanner
Scanner fileScanner = new Scanner(new File(fileName));
//Reads each line in the file one-by-one
while(fileScanner.hasNextLine())
{
//Stores the next line of code
String nextLine = fileScanner.nextLine();
//That line is then split using the delimiter (\t)
String[] splitStrings = nextLine.split(delim);
//If the newly created array is not 2 items in length then
//that line is not correctly formatted and should be ignored.
if(splitStrings.length != 2)
continue;
String gameName = splitStrings[0];//The first element is the game name
String console = splitStrings[1];//Next is the console
VideoGame newVideoGame = new VideoGame(gameName,console);
games.add(newVideoGame);//Added to the array list
}
fileScanner.close();
}
catch(Exception e)
{
System.out.println(" File does not exist ");
}
}
public void WriteToGameFile(String fileName, boolean append)
{
if(games == null)//if the file name is null then return
return;
try
{
//Creates the new instance of a print writer
PrintWriter fileWriter = new PrintWriter(new FileOutputStream(fileName,append));
for(VideoGame aVideoGame : games)
{
//Prints to the file
fileWriter.println(aVideoGame.getName()+delim+
aVideoGame.getConsole());
}
fileWriter.close();
}
catch(Exception e)
{
System.out.println("Error");
}
}
//returns an array list of video games based on a search criterion (name and console)
public void PrintSearchCriteria(String nameInput, String consoleInput)
{
for(VideoGame aVideoGame : games)
{
if(aVideoGame.getName().contains(nameInput) == true && aVideoGame.getConsole().contains(consoleInput) == true)
{
VideoGame newVideoGame = new VideoGame(aVideoGame.getName(),aVideoGame.getConsole());
System.out.println(newVideoGame.getName()+delim+newVideoGame.getConsole());
}
else if(aVideoGame.getName().contains(nameInput) == true && consoleInput.equalsIgnoreCase("*"))
{
VideoGame newVideoGame = new VideoGame(aVideoGame.getName(),aVideoGame.getConsole());
System.out.println(newVideoGame.getName()+delim+newVideoGame.getConsole());
}
else if(nameInput.equalsIgnoreCase("*") && aVideoGame.getConsole().contains(consoleInput) == true)
{
VideoGame newVideoGame = new VideoGame(aVideoGame.getName(),aVideoGame.getConsole());
System.out.println(newVideoGame.getName()+delim+newVideoGame.getConsole());
}
}
}
public void PrintCurrentResults(String fileName)
{
for(VideoGame aVideoGame : games)
{
System.out.println(aVideoGame.getName()+delim+
aVideoGame.getConsole());
}
}
}
Main Class
public class VideoGameFrontEnd {
public static void main(String[] args) {
//create and connect scanner object to keyboard
Scanner keyboard = new Scanner(System.in);
VideoGameManager vG = new VideoGameManager();
System.out.println("Welcome to the video game database!");
boolean quit = false;
try{
while(quit == false)
{
System.out.println("Enter 1 to load the video game database");
System.out.println("Enter 2 to search the database");
System.out.println("Enter 3 to print current results");
System.out.println("Enter 4 to print current results to file");
System.out.println("Enter 0 to quit");
int input = keyboard.nextInt();
switch(input){
case 0: input = 0;
System.out.println("Good Bye");
quit = true;
break;
case 1: input = 1;
System.out.println("Enter the file Name");
String fileName = keyboard.next();
vG.ReadGameFile(fileName);
break;
case 2: input = 2;
System.out.println("Enter the name of the game or '*' for all names");
String nameInput = keyboard.next();
System.out.println("Enter the name of the console or '*' for all consoles");
String consoleInput = keyboard.next();
vG.PrintSearchCriteria(nameInput,consoleInput);
break;
case 3: input = 3;
//print current results
break;
case 4: input = 4;
System.out.println("Enter the file name to print out.");
String fileNamePrintToFile = keyboard.next();
System.out.println("Append to file ? True or False");
String appendToFile = keyboard.next();
if(appendToFile.equalsIgnoreCase("true"))
{
vG.WriteToGameFile(fileNamePrintToFile, true);
}
else if(appendToFile.equalsIgnoreCase("false"))
{
vG.WriteToGameFile(fileNamePrintToFile, false);
}
else
{
System.out.println("Incorrect Response, auto shutdown");
System.exit(0);
}
default:
break;
}
}
}
catch(Exception e)
{
System.out.println("error");
System.exit(0);
}
}
}
I suggest logging framework like log4j,slf4j and so on. Or java standard logging utils.
If you want to know, how to save all the outputs send by System.out.print or println, here is one of the way, how you can achieve.
public static void main(String[] args) throws FileNotFoundException {
PrintStream ps = new PrintStream("mylog.log");
System.setOut(ps);
System.out.println(String.format("%s: %s", new Date(),"Application Started"));
System.out.println(String.format("%s: %s", new Date(),"Application Terminated"));
}
And the output will be some thing like this,
so im trying to read from a file the number of words and adding them up to give and int answer? And help and or suggestions would be nice, and i can only use a try/catch while for loop and if/else/if.... Thanks!
Here what i got so far:
package filereadingexercise2;
import java.io.*;
import java.util.Scanner;
/**
*
* #author theGreggstar
*/
public class FileReadingExercise2
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner keys = new Scanner(System.in);
String nameOfFile;
System.out.print("Please Enter The Name Of A File Or Directory, or Type Quit To Exit: ");
nameOfFile = keys.nextLine();
Scanner input = null;
try
{
input = new Scanner(new File(nameOfFile));
}
catch(FileNotFoundException s)
{
System.out.println("File does Not Exist Please Try Again: ");
}
while(input.hasNext())
{
String contents = input.next();
int length;
System.out.print(contents);
}
}
}
If I understand you correctly, you want something like this -
public static void main(String[] args) {
Scanner keys = new Scanner(System.in);
for (;;) { // Loop forever.
System.out.print("Please Enter The Name Of A File Or "
+ "Directory, or Type Quit To Exit: ");
String nameOfFile = keys.nextLine().trim(); // get the User input.
if (nameOfFile.equalsIgnoreCase("quit")) { // check for exit condition.
break;
}
File f = new File(nameOfFile); // Construct a File.
if (f.exists()) { // Does it exist?
if (f.isFile() && f.canRead()) { // is it a File and can I read it?
Scanner input = null;
try {
input = new Scanner(f); // The Scanner!
while (input.hasNextLine()) {
String contents = input.nextLine();
System.out.println(contents); // Print the lines.
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (input != null) {
input.close(); // Close the file scanner.
}
}
} else if (f.isDirectory()) { // No, it's a directory!
try {
System.out.println("File "
+ f.getCanonicalPath()
+ " is a directory");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}