How to write console output to a user named file - java

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,

Related

Call the exact value from text File

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.

Reading x lines of text at a time from a text file in Java

I'm trying to write a method for a school project for displaying a list of contacts from a text file. Only four contacts are supposed to display at a time and then re-entering "d" should display the next 4 until all have been displayed. Does anyone have any advice in how I could achieve this? Right now I just have it so it reads all of the lines of text.
import java.util.Scanner; import java.io.*;
public class Contacts
{
public static void main(String [] args) throws IOException
{
File aFile = new File("contacts.txt");
if (!aFile.exists())
System.out.println("Cannot find file");
else
{
Scanner in = new Scanner(aFile);
String input;
Scanner keyboard = new Scanner(System.in);
input = keyboard.nextLine();
if (input.contains("d"))
{
String aLineFromFile;
while(in.hasNext())
{
aLineFromFile = in.nextLine();
System.out.println(aLineFromFile);
}
in.close();
}
}
}
}
As MadProgrammer said, use a counter to track groups of 4.
else {
Scanner in = new Scanner(aFile);
Scanner keyboard = new Scanner(System.in);
String input = keyboard.nextLine();
while(input.contains("d")) {
int limit = 4;
String aLineFromFile;
while(in.hasNext() && limit > 0) {
aLineFromFile = in.nextLine();
System.out.println(aLineFromFile);
limit--;
}
if(in.hasNext()) {
input = keyboard.nextLine();
}
else {
break;
}
}
}

Modify a specific content of a file with user defined value

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

Search and match in Txt file (Java)

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.

Trouble incorporating filereader into code

