Trouble incorporating filereader into code - java

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 = "";
}

Related

how to use alternative of 'goto' in Java

How can I use any alternative to 'goto' in java?
I tried using break label. But since I am not breaking out of any loop, it is giving undefined label error.
import java.io.*;
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
label1:
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label1
}
int[] marksArray = new int[subNo];
for(int i=0; i<marksArray.length; i++)
{label2:
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label2
}
}
}
}
I was terminating the program on invalid input. But I need to execute the same lines on invalid input.
Rather than wanting to go to a specific point explicitly, wrap the bit you might want to repeat in a loop. If you don't want to execute the loop again, break.
For the first one:
while (true) {
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
break;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
// Nothing required to continue loop.
}
}
For the second one, wrap the loop body in loop:
for(int i=0; i<marksArray.length; i++)
{
while (true) {
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
break;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
}
Or, probably better, write a method wrapping this loop:
int getInt(BufferedReader br) throws IOException {
while (true) {
try
{
return Integer.parseInt(br.readLine().trim());
} catch(NumberFormatException e) {
System.out.println("Please enter a whole number.");
}
}
}
and then call this method:
System.out.println("Enter no. of subjects");
int subNo = getInt(br);
for(int i=0; i<marksArray.length; i++) {
System.out.println("Enter marks for subject " + (i+1));
marksArray[i] = getInt(br);
}
This code snippet will loop until a correct number is inserted, in this example (it solves your first goto problem)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean noNumberEntered; //Default on false
System.out.println("Enter no. of subjects");
//TODO: check if input is integer
while(!noNumberEntered){
try
{
subNo = Integer.parseInt(br.readLine().trim());
noNumberEntered = true;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
I have reformatted your code a little bit. My basic idea was: All of the goto statements can be written in equivalent loops. The first one has now been made with a while loop, which terminates ones there comes NO exception. As for the second label, that has been done with the same mechanism (so a while-loop), however, with a label that can be exited/terminated with a "break + nameOfYourLable" - statement.
import java.io.*;
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean goToLabel1 = true;
while (goToLabel1) {
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
goToLabel1 = false; //parsing succeeded, no need to jump to label1
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
//goto label1
}
}
int[] marksArray = new int[subNo];
for(int i=0; i<marksArray.length; i++)
{
label2: while (true) {
System.out.println("Enter marks for subject " + (i+1));
try
{
marksArray[i] = Integer.parseInt(br.readLine().trim());
break label2;
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
}
}
}
}
}
You can use a do while loop and a boolean instead, like that :
class $08_02_Total_Avg_Marks
{
public static void main(String args[]) throws IOException
{
//declare and initialize variables
int subNo = 0, totalMarks = 0;
float avg = 0.0F;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
boolean goodEntry = true;
do {
goodEntry = true;
System.out.println("Enter no. of subjects");
//check if input is integer
try
{
subNo = Integer.parseInt(br.readLine().trim());
}
catch(NumberFormatException e)
{
System.out.println("Please enter a whole number.");
goodEntry = false;
}
} while(!goodEntry);
}
You can do the same with your second goto.
There are many ways to do that (with while loop and a boolean, with breaks...), but loops are better then goto.

used of loop and encapsulation

I'm trying to get the program to do:
If the data entered is not accepted, request the information again
(note: it is fine to request ALL the information again, it is not necessary to only request specific info to be re-entered, but you can if you would like).
For the program everything seem to run fine except for when its the resolution, it ask for another input but if the input isn't correct it just accept. I need it to keep running until the correct input is enter.
import java.util.Scanner;
public class encap
{
private static String userID;
private static String password;
private static String resolution;
private static int Ramsize;
private static int freespace;
private static int videocard;
//Get and Set methods
public static String getuserID()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter userID : ");
userID = input.next();
return userID;
}
public static String getpassword()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter password : ");
password = input.next();
return password;
}
public static String getresolution()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter video resolution: ");
resolution = input.next();
if (resolution.equals("800x600") || resolution.equals("1024x768") || resolution.equals("1152x900"));
else
{
while(true)
{
System.out.println("Information invalid, Please fill again");
String getresolution = input.next();
if (resolution.equals("800x600") || resolution.equals("1024x768") || resolution.equals("1152x900"));
break;
}
}
return resolution;
}
public static int getRamsize()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter RAM size : ");
while(true)
{
if(input.hasNextInt())
{
Ramsize = input.nextInt();
break;
}
else
{
input.nextLine();
System.out.println("Invalid Input! Integer required");
System.out.print("Please enter RAM size : ");
}
}
return Ramsize;
}
public static int getfreespace()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter HD free space : ");
while(true)
{
if(input.hasNextInt())
{
freespace = input.nextInt();
break;
}
else
{
input.nextLine();
System.out.println("Invalid Input! Integer required");
System.out.print("Please enter HD free space : ");
}
}
return freespace;
}
public static int getvideocard()
{
Scanner input = new Scanner(System.in);
System.out.print("Please enter video card RAM size: ");
while(true)
{
if(input.hasNextInt())
{
videocard = input.nextInt();
break;
}
else
{
input.nextLine();
System.out.println("Invalid Input! Integer required");
System.out.print("Please enter video card RAM size: ");
}
}
return videocard;
}
public static void setuserID(String newuserID)
{
userID = newuserID;
}
public static void setpassword(String newpassword)
{
password = newpassword;
}
public static void setresolution(String newresolution)
{
resolution = newresolution;
}
public static void setRamsize (int newRamsize)
{
Ramsize = newRamsize;
}
public static void setfreespace (int newfreespace)
{
freespace = newfreespace;
}
public static void setvideocard (int newvideocard)
{
videocard = newvideocard;
}
public static void main(String[] args)
{
setuserID(getuserID());
setpassword(getpassword());
setresolution(getresolution());
setRamsize(getRamsize());
setfreespace(getfreespace());
setvideocard(getvideocard());
System.out.println("You have input the following information: " + "\nuserID: " + userID
+ "\npassword: " + password + "\nVideo resolution: " + resolution + "\nRam Size: "
+ Ramsize + "\nHD Free Space: " + freespace + "\nVideo Card Ram Size: " + videocard);
}
}
The problem is because you never do anything within your valid case scenario and you are using .next() for a single character instead of .nextLine() which grabs the entire input entered following an end of line character (return character)
This will ask until the input entered satisfies your if condition.
public static String getresolution()
{
String resolution;
boolean validAnswer = false;
Scanner input = new Scanner(System.in);
HashSet<String> validResolutions = new HashSet<>();
validResolutions.add("800x600");
validResolutions.add("1024x768");
validResolutions.add("1152x900");
//add more resolutions if you want without having to create a bigger if check
//validResolutions.add("1400x1120");
do {
System.out.print("Please enter video resolution: ");
resolution = input.nextLine().replaceAll(" ", "").replaceAll("\n", "");
validAnswer = validResolutions.contains(resolution) ? true : false;
if(!validAnswer)
System.out.println("Incorrect resolution please try again");
} while (!validAnswer);
return resolution;
}

