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
Related
I'm using NetBeans 16 and I'm trying to add the ability to edit a record from a text file I have saved separated by commas.
Ive tried this code here and I don't seem to get any errors (except the one produced as a result of the try catch) but I have no idea why this doesn't seem to work when I try to overwrite a record which I have selected ive tried everything I can think of I'm pretty new to coding so forgive me if there's some obvious error but I have no idea why this doesn't work my text file has 5 entries in a row if that helps but yeah any help is greatly appreciated
public class EditRecords {
private static Scanner x;
public static void main(String[]args)
{
String filepath = "VehicleInforUpd.txt";
System.out.println("Enter Registration of Entry You Wish To Edit");
Scanner scanner = new Scanner(System.in);
String editTerm = scanner.nextLine();
System.out.println("Enter new Registration: ");
String newReg = scanner.nextLine();
System.out.println("Enter new Make: ");
String newMake = scanner.nextLine();
System.out.println("Enter New Model: ");
String newModel = scanner.nextLine();
System.out.println("Enter New Year: ");
String newYear = scanner.nextLine();
System.out.println("Enter New Comments: ");
String newComment = scanner.nextLine();
editRecord(filepath,editTerm,newReg,newMake,newModel,newYear,newComment);
}
public static void editRecord(String filepath,String editTerm,String newReg,String newMake,String newModel, String newYear, String newComment)
{
String tempFile = "temp.txt";
File oldFile = new File(filepath);
File newFile = new File(tempFile);
String reg = ""; String make = ""; String model = ""; String year = ""; String comment = "";
try
{
FileWriter fw = new FileWriter(tempFile,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
while(x.hasNext())
{
reg = x.next();
make = x.next();
model = x.next();
year = x.next();
comment = x.next();
if(reg.equals(editTerm))
{
pw.println(newReg+","+newMake+","+newModel+","+ newYear+","+newComment);
}
else
{
pw.println(reg+","+make+","+model+","+year+","+comment);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
JOptionPane.showMessageDialog(null, "Changes Succesfully Saved");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
The Print stack trace results but im not sure what would cause the NullPointerException im getting
java.lang.NullPointerException
at com.mycompany.anprsystems.EditRecords.editRecord(EditRecords.java:70)
at com.mycompany.anprsystems.EditRecords.main(EditRecords.java:52)
I need to put my searching of the file in my readData() method in a loop that catches the fine not found exception then loops to prompt the user again for the file name until the correct one is entered. Once the proper file name is entered, then the return values pass to the other methods to continue the code.
I have tried putting the block of code into a do-while method but it results in a infinite loop. I need assistance with the semantics of this.
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
do{
try {
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
}
while(!file.exists());
return inputValues;
}
I am expecting this to explain "File not found!" then prompt again for the file name until the correct one is entered. However it only does the try-catch once and then attempts to return the inputValues return value. This causes the program to crash.
I have tried do while loop. But it ends up in an infinite loop
package weightedavgdataanalyzer;
import java.io.*;
import java.util.*;
public class WeightedAvgDataAnalyzer {
public static void main(String[] args) {
ArrayList<Double> inputValues = readData();
double weightedAvg = calcWeightedAvg(inputValues);
printResults(inputValues, weightedAvg);
}
private static void printResults(ArrayList<Double> inputValues, double weightedAvg) {
System.out.print("Enter output file name: ");
Scanner input = new Scanner(System.in);
String outputFile = input.nextLine();
try {
PrintWriter writer = new PrintWriter(outputFile);
writer.print("The weighted average of the numbers is " + weightedAvg + ", when using the data ");
for (int i = 2; i < inputValues.size(); i++) {
writer.print(inputValues.get(i) + ", ");
}
writer.println("where " + inputValues.get(0)
+ " is the weight used, and the average is computed after dropping the lowest "
+ Integer.valueOf((int) inputValues.get(1).doubleValue()) + " values.");
writer.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static double calcWeightedAvg(ArrayList<Double> inputValues) {
double sum = 0;
double average;
double weight = inputValues.get(0);
int toDrop = Integer.valueOf((int) inputValues.get(1).doubleValue());
ArrayList<Double> newList = new ArrayList<>();
for (int i = 2; i < inputValues.size(); i++) {
newList.add(inputValues.get(i));
}
Collections.sort(newList);
for (int i = (toDrop); i < newList.size(); i++) {
sum += weight * newList.get(i);
}
average = sum / (newList.size() - toDrop);
return average;
}
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
do{
try {
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
}
while(!file.exists());
return inputValues;
}
}
Move the initialization of File file = new File(inputFileName); inside the loop as well as the "ask for new file name line". And last step is to also check if the file is an directory. You can't read directories with a Scanner, but file.exists() will still return true
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
File file;
System.out.print("Enter the name of the input file: ");
do {
inputFileName = input.nextLine();
file = new File(inputFileName);
try {
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
} catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
} while (!file.exists() && !file.isDirectory());
return inputValues;
}
The other answers have not addressed that it is bad practice to control the flow of your code using catch and exception. You should reserve using your catch block for typically printing your errors or logging them.
I moved the logic of asking for the file into a loop that does not depend on an exception to correctly execute and placed it into a reusable method.
Here is what this change would look like:
ArrayList<Double> inputValues = new ArrayList<>();
double value;
File file = promptForFile(); //Condensed into a clean reusable single line of code
try {
Scanner input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
} catch (FileNotFoundException e) {
e.printStackTrace(); //Or log the error
}
And the method you can reuse anywhere for a new prompt:
public static File promptForFile()
{
System.out.print("Enter the name of the input file: ");
Scanner input = new Scanner(System.in);
String inputFileName = input.nextLine();
File file = new File(inputFileName);
while(!file.exists() && !file.isDirectory())
{
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
inputFileName = input.nextLine();
file = new File(inputFileName);
}
return file;
}
Now the logic of your code is separated from searching for the file and the code is extremely reusable and readable.
This couldn't be done before since you had two different logics mixed intertwined.
File myFile = new File("myFile.txt");
while(!myFile.exists()){
//re-enter filename and instantiate myFile as a new object using it as the argument
}
could just check whether the file exists in a loop like so before using it. The issue with looping for the FileNotFoundException is that your writer is what throws that, so you would have to constantly instantiate the writer and check whether the exception is thrown before possibly looping again, which isn't ideal.
The problem is when the exception is caught, you never ask for a new file name, so you are running the code on the same faulty file path over and over again. To fix this, just move this code block:
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
inside the loop.
You may also want to eliminate a condition on your loop, and instead add a return; at the end of your try block.
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
String inputFileName;
double value;
Scanner input = new Scanner(System.in);
while (true) {
try {
// Get response in the loop, instead of one time-only
System.out.print("Enter the name of the input file: ");
inputFileName = input.nextLine();
File file = new File(inputFileName);
input = new Scanner(file);
while (input.hasNextDouble()) {
value = input.nextDouble();
inputValues.add(value);
}
// Add your return statement here to get rid of the conditional
// loop.
return inputValues;
}
catch (FileNotFoundException e) {
System.out.println("File not found!");
System.out.println("Please enter file name again: ");
}
}
}
You can take input and can return once file is found or else can keep recording error message
public File getFile(){
while(true) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter the name of the input file: ");
File file = new File(System.in);
if (file.exists()) {
return file;
}else{
System.out.println("File not found! Please try again ");
}
}
}
}
private List<Double> getData(File file){
List<Double> listOfDoubles = new ArrayList<>();
try(Scanner scanner = new Scanner(file)){
while(scanner.hasNextDouble()) {
listOfDoubles.add(scanner.nextDouble());
}
}
return listOfDoubles;
}
private static ArrayList<Double> readData() {
ArrayList<Double> inputValues = new ArrayList<>();
File inputFile = getFile();
return getData(inputFile);
}
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.
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,
Having an issue here, I need this loop to print new lines of code to a file until but what it does is print 1 line then fails on the second time round,
Can never get it to print to another line, below is code
public class study {
public static void main(String[] args) throws IOException{
BufferedWriter post = null;
File file = new File("text.txt");
if(!file.exists()){
file.createNewFile();
}
boolean promptUser = true;
FileWriter fileWriter = new FileWriter(file);
post = new BufferedWriter(fileWriter);
try {
while(promptUser){
System.out.println("enter age "); //get age
Scanner getage = new Scanner(System.in);
int age= getage.nextInt();
if(age <20 || age>50){ //age range
System.out.println("age must be between 20 and 50");
System.exit(0);
}
System.out.println("enter name "); //get name
Scanner getname = new Scanner(System.in);
String name= getname.nextLine();
System.out.println("enter email "); //get email
Scanner getarea = new Scanner(System.in);
String email= getarea.nextLine();
post.write(age + "\t"); <===== fails here on second run
post.write(name + "\t");
post.write(email + "\t");
post.newLine();
post.close();
System.out.println("enter quit to quit or any key to continue");
Scanner options = new Scanner(System.in);
String option = options.nextLine();
if(option.equalsIgnoreCase("quit")){
System.out.println("goodbye!");
System.exit(0);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
post.write(age + "\t");
post.newLine();
post.write(name + "\t");
post.newLine();
post.write(email + "\t");
post.newLine();
//remove post.close(); from here
Now it may solve Your problem
Replace post.close(); with post.flush(); and you should be fine.
Close the stream when the exit condition is entered.
FIXED IT GUYS
I needed to move the FileWriter line out of the TRY
import java.io.*;
import java.util.*;
public class study {
public static void main(String[] args) throws IOException {
BufferedWriter post = null;
File file = new File("text.txt"); //create file
if (!file.exists())
{
file.createNewFile();
}
boolean promptUser = true;
FileWriter fileWriter = new FileWriter(file);
try {
while (promptUser) {
post = new BufferedWriter(fileWriter);
System.out.println("enter age "); // get age
Scanner getage = new Scanner(System.in);
int age = getage.nextInt();
if (age < 20 || age > 50){ //age range
System.out.println("age must be between 20 and 50");
System.exit(0);
}
System.out.println("enter name "); //get name
Scanner getname = new Scanner(System.in);
String name= getname.nextLine();
System.out.println("enter email "); // get email
Scanner getarea = new Scanner(System.in);
String email= getarea.nextLine();
//send data to file
post.write(age + ";");
post.write(name + ";");
post.write(email + ";");
post.newLine();
post.flush();
System.out.println("enter quit to quit or any key to continue");
Scanner options = new Scanner(System.in);
String option = options.nextLine();
if (option.equalsIgnoreCase("quit")) {
System.out.println("goodbye!");
post.close(); // close file upon quitting
System.exit(0);
}
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}