I have written this code and am almost done, however I am stuck wondering how to implement filereader into my code, to put data from the file into the existing list/array of numbers. I've looked up on websites how to put filereader in, but have been stumped over and over with syntax :( I'm also forced to stick with Java 1.4.2, so I can't use Scanner and that stuff.
Here is the incomplete code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
//Import libraries
public class phoneBook
{
static ArrayList ListNumbers = new ArrayList(); //Create array
public static void main(String[] args)
{
InputStreamReader inp = null;
BufferedReader input = null;//Create inputstreamreader and bufferedreader
int nOption = 0;
try
{
inp = new InputStreamReader(System.in);
input = new BufferedReader(inp);
while(true)
{
System.out.println("Welcome to PDA Phonebook");
System.out.println(" " + "\nWhat would you like to do?");
System.out.println("1. Enter Phone Numbers/ Add a Phone Number.");
System.out.println("2. Modify Phone Number.");
System.out.println("3. Delete Phone Number.");
System.out.println("4. Sort Phone Number.");
System.out.println("5. Show all Phone Numbers.");
System.out.println("6. Load Phone Numbers.");
System.out.println("7. Exit.");
System.out.println("\nChoose an option(1-7) >> ");
nOption = Integer.parseInt(input.readLine());
//Layout visual menu
switch(nOption)
{
case 1:
AddNumber(input);
break;
case 2:
ModifyNumber(input);
break;
case 3:
DeleteNumber(input);
break;
case 4:
SortNumber(input);
break;
case 5:
ShowAllNumbers();
break;
case 6:
LoadNumbers(input);
break;
case 7:
System.out.println("Exiting program. Press any key to continue....");
input.read();
System.exit(0);
break;
//Create cases for the input of the user
}
}
}
catch(Exception exp)
{
}
}
//create private static void for each option in the list
private static void AddNumber(BufferedReader input) throws IOException
{
NumberTemplate tmpObject = null;
tmpObject = new NumberTemplate();//create tmp object for new phone numbers
while(true)
{
System.out.println("Name belonging to the phone number >> ");
tmpObject.NumberName = input.readLine().toString();//Convert input of name to a string
System.out.println("Phone Number");
tmpObject.Number = input.readLine().toString(); //Convert input of phone number to a string
if(tmpObject != null)
ListNumbers.add(tmpObject);//Add the new phone number to the list of numbers
System.out.println("\n Do you want to add another phone number?(y/n) >>");
if(!input.readLine().toLowerCase().equals("y"))//Ask user if they want to add another number
break;//Return to list
}
}
private static void ModifyNumber(BufferedReader input) throws IOException
{
NumberTemplate tmpObject = null;
System.out.println("Name of the number to modify >> ");
String OldNumberName = input.readLine();//User inputs name of number they want to edit
int index = getNumberIndexByName(OldNumberName);
if(index == -1)//if the number does not exist
{
System.out.println(" Number belonging to " + OldNumberName+ " not found.");//Tell the user if they entered an nonexistant number name
}
else//if number does exist
{
tmpObject = (NumberTemplate)ListNumbers.get(index);
showNumber(tmpObject);
System.out.println("What you want to modify (Name|Number)? >>");
String strOption = input.readLine();//User chooses what they want to edit from the number
if("name".equals(strOption.toLowerCase()))
{
System.out.println("New Name belonging to the number >> ");
tmpObject.NumberName = input.readLine().toString();//User inputs the name they want to change the number to
}
else if("number".equals(strOption.toLowerCase()))
{
System.out.println("New number "+tmpObject.NumberName);
tmpObject.Number = input.readLine().toString();//User inputs the number they want to change
}
else
{
System.out.println("Unable to locate the property entered..");
}
ListNumbers.set(index, tmpObject);//Apply the changes to the list of numbers
}
}
private static int getNumberIndexByName(String Name)
{
int index = -1;
NumberTemplate tmp =null;
for(int i=0;i<ListNumbers.size();i++)
{
tmp = (NumberTemplate)ListNumbers.get(i);
if(tmp.NumberName.toLowerCase().equals(Name.toLowerCase()))
{
index = i;
break;
}
}
return index;//List numbers
}
private static void showNumber(NumberTemplate tnumber)
{
System.out.println(tnumber.NumberName+"\t\t"+tnumber.Number);
}
private static void DeleteNumber(BufferedReader input) throws IOException
{
System.out.println("Name of the number to delete >> ");
String OldNumberName = input.readLine();
int index = getNumberIndexByName(OldNumberName);
if(index == -1)//If number name doesn't exist
{
System.out.println(" Number belonging to " + OldNumberName+ " not found.");
}
else//if number name exists
{
ListNumbers.remove(index);//Remove the number from list of numbers
System.out.println(" Number belonging to " + OldNumberName+ "deleted successfully.");
}
}
private static void SortNumber(BufferedReader input) throws IOException
{
System.out.println("Enter the key to sort (Name|Number)? >>");
String strOption = input.readLine();//User inputs what they want to sort the numbers by
int nSize = ListNumbers.size();
String str1, str2;
if("name".equals(strOption.toLowerCase()))//Sort numbers by name
{
for(int i = 0;i<nSize;i++)
{
for(int j = (i+1);j<nSize;j++)
{
str1 = ((NumberTemplate)ListNumbers.get(i)).NumberName;
str2 = ((NumberTemplate)ListNumbers.get(j)).NumberName;
if(str1.compareToIgnoreCase(str2) > 0)
{
NumberTemplate tmp = (NumberTemplate) ListNumbers.get(i);
ListNumbers.set(i, (NumberTemplate) ListNumbers.get(j));
ListNumbers.set(j, tmp);
}
}
}
}
else if("number".equals(strOption.toLowerCase()))//Sort numbers by number
{
for(int i = 0;i<nSize;i++)
{
for(int j = (i+1);j<nSize;j++)
{
str1 = ((NumberTemplate)ListNumbers.get(i)).Number;
str2 = ((NumberTemplate)ListNumbers.get(j)).Number;
if(str1.compareToIgnoreCase(str2) > 0)
{
NumberTemplate tmp = (NumberTemplate) ListNumbers.get(i);
ListNumbers.set(i, (NumberTemplate) ListNumbers.get(j));
ListNumbers.set(j, tmp);
}
}
}
}
else
{
System.out.println("Unable to locate the property entered..");
}
ShowAllNumbers();
}
private static void ShowAllNumbers()
{
System.out.println("PDA Phone Book\n");//List all the numbers
System.out.println("Name\t\tNumber");
for(int i=0;i<ListNumbers.size();i++)
{
showNumber((NumberTemplate)ListNumbers.get(i));
}
}
private static void LoadNumbers(BufferedReader input) throws FileNotFoundException, IOException
{
{BufferedReader in = new BufferedReader(new FileReader("phoneBook.txt"));
while(true)
{
NumberTemplate tmpObject = null;
String line = in.readLine();
if (line == null)
break;
NumberTemplate nt = new NumberTemplate();
nt.NumberName = line;
line = in.readLine();
nt.Number = Integer.parseInt(line);
ListNumbers.add(nt);
}
}
}
class NumberTemplate
{
public String NumberName = "";
public String Number = "";
}
}
This is where I'm having the problem:
private static void LoadNumbers(BufferedReader input) throws FileNotFoundException, IOException
{
{BufferedReader in = new BufferedReader(new FileReader("phoneBook.txt"));
while(true)
{
NumberTemplate tmpObject = null;
String line = in.readLine();
if (line == null)
break;
NumberTemplate nt = new NumberTemplate();
nt.NumberName = line;
line = in.readLine();
nt.Number = Integer.parseInt(line);
ListNumbers.add(nt);
}
}
With these errors:
C:\Java\bin>javac phoneBook.java
phoneBook.java:81: error: non-static variable this cannot be referenced from a s
tatic context
tmpObject = new NumberTemplate();//create tmp object for new phone numbe
rs
^
phoneBook.java:240: error: non-static variable this cannot be referenced from a
static context
NumberTemplate nt = new NumberTemplate();
^
phoneBook.java:243: error: incompatible types
nt.Number = Integer.parseInt(line);
^
required: String
found: int
Note: phoneBook.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
3 errors
The file consists of 45 names and numbers, in the format:
name
number
name
number
etc....
You're passing input initialized with System.in to each method. You probably want to have something like
BufferedReader in = new BufferedReader(new FileReader("foo"));
and pass in to the methods. You need an additional variable as you want to use a standar input stream and a file input stream. You can also use a public field for that.
For more info take a look here or here.
while(true)
{
String line = in.readLine();
if (line == null)
break;
NumberTemplate nt = new NumberTemplate();
nt.NumberName = line;
line = in.readLine();
nt.Number = Integer.parseInt(line);
ListNumbers.add(nt);
}
probably with some try/catch.
This code repeats until the end of the file, reading the name, setting appropriate value in NumberTemplate instance, then parsing integer and doing the same. In the end it adds it your ArrayList.
Compiling code
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
//Import libraries
public class phoneBook
{
static ArrayList ListNumbers = new ArrayList(); //Create array
public static void main(String[] args)
{
InputStreamReader inp = null;
BufferedReader input = null;//Create inputstreamreader and bufferedreader
int nOption = 0;
try
{
inp = new InputStreamReader(System.in);
input = new BufferedReader(inp);
while(true)
{
System.out.println("Welcome to PDA Phonebook");
System.out.println(" " + "\nWhat would you like to do?");
System.out.println("1. Enter Phone Numbers/ Add a Phone Number.");
System.out.println("2. Modify Phone Number.");
System.out.println("3. Delete Phone Number.");
System.out.println("4. Sort Phone Number.");
System.out.println("5. Show all Phone Numbers.");
System.out.println("6. Load Phone Numbers.");
System.out.println("7. Exit.");
System.out.println("\nChoose an option(1-7) >> ");
nOption = Integer.parseInt(input.readLine());
//Layout visual menu
switch(nOption)
{
case 1:
AddNumber(input);
break;
case 2:
ModifyNumber(input);
break;
case 3:
DeleteNumber(input);
break;
case 4:
SortNumber(input);
break;
case 5:
ShowAllNumbers();
break;
case 6:
LoadNumbers(input);
break;
case 7:
System.out.println("Exiting program. Press any key to continue....");
input.read();
System.exit(0);
break;
//Create cases for the input of the user
}
}
}
catch(Exception exp)
{
}
}
//create private static void for each option in the list
private static void AddNumber(BufferedReader input) throws IOException
{
NumberTemplate tmpObject = null;
tmpObject = new NumberTemplate();//create tmp object for new phone numbers
while(true)
{
System.out.println("Name belonging to the phone number >> ");
tmpObject.NumberName = input.readLine().toString();//Convert input of name to a string
System.out.println("Phone Number");
tmpObject.Number = input.readLine().toString(); //Convert input of phone number to a string
if(tmpObject != null)
ListNumbers.add(tmpObject);//Add the new phone number to the list of numbers
System.out.println("\n Do you want to add another phone number?(y/n) >>");
if(!input.readLine().toLowerCase().equals("y"))//Ask user if they want to add another number
break;//Return to list
}
}
private static void ModifyNumber(BufferedReader input) throws IOException
{
NumberTemplate tmpObject = null;
System.out.println("Name of the number to modify >> ");
String OldNumberName = input.readLine();//User inputs name of number they want to edit
int index = getNumberIndexByName(OldNumberName);
if(index == -1)//if the number does not exist
{
System.out.println(" Number belonging to " + OldNumberName+ " not found.");//Tell the user if they entered an nonexistant number name
}
else//if number does exist
{
tmpObject = (NumberTemplate)ListNumbers.get(index);
showNumber(tmpObject);
System.out.println("What you want to modify (Name|Number)? >>");
String strOption = input.readLine();//User chooses what they want to edit from the number
if("name".equals(strOption.toLowerCase()))
{
System.out.println("New Name belonging to the number >> ");
tmpObject.NumberName = input.readLine().toString();//User inputs the name they want to change the number to
}
else if("number".equals(strOption.toLowerCase()))
{
System.out.println("New number "+tmpObject.NumberName);
tmpObject.Number = input.readLine().toString();//User inputs the number they want to change
}
else
{
System.out.println("Unable to locate the property entered..");
}
ListNumbers.set(index, tmpObject);//Apply the changes to the list of numbers
}
}
private static int getNumberIndexByName(String Name)
{
int index = -1;
NumberTemplate tmp =null;
for(int i=0;i<ListNumbers.size();i++)
{
tmp = (NumberTemplate)ListNumbers.get(i);
if(tmp.NumberName.toLowerCase().equals(Name.toLowerCase()))
{
index = i;
break;
}
}
return index;//List numbers
}
private static void showNumber(NumberTemplate tnumber)
{
System.out.println(tnumber.NumberName+"\t\t"+tnumber.Number);
}
private static void DeleteNumber(BufferedReader input) throws IOException
{
System.out.println("Name of the number to delete >> ");
String OldNumberName = input.readLine();
int index = getNumberIndexByName(OldNumberName);
if(index == -1)//If number name doesn't exist
{
System.out.println(" Number belonging to " + OldNumberName+ " not found.");
}
else//if number name exists
{
ListNumbers.remove(index);//Remove the number from list of numbers
System.out.println(" Number belonging to " + OldNumberName+ "deleted successfully.");
}
}
private static void SortNumber(BufferedReader input) throws IOException
{
System.out.println("Enter the key to sort (Name|Number)? >>");
String strOption = input.readLine();//User inputs what they want to sort the numbers by
int nSize = ListNumbers.size();
String str1, str2;
if("name".equals(strOption.toLowerCase()))//Sort numbers by name
{
for(int i = 0;i<nSize;i++)
{
for(int j = (i+1);j<nSize;j++)
{
str1 = ((NumberTemplate)ListNumbers.get(i)).NumberName;
str2 = ((NumberTemplate)ListNumbers.get(j)).NumberName;
if(str1.compareToIgnoreCase(str2) > 0)
{
NumberTemplate tmp = (NumberTemplate) ListNumbers.get(i);
ListNumbers.set(i, (NumberTemplate) ListNumbers.get(j));
ListNumbers.set(j, tmp);
}
}
}
}
else if("number".equals(strOption.toLowerCase()))//Sort numbers by number
{
for(int i = 0;i<nSize;i++)
{
for(int j = (i+1);j<nSize;j++)
{
str1 = ((NumberTemplate)ListNumbers.get(i)).Number;
str2 = ((NumberTemplate)ListNumbers.get(j)).Number;
if(str1.compareToIgnoreCase(str2) > 0)
{
NumberTemplate tmp = (NumberTemplate) ListNumbers.get(i);
ListNumbers.set(i, (NumberTemplate) ListNumbers.get(j));
ListNumbers.set(j, tmp);
}
}
}
}
else
{
System.out.println("Unable to locate the property entered..");
}
ShowAllNumbers();
}
private static void ShowAllNumbers()
{
System.out.println("PDA Phone Book\n");//List all the numbers
System.out.println("Name\t\tNumber");
for(int i=0;i<ListNumbers.size();i++)
{
showNumber((NumberTemplate)ListNumbers.get(i));
}
}
private static void LoadNumbers(BufferedReader input) throws FileNotFoundException, IOException
{
BufferedReader in = new BufferedReader(new FileReader("phoneBook.txt"));
while(true)
{
NumberTemplate tmpObject = null;
String line = in.readLine();
if (line == null)
break;
NumberTemplate nt = new NumberTemplate();
nt.NumberName = line;
line = in.readLine();
nt.Number = line;
ListNumbers.add(nt);
}
}
}
class NumberTemplate
{
public String NumberName = "";
public String Number = "";
}

Categories