Possible to write what would be output into a HTML file? - java

What I want to do is make it so that when the program runs it will run the ordinary way but if the user selects that they want the display to be in html then it will run what the ordinary program would do but rather than display it in the console it will write what was going to appear in the console into a html file that the user specifies. Is this possible? I have code to accept the user input and have them specify what format they want it in as well as open the browser but I'm not sure if this could work. The code I have already is below:
import java.awt.Desktop;
import java.io.*;
import java.util.*;
public class reader {
static int validresults = 0;
static int invalidresults = 0;
// Used to count the number of invalid and valid matches
public static boolean verifyFormat(String[] words) {
boolean valid = true;
if (words.length != 4) {
valid = false;
} else if (words[0].isEmpty() || words[0].matches("\\s+")) {
valid = false;
} else if ( words[1].isEmpty() || words[1].matches("\\s+")) {
valid = false;
}
return valid && isInteger(words[2]) && isInteger(words[3]);}
// Checks to see that the number of items in the file are equal to the four needed and the last 2 are integers
// Also checks to make sure that there are no results that are just whitespace
public static boolean isInteger(String input) {
try {
Integer.parseInt(input);
return true;
}
catch (Exception e) {
return false;
}
}
// Checks to make sure that the data is an integer
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
while (true) { // Runs until it is specified to break
Scanner scanner = new Scanner(System.in);
System.out.println("Enter filename");
String UserFile = sc.nextLine();
File file = new File(UserFile);
if (!file.exists()) {
continue;
}
if (UserFile != null && !UserFile.isEmpty()){
System.out.println("Do you want to generate plain (T)ext or (H)TML");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("H")) {
Desktop.getDesktop().browse(file.toURI());
} else if (input.equalsIgnoreCase("T")) {
processFile(UserFile);
} else {
System.out.println("Do you want to generate plain (T)ext or (H)TML");
}
}
}
}
// Checks how the user wants the file to be displayed
private static void processFile(String UserFile) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
int totgoals = 0;
Scanner s = new Scanner(new BufferedReader(
new FileReader(UserFile))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
// Splits the file at colons
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
totgoals = totgoals + hscore;
ascore = Integer.parseInt(words[3]); //read the away team score
totgoals = totgoals + ascore;
validresults = validresults + 1;
System.out.println(hteam + " " + "[" + hscore + "]" + " " + "|" + " " + ateam + " " + "[" + ascore + "]");
// Output the data from the file in the format requested
}
else{
invalidresults = invalidresults + 1;
}
}
System.out.println("Total number of goals scored was " + totgoals);
// Displays the total number of goals
System.out.println("Valid number of games is " + validresults);
System.out.println("Invalid number of games is " + invalidresults);
System.out.println("EOF");
}
}

//This is where we'll write the HTML to if the user's chooses so
private static final String OUTPUT_FILENAME = "output.html";
public static void main(String[] args) throws IOException
{
final Scanner scanner = new Scanner(System.in);
final String content = "Foobar";
final boolean toHtml;
String input;
//Get the user's input
do
{
System.out.print("Do you want messages "
+ "written to (P)lain text, or (H)TML? ");
input = scanner.nextLine();
} while (!(input.equalsIgnoreCase("p")
|| input.equalsIgnoreCase("h")));
toHtml = input.equalsIgnoreCase("h");
if (toHtml)
{
//Redirect the standard output stream to the HTML file
final FileOutputStream fileOut //False indicates we're not appending
= new FileOutputStream(OUTPUT_FILENAME, false);
final PrintStream outStream = new PrintStream(fileOut);
System.setOut(outStream);
}
System.out.println(toHtml
? String.format("<p>%s</p>", content) //Write HTML to file
: content); //We're not writing to an HTML file: plain text
}

Related

How can I read and compare numbers from a text file?

I've a text file and eclipse reads that without problem. The problem is that I don't know how I can hold the numbers from the FileReader. My program is supposed to read a text from a file that file has 2 names with their school points.
For example:
Jack 30 30 30
Martin 20 20 30
How can I find the one with the greater points?
public static void main(String[] args) {
String name = null;
try {
Scanner keybord = new Scanner(System.in);
System.out.println("enter in file name");
String filename = keybord.nextLine();
Scanner file = new Scanner(new File(filename));
while (file.hasNext())
{
name = file.nextLine();
System.out.println(name);
///?? what do i have to write to compare to persons points
}
} catch(IOException e) {
System.out.println("The file does not exist");
}
}
I know, it is not an efficient method, but I solved the problem with this code:
public static void main(String[] args)
{
String name = null;
int i = 0;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
try
{
Scanner keybord = new Scanner(System.in);
System.out.println("enter in file name");
String filename = keybord.nextLine();
Scanner file = new Scanner(new File(filename));
while (file.hasNext())
{
name = file.next();
System.out.println(name + " ");
while (file.hasNextInt())
{
i = i + file.nextInt();
}
if (i < min)
{
min = i;
}
System.out.println("min " + min);
if (i > max)
{
max = i;
}
System.out.println("max " + max);
i = 0;
}
} catch (IOException e)
{
System.out.println("File does not exist");
}
}
This probably isn't the most efficient way of solving it, but I gave it a shot. It isn't the full code for comparing multiple lines but you can just run this through a while loop until the file doesn't have next like you were already doing. Once you run this through you can store the value of each line to a variable and then compare the variables. ex: boolean xIsBigger x > y;. Then if it is true, x is the bigger number but if it is false then you know y is the bigger number. Hope this helps.
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Test {
public static void main(String[] args) throws ScriptException {
String line = "Jack 20 20 20";
line = line.replaceAll("[^0-9]", " ");
line = line.replaceFirst("^ *", "");
line = line.replaceAll(" ", "+");
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
System.out.println(engine.eval(line));
}
}
System output: 60.