How to write console output to a user named file

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,

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

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
}

How to write contents of an array list to a text file?

I have this basic enough Java program that asks the user to input songs to a music library array list. From there the user can shuffle their songs, delete a song, delete all etc. It's nearly finished, I just have one issue I can't resolve. It happens when I try export the array list to a text file. Instead of the content of the array list, my output would look like this, as opposed to the details the user submitted:
"1: MainClass.SongClass#c137bc9
MainClass.SongClass#c137bc9"
I'll post my code below, I'd really appreciate if someone could point me in the right direction!
My Final Project class which serves as my main class:
package MainClass;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FinalProject extends UserInput {
public String nextInt;
public static void main(String[] args) {
// SongLibrary iTunes; //Object stores the file cars.txt
// iTunes = new SongLibrary("MUSIC LIBRARY.txt");
// songData CLO = iTunes.readFileIntoList();
UserInput ui;
ui = new UserInput();
Scanner input = new Scanner(System.in);
int opt;
//Calls Methods Class so methods can be used below
Menu menuFunctions = new Menu();
//Calls FileReaderTest Class so file can be read
SongLibrary Reader = new SongLibrary();
//initial prompt only displayed when program is first ran
System.out.println("Welcome to your music library!");
do {
//Menu Prompts printed to the screen for the user to select from
System.out.println(" ");
System.out.println("Main Menu:");
System.out.println("........ \n");
System.out.println("Press 0 to Exit");
System.out.println("Press 1 to Add a Song");
System.out.println("Press 2 to View All Songs");
System.out.println("Press 3 to Remove a Song");
System.out.println("Press 4 to Shuffle Library");
System.out.println("Press 5 to Play a Random song");
System.out.println("Press 6 to Remove ALL Songs");
System.out.println("Press 7 to Save Library\n");
//Monitors the next Int the user types
opt = input.nextInt();
//"if" statements
if (opt == 0) {
//This corresponds to the condition of the while loop,
//The program will exit and print "Goodbye!" for the user.
System.out.println(" ");
System.out.println("Goodbye!");
} else if (opt == 1) {
//This method allows the user to add a song to the library.
//With the format being Title, Artist, Year.
System.out.println(" ");
menuFunctions.addEntry();
} else if (opt == 2) {
//This method prints the contents of the Array List to the screen
System.out.println("\n");
menuFunctions.viewAll();
} else if (opt == 3) {
//This method allows the user to remove an indiviual song from
//their music library
System.out.println("\n");
menuFunctions.removeOne();
} else if (opt == 4) {
//This method uses the Collections.shuffle method
//to re-arrange the track list
//song to simulate a music player's shuffle effect.
System.out.println("\n");
menuFunctions.shuffleSongs();
} else if (opt == 5) {
//This method will clear all contents of the library.
//It will ask the user to confirm their choice.
System.out.println("\n");
menuFunctions.randomSong();
} else if (opt == 6) {
//This method will clear all contents of the library.
//It will ask the user to confirm their choice.
System.out.println("\n");
menuFunctions.clearLibrary();
}
else if (opt == 7) {
try {
menuFunctions.saveLibrary();
} catch (FileNotFoundException x) {
System.out.println("File not found. " + x);
}
}
else {
//If the user selects an incorrect number, the console will
//tell the user to try again and the main menu will print again
System.out.println("\n");
System.out.println("Incorrect Entry, please try again");
}
} //do-while loop
while (opt > 0);
}
}
My SongClass class which holds the constructor and Get/Set methods
package MainClass;
public class SongClass {
private int songMinutes;
private int songSeconds;
private String songTitle;
private String songArtist;
private String songAlbum;
private int songYear;
public SongClass(int m, int ss, String t, String art, String al, int y){
songMinutes = m;
songSeconds = ss;
songTitle = t;
songArtist = art;
songAlbum = al;
songYear = y;
}
//GET METHODS
public int getMinutes() {
return songMinutes;
}
public int getSeconds() {
return songMinutes;
}
public String getTitle() { //
return songTitle;
}
public String getArtist() {
return songArtist;
}
public String getAlbum() {
return songAlbum;
}
public int getYear() {
return songYear;
}
//SET METHODS
public void setMinutes(int m){
songMinutes = m;
}
public void setDuration(int ss){
songSeconds = ss;
}
public void setTitle(String t){
songTitle = t;
}
public void setArtist(String art){
songArtist = art;
}
public void setAlbum(String al){
songAlbum = al;
}
public void printSong(){
System.out.println(songMinutes+":"+ songSeconds + " - " + songTitle + " - " + songArtist + " - " +songAlbum + " - "+ "("+songYear+")");
}
}
My menu class which holds most of the methods used in the program
package MainClass;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
public class Menu {
public void add(SongClass s) throws NumberFormatException {
try {
songLibrary.add(s);
} catch (NumberFormatException x) {
}
}
Scanner input = new Scanner(System.in);
UserInput ui = new UserInput();
public ArrayList<SongClass> songLibrary;
public Menu() {
songLibrary = new ArrayList<SongClass>();
}
public void removeOne() throws ArrayIndexOutOfBoundsException {
try {
System.out.println("Which song would you like to delete? (1 of " + songLibrary.size() + ")");
viewAll();
//calls the viewAll method to print current library to screen
int remove = input.nextInt();
//creates an int that corresponds to the nextInt typed.
if (remove > songLibrary.size()) {
System.out.println("Invalid ");
//if the user types a number higher than the highest index of the
//array list, they will be shown an error and return to the menu
}
else {
remove --;
SongClass s = songLibrary.get(remove);
System.out.println("Are you sure you would like to delete the following track from your music library? ");
s.printSong();
//confirms user wants to delete the selected track
System.out.print("1: Yes \n2: No" + "\n");
int confirmDelete = input.nextInt();
//Asks the user to input 1 or 2,
if (confirmDelete == 1) {
songLibrary.remove(remove);
//removes the index of the 4 array lists
System.out.println( "Removed.");
viewAll();
} else if (confirmDelete == 2) {
System.out.println("\n" + "Okay, the song won't be removed");
} else {
System.out.println("\n" + "Invalid option.");
}
}
}
catch (ArrayIndexOutOfBoundsException x) {
System.out.println("Please select an valid entry");
}
}
public void clearLibrary() {
System.out.println("Confirm?");
System.out.print("1: Yes \n2: No" + "\n");
int confirmDelete = input.nextInt();
//if the user types one, this triggers the clear method.
if (confirmDelete == 1) {
songLibrary.clear();
System.out.println("\n" + "Your music library has been cleared" + "/n");
}
}
public void shuffleSongs() {
//The shuffle function shifts the location of all the elements of an
//array list. This mimics the shuffle effect of a Music player
//The attributes of the song all get shuffled together because they
//are all linked by the same seed.
long seed = System.nanoTime();
Collections.shuffle(songLibrary, new Random(seed));
System.out.println("Your library is now shuffled" + "\n");
viewAll();
//Shuffles library, then outputs the new library list.
}
public void viewAll() {
if (songLibrary.isEmpty()) {
System.out.println("Your library is currently empty!");
} else {
System.out.println("Your Music Library" + "\n" + "Duration - Artist - Song - Album -(Year) " + "\n");
for (int i = 0; i < songLibrary.size(); i++) {
SongClass s = songLibrary.get(i);
s.printSong();
}
}
System.out.println("\n");
}
public void randomSong() {
int randomSong = (int) (Math.random() * (songLibrary.size() - 1));
//uses Math.random to generate a random double between 0.0 and 1.0
//it then multiplies it by the size of the array list - 1
//The end result is that a random index of the array list is selected
System.out.println("Now Playing:");
//the selected song randomSong is then outputted
//this changes each time the randomSong method is called
SongClass s = songLibrary.get(randomSong);
s.printSong();
}
public void saveLibrary() throws FileNotFoundException {
try (PrintWriter pw1 = new PrintWriter("MUSIC LIBRARY.txt")) {
File inFile = new File("MUSIC LIBRARY.txt");
Scanner in = new Scanner(inFile);
System.out.println("Your music library has been successfully exported!\n");
pw1.println("Your Music Library");
pw1.println(" ");
pw1.println("Duration - Artist - Song - Album (Year) " + "\n");
pw1.println(" ");
for (int i = 0; i < songLibrary.size(); i++) {
System.out.println("The loop ran this many times");
System.out.println(i);
int counter = i + 1;
pw1.println(counter + ": " + songLibrary.get(i));
}
System.out.println("Loop is over, PrintWriter should close.");
pw1.close();
}
}
public void addEntry() throws NumberFormatException {
try {
int minutes = ui.getInt("How many minutes does this song last?");
int seconds = ui.getInt("How many seconds does this song last?");
String title = ui.getString("What is the title of the track?");
String artist = ui.getString("Who performs the track?");
String album = ui.getString("What album is the track from?");
int year = ui.getInt("What year was the track released?");
System.out.println("Please enter a number:");
System.out.println("\n");
SongClass s = new SongClass(minutes, seconds, title, artist, album, year);
songLibrary.add(s);
System.out.println("Thank you!" + " " + title + " " + "was added to your library:");
} catch (NumberFormatException x) {
System.out.println(" ");
System.out.println("Year/Duration can use numbers only, please try again.");
System.out.println(" ");
}
}
}
And my user input class
package MainClass;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class UserInput{
private Scanner keyboard;
public UserInput() {
this.keyboard = new Scanner(System.in);
}
public String getString(String prompt) {
String line;
System.out.print(prompt + ": ");
line = this.keyboard.nextLine();
return line;
}
public int getInt(String prompt) {
String line;
int num;
System.out.print(prompt + ": ");
line = this.keyboard.nextLine();
num = Integer.parseInt(line);
return num;
}
public Date getDate(String prompt) {
String line;
SimpleDateFormat formatter;
Date date;
System.out.print(prompt + " (dd/MM/yyyy): ");
line = this.keyboard.nextLine();
formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
date = formatter.parse(line);
}
catch (ParseException ex) {
date = null;
}
return date;
}
public boolean getBoolean(String prompt) {
String line;
System.out.print(prompt + "? (Y|N)");
line = this.keyboard.nextLine();
return line.equalsIgnoreCase("Y");
}
}
"1: MainClass.SongClass#c137bc9 MainClass.SongClass#c137bc9"
This is what the default implementation of toString outputs.
You need to override toString in your SongClass:
#Override
public String toString(){
return String.format("%d:%d - %s - %s - %s - (%d)",
songMinutes,songSeconds, songTitle, songArtist , songAlbum, songYear);
}
An alternative (which may be better if you don't want to override toString, because that method is used elsewhere) is to loop over all elements of your list and explicitly format the output by calling appropriate getters (or another method similar to your printSong method).

Categories