Alright gents I am trying to make a program that reads information from a file and then writes information out to another file.
I am reading from 2 columns first column is an integer (Team#) second column is a string(name of member)
1 Sam
3 Bob
6 Jill
3 Mike
1 Terra
1 Juice
6 Tom
6 Lucy
3 Dude
And then I have to take the 3rd instance in and output the name of the individual so it will look like this
Team Member
1 Juice
3 Dude
6 Lucy
I am having issues with trying to read the text into the array in order to output it, I am trying to use Parse String
My Code
package team;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Team {
public static void main(String[] args) throws FileNotFoundException {
//Output Please wait
System.out.println("Team Leader Started. Please wait....");
//Add Read and Write File locations
File inFile = new File("C:\\Users\\Christ\\Documents\\NetBeansProjects\\Team\\src\\team\\read.txt");
File outFile = new File("C:\\Users\\Christ\\Documents\\NetBeansProjects\\Team\\src\\team\\outputfile.txt");
// Initialise Arrays
int[] team = new int[99];
String[] name = new String[99];
// Scanner
Scanner sc = new Scanner(inFile);
sc.nextLine(); // move to second line assuming file is not empty.
// While Loop
while(sc.hasNextLine()) {
String s = sc.nextLine().trim();
String[] splitStr = s.split(" ");
team[Integer.parseInt(splitStr[0])-1] += Integer.parseInt(splitStr[1]);
name[String.parseString(splitStr[0])-1]++;
}
PrintWriter outFileWriter = new PrintWriter(outFile);
outFileWriter.println("Team Name");
// For loop
for(int i=0;i<99;i++) {
// Team
int t=i+1;
// Member
String m = name[i];
// Output to File
outFileWriter.println(t + " "+" "+ " " + m);
}
outFileWriter.close();
//Output Completed file, reference output file for sucees
System.out.println("Team Leader Completed Successfully");
}
}
Can someone please tell me where im going wrong? I do not want the final result only the ability at the moment to output the Team number and then the Member name to my output file.
Please Help ^_^
I would use a Map<Integer, ArrayList<String>> to store your team members with their corresponding teams.
It allows you to store key/value pairs and to maintain a dynamic list of members for each team.
public static void main(String [] args) throws FileNotFoundException{
System.out.println("Team Leader Started. Please wait....");
Map<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();
//Add Read and Write File locations
File inFile = new File("C:\\Users\\Christ\\Documents\\NetBeansProjects\\Team\\src\\team\\read.txt");
File outFile = new File("C:\\Users\\Christ\\Documents\\NetBeansProjects\\Team\\src\\team\\outputfile.txt");
// Scanner
Scanner sc = new Scanner(inFile);
// While Loop
while(sc.hasNextLine()) {
String s = sc.nextLine();
String[] splitStr = s.split(" ");
Integer id = Integer.parseInt(splitStr[0]);
String name = splitStr[1];
List<String> list = map.get(id);
if(list == null)
map.put(id, new ArrayList<>(Arrays.asList(name)));
else {
list.add(name);
}
}
PrintWriter outFileWriter = new PrintWriter(outFile);
outFileWriter.println("Team Name");
// For loop
for(Map.Entry<Integer, ArrayList<String>> entry : map.entrySet()){
outFileWriter.write(entry.getKey()+"\t"+entry.getValue().toString()+"\n");
}
outFileWriter.close();
//Output Completed file, reference output file for sucees
System.out.println("Team Leader Completed Successfully");
}
Output :
Team Name
1 [Sam, Terra, Juice]
3 [Bob, Mike, Dude]
6 [Jill, Tom, Lucy]
If you know the number of inputted people, then adding a row to the input file denoting the length would allow for array sizes to be the minimum required also this gets rid of 100+ people casing an issue
like:
#9
1 Sam
3 Bob
6 Jill
3 Mike
1 Terra
1 Juice
6 Tom
6 Lucy
3 Dude
Related
Reset may not be the right word here, but I am currently building a program that lets the user look up a name, and by scanning a txt file containing a list of names followed by numbers, the program then displays the numbers following said name. The way I am doing this is via .nextLine, but if the user inputs a name that's later in the list (say Samantha in the example) and then tries to look up a name at the top of the list (like Sally), the second name isn't found.
For reference, here is an example of that txt file:
Sally 0 0 0 0 0 0 0 0 0 0 886
Sam 58 69 99 131 168 236 278 380 467 408 466
Samantha 0 0 0 0 0 0 272 107 26 5 7
Samir 0 0 0 0 0 0 0 0 920 0 798
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class BabyNames {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Scanner input = new Scanner (new File("BabyNames.txt"));
Scanner keyboard = new Scanner (System.in);
System.out.println("This program allows you to search through the data from the "
+ "Social Security Administration to see how popular a particular name has "
+ "been since 1900.");
System.out.print("Name? ");
String name = keyboard.nextLine();
do {
while(input.hasNextLine()) {
String text = input.nextLine();
String[] words = text.split(" ");
if (text.contains(name)) {
System.out.println("Statistics on name \"" + name + "\"");
for (int i = 1; i < words.length; i++) {
System.out.println((1900 + (i-1)*10) + ": " + words[i]);
}
System.out.println("Enter another name or type quit to exit.");
name = keyboard.nextLine();
break;
}
else if (name.contains("quit") || name.contains("quit")){
System.exit(0);
}
else {
continue;
}
System.out.print("Error, name not found.");
}
} while (!name.contains("quit") || name.contains("quit"));
}
}
I looked up the .reset method but that hasn't seemed to work. Honestly, I'm stumped here.
Again, don't try to "reset" the Scanner or re-read the file. Your best bet is to read the file once and place all the data into a collection of some type, here a Map<String, SomeCustomClass> would work best. I'd first create a class to hold a row of information, perhaps called BabyName, one that holds a String field for name and an Integer List for the numbers listed after the name, something like:
import java.util.*;
public class BabyName {
String name;
List<Integer> numberList = new ArrayList<>();
public BabyName(String name, List<Integer> numberList) {
this.name = name;
this.numberList = numberList;
}
public String getName() {
return name;
}
public List<Integer> getNumberList() {
return numberList;
}
#Override
public String toString() {
return "BabyName [name=" + name + ", numberList=" + numberList + "]";
}
// consider adding hashCode and equals methods that are based on the name field alone
// ...
}
And then I'd recommend in your code a method that takes a line of text that has been extracted from the file, and converts it into a BabyName object:
private static BabyName createBabyName(String line) {
String[] tokens = line.split("\\s+");
String name = "";
List<Integer> numberList = new ArrayList<>();
// ... code to extract the data and that fills the numberList here
// ... left blank for you to fill in
BabyName babyName = new BabyName(name, numberList);
return babyName;
}
And then create a Map<String, BabyName> babyNameMap = new HashMap<>(); to hold BabyName objects using the name field as the map key, and when you read the file (just once mind you), you fill the map:
Scanner fileScanner = null;
try {
fileScanner = new Scanner(new File(FILE_PATH_NAME));
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(-1);
}
// read file and fill the map
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
BabyName babyName = createBabyName(line);
babyNameMap.put(babyName.getName(), babyName);
}
Then you can use this map to get the data from the user multiple times without having to re-read the file or reuse a Scanner.
e.g.,
String nameEnteredByUser = keyboard.nextLine();
BabyName selectedBabyName = babyNameMap.get(nameEnteredByUser);
// check for null here first
String name = nameEnteredByUser;
List<Integer> numberList = selectedBabyName.getNumberList();
Java Scanner, in general, doesn't know/control the pointer position in the file. It wraps over InputStream which in turn provides the input to the Scanner w.r.t every nextLine() call.
Scanner systemInput = new Scanner(System.in);
//new Scanner(new FileInputStream("file.t"));
InputStream has Mark/Reset feature which will help us to control the pointer position.
(Note: mark/ reset enables us to mark a checkpoint and you can jump back to the checkpoint later.)
Unfortunately, FileInputStream doesn't support it. But, BufferedInputStream came to the rescue.
Let's cook a solution for your problem,
Create a FileInputStream with your input file.
Wraps it with BufferedInputStream which provides mark() and reset() functions.
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream("BabyNames.txt"));
Provide it as input to the Scanner constructor.
Scanner input = new Scanner (inputStream);
Mark a checkpoint at the beginning of the file.
inputStream.mark(0);//saving a checkpoint
After the end of the inner while loop, reset the pointer to the marked position.
inputStream.reset();
Now, your code works fine.
The task is to create a java program that reads information from three .csv files and output a list of transcripts, ordered in descending order of aggregate mark, to a file in the current directory called "RankedList.txt". The program should show whether students have passed their year at university and what grade they achieved. The students took two modules, IR101 and IR102. This data is stored in two .csv files, IR101.csv and IR102.csv. Their names and registration numbers are stored in students.csv.
The rules of assessment stipulate the following:
Students must pass both modules in order to proceed to Stage 2. The pass mark for a module is 40.
Students who do not pass both modules will be deemed to have failed.
Students who fail only one of the two modules will be allowed a resit attempt.
Students who fail both modules will be required to repeat the year.
Students who pass both modules will be awarded a class based on their aggregate mark using the following scale:
70 – 100 = 1st
60 – 69.9 = 2.1
50 – 59.9 = 2.2
40 – 49.9 = 3rd
I have been able to complete this task however one problem I have faced is that my code only works for .txt files. If someone could show me how to change my code to work with .csv files I would be most grateful. My program so far is as follows:
package assignment;
import java.io.*;
import java.util.*;
public class StudentsMarks {
public static void main(String[] args) throws FileNotFoundException,IOException {
String currDir = "C:\\Users\\phili_000.Philip.001\\workspace\\ce152\\src\\ass\\StudentsMarks.java";
Scanner sc = new Scanner(new File(currDir+"IRStudents.csv"));
HashMap<Integer, String> students = new HashMap<Integer, String>();
while (sc.hasNext()) {
String line = sc.nextLine();
students.put(sc.nextInt(), sc.next());
String[] parts = line.split(",");
}
sc = new Scanner(new File(currDir+"IR101.csv"));
HashMap<Integer, Double> ir1 = new HashMap<Integer, Double>();
while (sc.hasNext()) {
String line = sc.nextLine();
ir1.put(sc.nextInt(), sc.nextDouble());
String[] parts = line.split(",");
}
sc = new Scanner(new File(currDir+"IR102.csv"));
HashMap<Integer, Double> ir2 = new HashMap<Integer, Double>();
while (sc.hasNext()) {
String line = sc.nextLine();
ir2.put(sc.nextInt(), sc.nextDouble());
String[] parts = line.split(",");
}
File output=new File(currDir+"RankedList.txt");
BufferedWriter b=new BufferedWriter(new FileWriter(output));
Iterator<Integer> ids = students.keySet().iterator();
while (ids.hasNext()) {
Integer id=ids.next();
b.write(id+" "+students.get(id));
b.newLine();
Double marks1=ir1.get(id);
Double marks2=ir2.get(id);
Double aggregate=(marks1+marks2)/2;
b.write("IR101\t "+marks1+"\t IR102\t "+marks2+"\t Aggregate "+aggregate);
b.newLine();
String classStd;
if(aggregate>=70){
classStd="1st";
}else if(aggregate>=60){
classStd="2.1";
}else if(aggregate>=50){
classStd="2.2";
}else if(aggregate>=40){
classStd="3rd";
}else{
classStd="failed";
}
String outcome;
if(marks1<40 && marks2<40){
outcome="Repeat the year";
}else if(marks1<40){
outcome="Resit IR101";
}else if(marks2<40){
outcome="Resit IR102";
}else{
outcome="Proceed to Stage 2";
}
b.write("Class:\t " + classStd + "\t Outcome: " + outcome);
b.newLine();
b.write("----------------------------------------------------");
b.newLine();
}
b.flush();
b.close();
}
}
String csvFile = "path.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] parts = line.split(cvsSplitBy);
}
} catch (Exception e) {
e.printStackTrace();
}
when reading a csv you should read the file line by line at the same time you should split the string in the line by using split method then you will
get an array of strings.
I am supoose to read a file lets say it has 3 lines:
2
Berlin 0 2 2 10000 300
Nilreb 0 2 2 10000 300
the first integer number shows how many names(lines) i have.
the 2nd and 3rd lines show information about two post offices.
them i am suppose to read each line and save the data.
I have to create post offices that they are names: Berlin and Nilreb.
Can anyone help me?
so far i have done this:
public static void read_files() throws IOException{
Scanner in = new Scanner(new File("offices")); //open and read the file
int num_of_lines = in.nextInt();
while(in.hasNext()){
String offices = in.nextLine();
}
To read files I recommend to you to use an ArrayList:
Scanner s = new Scanner(new File(//Here the path of your file));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext())
{
list.add(s.nextLine());
}
Now in your ArrayList you will have all the lines of your file. So, now, you can go through all the post offices that you have with a for loop (I start in the index 1 because the first line it's the line of how many post offices are in the file, you won't need it with this method) and split them to get all the information about them. For example, in the position 0 of the array of Strings you will have the name of your post Office and in the rest of the positions (1,2,3,4...) the rest of your values stored in your file (one value by space in your line). Like this:
for(int i = 1; i < list.size(); i++)
{
String[] line = list.get(i).split(" ");
System.out.println("The name of this post office is " + line[0]);
}
EDIT: I saw now in a comment above that you want to create a class for each line. Then you can do (inside the for loop, instead of the System.out.println) the code that I put below (supossing that your class will be PostOffice):
PostOffice postOffice = new PostOffice(line[0],line[1],line[2],line[3],line[4],line[5]);
Note: If you don't understand something about my code please let me know.
I expect it will be helpful for you!
I think I figured it out: can u check if it is correct:
public static void read_files() throws IOException{
Scanner in = new Scanner(new File("offices"));
int num_of_lines = in.nextInt();
String[] office = new String[num_of_lines];
while(in.hasNext()){
for(int = 0; i < num_of_lines; i++){
office[i] = in.next();
}
List item
I am writing a method that will take in some command line arguments, validate them and if valid will edit an airport's code. The airport name and it's code are stored in a CSV file. An example is "Belfast,BHD". The command line arguments are entered as follows, java editAirport EA BEL Belfast, "EA" is the 2letter code that makes the project know that I want to Edit the code for an Airport, "BEL" is the new code, and Belfast is the name of the Airport.
When I have checked through the cla's and validated them I read through the file and store them in an ArrayList as, "Belfast,BEL". Then I want to update the text file by removing the lines from the text file and dumping in the arraylist, but I cannot figure out how to do it. Can someone show me a way using simple code (no advanced java stuff) how this is possible.
Here is my program
import javax.swing.*;
import java.io.*;
import java.util.*;
import java.text.*;
public class editAirport
{
public static void main(String [] args)throws IOException
{
String pattern = "[A-Z]{3}";
String line, line1, line2;
String[] parts;
String[] parts1;
boolean found1 = false, found2 = false;
File file = new File("Airports.txt"); // I created the file using the examples in the outline
Scanner in = new Scanner(file);
Scanner in1 = new Scanner(file);
Scanner in2 = new Scanner(file);
String x = args[0], y = args[1], z = args[2];
//-------------- Validation -------------------------------
if(args.length != 3) // if user enters more or less than 3 CLA's didplay message
JOptionPane.showMessageDialog(null, "Usage: java editAirport EA AirportCode(3 letters) AirportName");
else if(!(file.exists())) // if "Airports.txt" doesn't exist end program
JOptionPane.showMessageDialog(null, "Airports.txt does not exist");
else // if everything is hunky dory
{
if(!(x.equals("EA"))) //if user doesn't enter EA an message will be displayed
JOptionPane.showMessageDialog(null, "Usage: java editAirport EA AirportCode(3 letters) AirportName");
else if(!(y.matches(pattern))) // If the code doesn't match the pattern a message will be dislayed
JOptionPane.showMessageDialog(null, "Airport Code is invalid");
while(in.hasNext())
{
line = in.nextLine();
parts = line.split(",");
if(y.equalsIgnoreCase(parts[1]))
found1 = true; //checking if Airport code already is in use
if(z.equalsIgnoreCase(parts[0]))
found2 = true; // checking if Airport name is in the file
}
if(found1)
JOptionPane.showMessageDialog(null, "Airport Code already exists, Enter a different one.");
else if(found2 = false)
JOptionPane.showMessageDialog(null, "Airport Name not found, Enter it again.");
else
/*
Creating the ArrayList to store the name,code.
1st while adds the names and coses to arraylist,
checks if the name of the airport that is being edited is in the line,
then it adds the new code onto the name.
sorting the arraylist.
2nd for/while is printing the arraylist into the file
*/
ArrayList<String> airport = new ArrayList<String>();
while(in1.hasNext()) // 1st while
{
line1 = in1.nextLine();
if(line1.contains(z))
{
parts1 = line1.split(",");
parts1[1] = y;
airport.add(parts1[0] + "," + parts1[1]);
}
else
airport.add(line1);
}
Collections.sort(airport); // sorts arraylist
FileWriter aFileWriter = new FileWriter(file, true);
PrintWriter output = new PrintWriter(aFileWriter);
for(int i = 0; i < airport.size();)
{
while(in2.hasNext()) // 2nd while
{
line2 = in2.nextLine();
line2 = airport.get(i);
output.println(line2);
i++;
}
}
output.close();
aFileWriter.close();
}
}
}
}
The Airports.txt file is this
Aberdeen,ABZ
Belfast City,BHD
Dublin,DUB
New York,JFK
Shannon,SNN
Venice,VCE
I think your problem may lie in the two lines:
line2 = in2.nextLine();
line2 = airport.get(i);
this will overwrite the 'line2' in memory, but not in the file.
I need to create a Linked List from a text file that looks like this:
john, peter, maria, dan, george, sonja
fred, steve
ann, tom, maria
//etc...
I want to print the first name in each line (leader) and the remaining names in the line (associated with that name).
So for example:
Leader: John Friends: peter, maria, dan, george, sonja Friend Count: 5
Leader: Fred Friends: steve Friend Count: 1
//etc...
This is what I have so far:
import java.util.*;
import java.io.*;
import javax.swing.JFileChooser;
public class Test {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<String>();
LinkData ld1 = new LinkData();
JFileChooser chooser = new JFileChooser(".");
int returnVal = chooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: "
+ chooser.getSelectedFile().getName()
+ "Print some info"
// open and read file:
Scanner scanner = null;
try {
scanner = new Scanner(chooser.getSelectedFile());
} catch (IOException e) {
System.err.println(e);
error();
}
if (scanner == null)
error();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Scanner lineScan = new Scanner(line);
lineScan.useDelimiter(", ");
// System.err.println("The line that was scanned: " + line);
String leader = lineScan.next();
while (lineScan.hasNext()) {
list.add(lineScan.next());
}
System.out.println("Leaders include_" + leader + list.toString());
}
}
}
private static void error() {
System.err.println("An error has occurred: bad data");
System.exit(0);
}
}
Right now, the first name is printing fine, but then the linked list keeps growing and growing so the results don't print the way I want...
you should clear() the list between 2 line reads
while (scanner.hasNextLine()) {
list.clear();
//...
}
You are on the right track. You are processing each line into a leader and a list of friends. You will want to keep track of each of those entities in another object - I would recommend a Map. Something like:
Map<String, List<String>> leaderMap = new HashMap<String, List<String>>();
// ...
String leader = lineScan.next();
while (lineScan.hasNext()) {
list.add(lineScan.next());
}
leaderMap.put(leader, list);
Don't forget to reinitialize the list for each line you read from the file. At the end you can iterate the map, print the key (leader), and size of associated list (number of friends). Good luck!