InputMismatchError when trying to close console

I've written an extremely basic program with 3 options. While executing the "Quit" section of the code I get a InputMismatchError. I know that this is because the program is expecting an integer when me/User is giving it a String.
I was just wondering how I would go about setting something like this up.
I've also tried a string to char method but that's also gave me the same error.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
static Scanner S = new Scanner(System.in);
public static void main(String[] args) throws IOException
{
int DisJ, ISJ, User;
ISJ = 1;
DisJ = 2;
String input = "";
// change print outs to appropriate names::::
System.out.println("--Main Menu--");
System.out.println("Display Journeys:" + ISJ);
System.out.println("Suitable Journeys:" + DisJ);
System.out.println("Quit: " );
//User = S.next().charAt(0);
User = S.nextInt();
if (User == 1)
{
System.out.println("You have selected Display Journeys");
try
(BufferedReader ReadFile = new BufferedReader(new FileReader("E:\\input.txt")))
{
String line = null;
while ((line = ReadFile.readLine()) != null)
{
System.out.println(line);
}
}
}
else if (User ==2)
{
System.out.println("You have selected Suitable Journeys");
}
System.out.println("Specify Destination: ");
String destination = S.next();
System.out.println("Specify Max Time (HH:MM): ");
String specificTime = S.next();
// This assigns the first two integers to the string hours
String hours = specificTime.substring(0,2);
//This assigns the last two integers to the string minutes
String minutes = specificTime.substring(3,5);
//integer.parseInt converts the string into an integer
int hours1 = Integer.parseInt(hours);
//integer.parseInt converts the string into an integer
int minutes1 = Integer.parseInt(minutes);
int Time;
// Equation to convert the hh:mm into minutes
Time = (60 * hours1) + minutes1;
System.out.println("Specify number of changes");
int Changes = S.nextInt();
System.out.println( "Destination selected: " + input + "Minutes specified: " + Time + "," + "Number of changes: " + Changes);
int quit;
String Quit = S.next();
if (Quit.equals("Quit")) {
System.out.println("Goodbye!");
System.exit(0);
}
try {
quit = Integer.parseInt(Quit);
}
catch (Exception e)
{
System.out.println("Type Quit to leave");
}
}
}
Is your question that you are not able to make the argument in the if statement true?
Try setting it as a boolean instead of an int / string, and throughout your code just have it changing quit to true/false instead of a number/string.
EDIT: Oh i see. So you just want to make it so that the user can press a key and it will quit, like a "Please enter Y to exit the program"
Do you have a scanner set up?
Wrap yor coe with a try and catch errors to handle them
int quit;
try {
quit = Integer.parseInt(Quit);
} catch (Exception e) {
// handle error...
}
http://beginnersbook.com/2013/04/try-catch-in-java/
To simply check what the user entered just accept a string and check its value like so:
Scanner scanner = new Scanner(System.in);
System.out.print("Quit?");
String text = scanner.nextLine();
if (text.equals("Quit") or text.equals("q")) {
//...
}

Display error when empty array

