I am trying to write a program to create player objects and save them to a file(Which I have done).
The problem I am trying to resolve is, I want to be able to pull the players out of the file when needed. So if I want to get the information for just player 1 or player n, with just their details is there a way I can pull it from the file if needed?
Any help or ideas would be greatly appreciated.
Thanks very much for your help in advance.
package p;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Runner {
public static final Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("output.txt", true);
PlayerData player = null;
List<PlayerData> players = new ArrayList<>();
System.out.println("How many players do you want to register? : ");
int num = input.nextInt();
while (true) {
System.out.println("Plz enter Name : ");
String name = input.next();
writer.write("Name: " + name + System.lineSeparator());
System.out.println("Plz enter age : ");
String age = input.next();
writer.write("Age: " + age + System.lineSeparator());
System.out.println("Plz enter Player_id : ");
String player_id = input.next();
writer.write("Player_id: " + player_id + System.lineSeparator());
System.out.println("Plz enter agent_id : ");
String agent_id = input.next();
writer.write("Agent_id:" + agent_id + System.lineSeparator());
System.out.println("Plz enter status : ");
String status = input.next();
writer.write("Status: " + status + System.lineSeparator());
System.out.println("Plz enter position : ");
String position = input.next();
writer.write("Position: " + position + System.lineSeparator());
System.out.println("Plz enter valuation : ");
Double valuation = input.nextDouble();
writer.write("Value: " + valuation + System.lineSeparator());
writer.write("\n " + System.lineSeparator());
System.out.println("\n");
player = new PlayerData(name, age, player_id, agent_id, valuation, status, position);
players.add(player);
System.out.println("Information Entered: \n" + player + "\n" + "Name : " + name + "\n" + "Age: " + age
+ "Player id: " + player_id + "\n" + "Agent id: " + agent_id + "\n" + "Player Value: " + valuation
+ "\n" + "Player Status:" + status + "\n" + "Player position:" + position + "\n");
writer.close();
if (players.size() == num)
break;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("output.txt")));
String line = " ";
System.out.println("Current Players on the transfer List \n");
while ((line = reader.readLine()) != null) {
System.out.println(line);
} // while
reader.close();// close reader
}
}
Maybe something along the lines of this, first while loop should get you to a place where the player name matches your input name , next while will get the next 7 lines into the playerinfo list.
public FileReader fr = new FileReader("path/to/your/file");
public BufferedReader br = new BufferedReader(fr);
String playerName = "John";
String line;
List<String> playerInfo = new ArrayList<String>();
while((line = br.readLine()) != null){
if (line.contains(playerName))
{
int numLines = 7;
playerInfo.add(line);
while((line = br.readLine()) != null && numLines >= 1){
playerInfo.add(line);
numLines --;
break;
}
break;
}
}
You might try using Java Object Serialization:
Java Object Serialization (Oracle)
I guess regardless of whether you use your current method or Object Serialization, you could save each player to a different file.
Related
vaccination.txt
Can someone help me with my codes? I have a problem displaying the information on the screen. I need to display the info based on the question requirement below:
Display all information about those born in Selangor who received the booster dose (dose 3) on screen. The person born in Selangor is represented by two digits there are 10 after the six digits that represent the birth date from the identification (ic) number.
I also have a problem writing the data into the relevant files. I tried the same method (by using the print writer) as what I have done before, but it doesn't work here and Idk why. Do help me
import java.io.*;
import java.util.*;
public class Main
{
public static void main(String\[\] args) {
File inFile = new File ("vaccination.txt");
File comorbid = new File ("comorbid.txt");
File nonComorbid = new File ("non_comorbid.txt");
try {
//read data from file
Scanner sc = new Scanner (inFile);
//write data into file
PrintWriter pw = new PrintWriter(comorbid);
PrintWriter pw2 = new PrintWriter (nonComorbid);
String vaccinePlace = " ", ICnum = " ", category = " ", vaccineType = " ";
int doseNum = 0;
pw.println("Matric Name Part Gender");
pw.println("--------------------------------------------------------------------");
pw2.println("Matric Name Part Gender");
pw2.println("--------------------------------------------------------------------");
while(sc.hasNext()) //check line by line
{
String data = sc.nextLine();
StringTokenizer st = new StringTokenizer(data, ":");
vaccinePlace = st.nextToken();
ICnum = st.nextToken();
category = st.nextToken();
vaccineType = st.nextToken();
doseNum = Integer.parseInt(st.nextToken());
//display information on screen
if (doseNum == 3)
{
if (ICnum.substring(6,8).equalsIgnoreCase("10"))
{
System.out.println("Vaccine place: " + vaccinePlace);
System.out.println("IC number: " + ICnum);
System.out.println("Category: " + category);
System.out.println("Vaccine type: " + vaccineType);
System.out.println("Dose number: " + doseNum);
}
}
//write and store information into comorbid.txt and nonComorbid file
if (category.equalsIgnoreCase("comorbid")) {
pw.println(vaccinePlace + " " + ICnum + " " + vaccineType + " " + doseNum);
}
if (category.equalsIgnoreCase("non-comorbid")) {
pw.println(vaccinePlace + " " + ICnum + " " + vaccineType + " " + doseNum);
}
} //end loop
sc.close();
pw.close();
pw2.close();
}
catch (FileNotFoundException fnf) {
System.out.println(fnf.getMessage());
}
catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
I am trying to make a list of players to add to a file, so I can store them and recall them when needed.
I have managed to write to the file, but each time I re-write to the file the last file entry gets overridden.
Has anyone got any idea how I can just save each entry to the file without it being overridden each time?
Any help would get greatly appreciated
Thanks in advance!!!!!!
package p;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Runner {
public static final Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
FileWriter writer = new FileWriter("output.txt");
PlayerData player = null;
List<PlayerData> players = new ArrayList<>();
System.out.println("How many players do you want to register? : ");
int num = input.nextInt();
while (true) {
System.out.println("Plz enter Name : ");
String name = input.next();
writer.write("Name: " + name + System.lineSeparator());
System.out.println("Plz enter age : ");
String age = input.next();
writer.write("Age: " + age + System.lineSeparator());
System.out.println("Plz enter Player_id : ");
String player_id = input.next();
writer.write("Player_id: " + player_id + System.lineSeparator());
System.out.println("Plz enter agent_id : ");
String agent_id = input.next();
writer.write("Agent_id:" + agent_id + System.lineSeparator());
System.out.println("Plz enter status : ");
String status = input.next();
writer.write("Status: " + status + System.lineSeparator());
System.out.println("Plz enter position : ");
String position = input.next();
writer.write("Position: " + position + System.lineSeparator());
System.out.println("Plz enter valuation : ");
Double valuation = input.nextDouble();
writer.write("Value: " + valuation + System.lineSeparator());
System.out.println("\n");
player = new PlayerData(name, age, player_id, agent_id, valuation, status, position);
players.add(player);
System.out.println("Information Entered: \n" + player + "\n" + "Name : " + name + "\n" + "Age: " + age
+ "Player id: " + player_id + "\n" + "Agent id: " + agent_id + "\n" + "Player Value: " + valuation
+ "\n" + "Player Status:" + status + "\n" + "Player position:" + position + "\n");
writer.close();
if (players.size() == num)
break;
}
System.out.println(players);
}
}
FileWriter writer = new FileWriter("output.txt", true);
Whenever I put inputs into this loop, no matter how many it will only write my final input to the file
Here's the code:
import java.util.Scanner;
import java.io.IOException;
import java.io.*;
class lista {
public static void main(String[] args) throws IOException {
Scanner n = new Scanner(System.in);
int x = 0;
File productList = new File("productList.txt");
FileWriter fr = new FileWriter("productList.txt", true);
/// While Loop Start
while (x == 0) {
System.out.println("Enter the product:");
String product = n.nextLine();
System.out.println("");
System.out.println("Enter the price:");
String price = n.nextLine();
System.out.println("");
System.out.println("Enter the type of product, e.g. Movie, Bluray, etc...");
String type = n.nextLine();
System.out.println("");
System.out.println(product + " - " + "$" + price + " (" + type + ")" + "\n\n");
try {
fr.write((product + " - " + "$" + price + " (" + type + ")" + "\n\n"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Type \"0\" if you would like to stop, type \"1\" if you would like to continue.");
int y = n.nextInt();
n.nextLine();
if (y == 1) {
x = 0;
} else {
x = 1;
fr.close();
}
}
/// While Loop Ends
}
}
I can input something like,
1,1,1,1
2,2,2,1
3,3,3,0
, and it will only print:
3 - $3 (3)
Thanks.
This is a possible duplicate of Trouble with filewriter overwriting files instead of appending to the end.
However you seem to have found the solution yourself already (the true parameter when creating the FileWriter). This should append to the file instead of overwriting it. If this does not work, then you might have a problem with the file or the OS. In any case, your code is not fundamentally wrong and should work.
Some suggestions for readability and ease of use on the code itself (just minor details).
Scanner in = new Scanner(System.in);
PrintStream out = System.out;
try (FileWriter writer = new FileWriter("productList.txt", true)) {
INPUT_LOOP:
while (true) {
out.println("Enter the product:");
String product = in.nextLine();
out.println();
out.println("Enter the price:");
String price = in.nextLine();
out.println();
out.println("Enter the type of product, e.g. Movie, Bluray, etc...");
String type = in.nextLine();
out.println();
String entry = product + " - " + "$" + price + " (" + type + ")" + "\n\n";
out.println(entry);
writer.append(entry);
out.println("Type \"exit\" if you would like to stop, any other input will continue.");
if (in.nextLine().trim().toLowerCase().equals("exit")) {
break INPUT_LOOP;
}
}
} catch (IOException e) {
e.printStackTrace();
}
I have a text file, and I want to find the middle word of the whole file and print the number of characters it has. I can do this for one line:
System.out.println("'" + str[tok / 2] + "'");
But I don't know how to point to a certain line. Here is all of my code:
import java.io.*;
import java.text.*;
import java.util.*;
public class AmendClassify {
public static void main(String[] args) {
try {
System.out.println("Please enter the file name:");
Scanner sc = new Scanner(System.in);
String file = sc.next();
file = file + ".txt";
Scanner s = new Scanner(new FileReader(file));
System.out.println("You are scanning '" + file + "'");
PrintWriter output = new PrintWriter(new FileOutputStream("output.txt"));
double lineNum = 0;
double wordCount = 0;
double charCount = 0;
int tok = 0;
String str[] = null;
DecimalFormat df = new DecimalFormat("#.#");
String line = null;
while (s.hasNextLine()) {
line = s.nextLine();
lineNum++;
str = line.split((" "));
tok = str.length;
for (int i = 0; i < str.length; i++) {
if (str[i].length() > 0) {
wordCount++;
}
}
charCount += (line.length());
}
double density = (charCount / wordCount);
System.out.println("'" + str[tok / 2] + "'"); // middle word of the 1st/last line
gap();
System.out.println("Number of lines: " + lineNum);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of characters: " + charCount);
gap();
System.out.println("The DENSITY of the text is: " + df.format(density));
System.out.println();
int critical;
System.out.println("Do you want to alter the critical value(Y/N)");
String answer = sc.next();
if (answer.equals("y") || answer.equals("Y")) {
System.out.println("Please enter a value: ");
critical = sc.nextInt();
} else {
critical = 6;
}
//So...
if (density > critical) {
System.out.println("NAME: '" + file + "'" + ", DENSITY: " + df.format(density) + ", TYPE: " + "Heavy");
} else {
System.out.println("NAME: '" + file + "'" + ", DENSITY: " + df.format(density) + ", TYPE: " + "Light");
}
System.out.print("--FINISHED--");
s.close();
output.close();
sc.close();
} //end of try
catch (FileNotFoundException e) {
System.out.println("Please enter a valid file name");
}
} // end of main
public static void gap() {
System.out.println("------------------------------");
}
}
A text file I have used to test is
Hello my name is Harry. This line contains 83 characters, 15 words, and 1 line(s).
This is the second line.
This is the third line.
This is the fourth line.
Since this looks like a homework assignment I'd recommend reading the entire file into a String and then removing all new-line characters with replaceAll() if need be (depending how you read the entire file into a String). You then would effectively have a single line ... so your existing code would work (taking into account that the middle word would actually be the word to the left of the middle if the file has an even number of words).
Note that this is not an optimal solution though. Don't use it at work.
I need help, obviously. Our assignment is to retrieve a file and categorize it and display it in another file. Last name first name then grade. I am having trouble with getting a loop going because of the error "java.util.NoSuchElementException" This only happens when I change the currently existing while I loop I have. I also have a problem of displaying the result. The result I display is all in one line, which I can't let happen. We are not allowed to use arraylist, just Bufferedreader, scanner, and what i already have. Here is my code so far:
import java.util.;
import java.util.StringTokenizer;
import java.io.;
import javax.swing.*;
import java.text.DecimalFormat;
/*************************************
Program Name: Grade
Name: Dennis Liang
Due Date: 3/31/11
Program Description: Write a program
which reads from a file a list of
students with their Grade. Also display
last name, first name, then grade.
************************************/
import java.util.*;
import java.util.StringTokenizer;
import java.io.*;
import javax.swing.*;
import java.text.DecimalFormat;
class Grade {
public static void main(String [] args)throws IOException {
//declaring
String line = "";
StringTokenizer st;
String delim = " \t\n\r,-";
String token;
String firstname;
String lastname;
String grade;
String S69andbelow="Students with 69 or below\n";
String S70to79 ="Students with 70 to 79\n";
String S80to89= "Students with 80 to 89\n";
String S90to100= "Students with 90 to 100\n";
int gradeint;
double gradeavg = 0;
int count = 0;
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
FileInputStream finput = new FileInputStream(inputFile);
FileOutputStream foutput = new FileOutputStream(outputFile);
FileReader reader = new FileReader(inputFile);
BufferedReader in = new BufferedReader(reader);
Scanner std = new Scanner(new File("input.txt"));
Scanner scanner = new Scanner(inputFile);
BufferedWriter out = new BufferedWriter(new FileWriter(outputFile));
Scanner scan = new Scanner(S69andbelow);
//reading linev
line = scanner.nextLine();
st = new StringTokenizer(line, delim);
//avoiding selected characters
try {
while(st.hasMoreTokens()) {
firstname = st.nextToken();
lastname = st.nextToken();
grade = st.nextToken();
//storing tokens into their properties
gradeint = Integer.parseInt(grade);
//converting token to int
gradeavg = gradeavg + gradeint;
//calculating avg
count++;
//recording number of entries
if (gradeint <=69) {
S69andbelow = S69andbelow + lastname + " "
+ firstname + " " + "\t" + grade + "\n";
} // saving data by grades
else if (gradeint >= 70 && gradeint <= 79) {
S70to79 = S70to79 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
else if (gradeint >= 80 && gradeint <=89) {
S80to89 = S80to89 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
else {
S90to100 = S90to100 + lastname + " " + firstname
+ " " + "\t" + grade + "\n";
} // saving data by grades
}//end while
System.out.println(S69andbelow + "\n" + S70to79 + "\n"
+ S80to89 + "\n" + S90to100);
//caterorizing the grades
gradeavg = gradeavg / count;
//calculating average
DecimalFormat df = new DecimalFormat("#0.00");
out.write("The average grade is: "
+ df.format(gradeavg));
System.out.println("The average grade is: "
+ df.format(gradeavg));
Writer output = null;
output = new BufferedWriter(new FileWriter(outputFile));
// scanner.nextLine(S69andbelow);
//output.write(S69andbelow + "\n" + S70to79 + "\n"
// + S80to89 + "\n" + S90to100);
// output.close();
}
catch( Exception e ) {
System.out.println(e.toString() );
}
// Close the stream
try {
if(std != null )
std.close( );
}
catch( Exception e ) {
System.out.println(e.toString());
}
}
}
my input file looks like this:
Bill Clinton 85 (enter)
Al Gore 100 (enter)
George Bush 95 (enter)
Hillery Clinton 83(enter)
John McCain 72(enter)
Danna Green 87(enter)
Steve Delaney 76(enter)
John Smith(enter)
Beth Bills 60(enter)
It would help to point things out just in case I don't follow you all the way through.
An easy way of finding a problem in this would be to comment out most of the code and find out each step at a time. So start with being able to read the file. Then print to the screen. Then print the organized data to the screen. Finally print the organized data to the file.
This should be a fairly simple