I am creating a reverse polish notation calculator in java that accepts file input. One of the requirements is that certain statistics are generated from the calculations too.
below are two snippets of my code.
public static int invalidlines = 0;
public static int validlines = 0;
public static int stats1 = 0;
private static Scanner input;
public static ArrayList<String> validList = new ArrayList<String>();
public static ArrayList<Integer> stats = new ArrayList<Integer>(); {
if (stats.isEmpty());
display("n/a");
}
static int sum(ArrayList<Integer> stats)
{
int value = 0;
for(int i : stats)
{
value += i;
}
return value;
}
Thats the code for my array lists.
static void fileInput() throws IOException
{
input = new Scanner(System.in);
try
{
String currentLine = new String();
int answer = 0;
//Open the file
display("Enter File Name: ");
FileInputStream fstream = new FileInputStream(input.nextLine()); // make a input stream
BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); // pass input stream to a buffered reader for manipulation
String strLine; // create string vars
//loop to read the file line by line
while ((strLine = br.readLine()) != null) { // Whilst the buffered readers read line method is not null, read and validate it.
currentLine = strLine;
if(strLine.trim().isEmpty())
{
display("You have entered a blank line, the program will now exit");
System.exit(0);
}
if(isValidLine(currentLine))
{
validList.add(currentLine);
validlines++;
String[] filearray = new String[3];
filearray = currentLine.split(" ");
int val1 = Integer.parseInt(filearray[0]);
int val2 = Integer.parseInt(filearray[1]);
display("Your expression is: " + filearray[0] + " " + filearray[1] + " " + filearray[2]);
switch(filearray[2]) {
case("+"):
answer = val1 + val2;
stats.add(answer);
break;
case("-"):
answer = val1 - val2;
stats.add(answer);
break;
case("/"):
answer = val1 / val2;
stats.add(answer);
break;
case("*"):
answer = val1 * val2;
stats.add(answer);
break;
}
display("Your calculation is " + filearray[0] + " " + filearray[2] + " " + filearray[1] + " = " + answer);
}
}
}
catch (FileNotFoundException e)
{
display("Please Enter a valid file name");
}
display("Evaluations Complete");
display("=====================");
display("Highest Result: " + Collections.max(stats));
display("Lowest Result: " + Collections.min(stats));
display("Aggregate Result: " + sum(stats));
display("Average Result: " + sum(stats) / validlines);
display("Total Valid Lines: " + validlines);
display("Total Invalid Lines: " + invalidlines);
}
I require it so that if there are no valid calculations from the text file that the highest, lowest and average result displays show as 'n/a' instead they bring the java error in my console shown below.
Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(Unknown Source)
at java.util.Collections.max(Unknown Source)
at Assignment.fileInput(Assignment.java:156)
at Assignment.main(Assignment.java:177)
Replace
Collections.max(stats)
with
(!stats.isEmpty() ? Collections.max(stats) : "n/a")
(similarly for Collections.min)
You are also going to want to handle the case of validlines == 0 to avoid the division by zero error in / validlines.

I can't display a name from.txt file with a line number in the console

I have a Names.txt file I created with 4 names,bill,dave,mike, andjim
I can enter the file name and I can enter the name to search, for example dave above and then the console should return "dave appears on line 2 of Names.txt". Instead it returns "dave does not exist", which would be correct if it is not one of the four names. What mistake I am making in my while loop below?
public class names {
public static void main(String[] args) throws IOException {
String friendName; // Friend's name
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the filename.
System.out.print("Enter the filename: ");
String filename = keyboard.nextLine();
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Get the name of a friend.
System.out.print("Enter name to search: ");
friendName = keyboard.nextLine().toLowerCase();
int lineNumber = 1;
while (inputFile.hasNextLine()) {
if ("friendName".equals(inputFile.nextLine().trim())) {
// found
String line = inputFile.nextLine();
System.out.println("friendName" + " appears on line " + lineNumber + " of Names.txt");
lineNumber++;
//break;
} else {
// not found
System.out.println(friendName + " does not exist. ");
break;
}
}
// Close the file.
inputFile.close();
}
}
Remove the quotes from friendName and use the actual variable which you read in from the file:
int lineNumber = 1;
booelan found = false;
while (inputFile.hasNextLine()) {
String nextLine = inputFile.nextLine().trim();
if (friendName.equals(nextLine)) {
// found
found = true;
break; // name is found, no point in searching any further
}
lineNumber++; // always increment the line number
}
if (found) {
System.out.println(friendName + " appears on line " + lineNumber + " of Names.txt");
}
else {
System.out.println(friendName + " does not exist. ");
}
I also changed the way you use your Scanner. In your original code, you were calling Scanner.nextLine() twice in the case of a match with the friend name. This would cause the scanner to advance two lines which is not what you want.
package com.stackoverflow;
import java.io.*;
import java.util.*;
public class Names
{
public static void main(String[]args) throws IOException
{
String friendName; // Friend's name
// Create a Scanner object for keyboard input.
Scanner keyboard = new Scanner(System.in);
// Get the filename.
System.out.print("Enter the filename: ");
String filename = keyboard.nextLine();
// Open the file.
File file = new File(filename);
Scanner inputFile = new Scanner(file);
// Get the name of a friend.
System.out.print("Enter name to search: ");
friendName = keyboard.nextLine().toLowerCase();
int lineNumber = 0;
Boolean isFound = false;
while(inputFile.hasNextLine()){
lineNumber++;
String line = inputFile.nextLine();
if(line.trim().contains(friendName)){
System.out.println(friendName + " appears on line " + lineNumber + " of Names.txt");
}
}
if(!isFound){
System.out.println("given friend name "+friendName+" not exists in the file");
}
// Close the file.
inputFile.close();
} }

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