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.
Related
So I'm working on a project that requires me to compare a users input to a list of words in a txt file. I've been trying to compare the the input as a string to the BufferReader, but it hasn't been working. Any suggestions is welcomed
Here's the code for the project
public class Lab5Program1 {
public static void main(String[] args) throws IOException {
File file = new File("fileName");
BufferedReader br = new BufferedReader(new FileReader(file));
/** In order to read a text file that is inside the package, you need to call the actual file and then pass it
* to the BufferedReader. So that it can be used in the file**/
// String[] wordArray = { "hello", "goodbye", "cat", "dog", "red", "green", "sun", "moon" };
String isOrIsNot, inputWord;
// This line asks the user for input by popping out a single window
// with text input
inputWord = JOptionPane.showInputDialog(null, "Enter a word in all lower case:");
// if the inputWord is contained within wordArray return true
if (wordIsThere(inputWord, br))
isOrIsNot = "is"; // set to is if the word is on the list
else
isOrIsNot = "is not"; // set to is not if the word is not on the list
// Output to a JOptionPane window whether the word is on the list or not
JOptionPane.showMessageDialog(null, "The word " + inputWord + " " + isOrIsNot + " on the list.");
} //main
public static boolean wordIsThere(String findMe, BufferedReader bufferedReader) throws IOException {
// for (int i = 0; i < bufferedReader.lines() ; i++){
// if (findMe.equals(theList[i])){
// return true;
// }
// }
while((findMe = bufferedReader.readLine()) != null) {
if (findMe.equals(bufferedReader.readLine())){
return true;
}
}
return false;
} // wordIsThere
}
The error is coming from the function to check if the word exists. Each line being reader from the text file is not being checked with findMe. Made these changes, it works.
public static boolean wordIsThere(String findMe, BufferedReader br) throws IOException {
for (String word = br.readLine() ; word != null; word = br.readLine()) {
if (word.equals(findMe))
return true;
}
return false;
}
In method wordIsThere, parameter findMe is the word you are looking for. However you overwrite the value of the parameter with the line read from the file.
You should declare a separate variable to store the line of text that you read from the file.
public static boolean wordIsThere(String findMe, BufferedReader bufferedReader) throws IOException {
String line = bufferedReader.readLine(); // read first line of file
while(line != null) {
if (findMe.equals(line)){
return true;
}
line = bufferedReader.readLine(); // read next line of file
}
return false;
}
Also note that since you are using JOptionPane to get user input, a separate thread is launched and this thread does not terminate when method main terminates. Hence you should call method exit, of class java.lang.System in the last line of main, in class Lab5Program1. Otherwise, each time you run class Lab5Program1 you will start a new JVM that will not terminate.
For console applications, you can use class java.util.Scanner to get user input.
Scanner stdin = new Scanner(System.in);
System.out.print("Enter a word in all lower case: ");
String inputWord = stdin.nextLine();
Also consider closing files when you have finished with them. In your case it is not necessary since the file is automatically closed when the JVM terminates.
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.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
So i have a tiny problem, for some reason I'm blanking and I've tried moving it inside the loop and back to the outside of the loop it doesn't work. In option two which returns method display_names it reads them from the file it writes them to the console on one line instead of two separate lines.
ex:
Enter two knew people clicking 3:
smith, rob, 123-123-1234
smith, tom, 123-123-1235
Display names by clicking 2:
smith, rob, 123-123-1234smith, tom, 123-123-1235
instead of:
smith, rob, 123-123-1234
smith, tom, 123-123-1235
Main Code:
import java.util.*;
import java.io.*;
public class ContactList
{
/**
Contact list file name
*/
private String filename;
String findMe;
/**
ContactList constructor accepts a String parameter
*/
public ContactList(String inFileName)
{
filename = inFileName;
}
/**
3) add a new record to the file. Open the file for writing in append mode(there is a FileWriter constructor with the appropriate parameters).
a) prompt the user to enter data for each field in the record. Each field is a String.
The last name is required. If the last name is the empty string(""), return to the menu.
b) when the user has completed entering data(i.e., all the fields have been prompted), re-display the user choices
c) do not overwrite existing data
*/
public void new_record()
{
/*
Prompt for data:
Last name
First name
Phone
*/
//Create a scanner object
Scanner scan = new Scanner(System.in);
//prompt for the last name
System.out.println("Last Name: ");
//input the last name
String lastName = scan.next();
//the Last_name must not be empty
if(lastName.length() > 0)
{
//get the first name and the phone
System.out.println("Enter First Name: ");
String firstName = scan.next();
System.out.println("Enter phone number(xxx-xxx-xxxx): ");
String phone = scan.next();
//create the output string
String info = String.format("%s, %s, %s", lastName, firstName, phone);
//Declare variables to hold file types
File file = new File(filename);
//try to open the file for writing - append the data
try
{
if(!file.exists()){
PrintWriter out = new PrintWriter(filename);
out.println(info);
out.flush();
out.close();
}
else if(file.exists()){
FileWriter fw = new FileWriter(filename, true);
fw.write(info);
fw.close();
}
}
catch(IOException ioe)
{
System.out.println("new_record: Exception opening the file for writing");
}
}//end of test of Last_name
}//end of new_record
/**
2) display all last names and first names in the file.
Open the file for reading, read each record and
display the field values.
a) display all the lastName, firstName paired fields in the file;
display with the format lastName, firstName
b) when all records have been displayed, display the record count - the record count is the number of records read and should equal the number of records in the file
c) after all the records and the count have been displayed, display the user choices
*/
public void display_names()
{
//delare variables to hold file types
File file = new File(filename);
//try to open the file for reading
try
{
if(file.exists()){ //if the file exists allow it to be read
BufferedReader br = new BufferedReader(new FileReader(filename)); //Allows the file to be read line by line
String line = br.readLine();
int count = 0;
System.out.println("");
while(line != null){
System.out.println(line);
line = br.readLine();
count++;
}
System.out.println("");
System.out.println("Total records read: " +count);
br.close();
}
}
catch(IOException ioe)
{
System.out.println("display_names: Exception opening the file");
}
}//end of display_names
/**
1) search an address file for a particular last name
and then display the Last name, the first name, and
the phone for each match
2) display the count of records which match the last name
*/
public void search(String LastName)
{
//Declare variables to hold file types
File file = new File(filename);
this.findMe = LastName;
//try to open the file for reading
try
{
if(file.exists()){
BufferedReader br = new BufferedReader(new FileReader(filename)); //Allows the file to be read line by line
String s="", line = null;
int count = 0;
while((line = br.readLine()) != null){
String [] parts = line.split(",");
if(parts[0].equals(findMe)){
count = 1;
s= line;
}
}
System.out.println("\n"+s+"\n");
System.out.println("Total matching records found: " +count);
br.close();
}
}
catch(IOException ioe)
{
System.out.println("search: Exception opening the file");
}
}//end of search
}//end of class
Tester Code:
import java.util.*;
public class TestContactList
{
/**
main
*/
public static void main(String args [])
{
final int ONE = 1;
final int TWO = 2;
final int THREE = 3;
final int FOUR = 4;
final int FIVE = 5;
Scanner scan = new Scanner(System.in);
/*
*/
while(true)
{
System.out.println("1) Search an address file for a particular last name ");
System.out.println("2) Display all last names and first names in the file ");
System.out.println("3) Add a new record to the file ");
System.out.println("4) End the program ");
System.out.print("Please choose 1 - 4: ");
int choice = scan.nextInt();
scan.nextLine();
/*
Create a new ContactList object with the name of the
contact list file.
*/
ContactList cl = new ContactList("MyAddressBook.txt");
/*
if 4 exit program
*/
if(choice == FOUR)
{
System.exit(0);
}
/*
if 1 call search method
*/
if(choice == ONE)
{
System.out.print("Enter name to find: ");
String findMe = scan.nextLine();
cl.search(findMe);
}
/*
if 2 call display_names method
*/
if(choice == TWO)
{
cl.display_names();
}
/*
if 3 call new_record method
*/
if(choice == THREE)
{
cl.new_record();
}
}//end of while loop
}//end of main
}
thanks in advance xD, I think this should be a simple fix
well, it seems that the data files are the ones missing here :-) but from your code
while((line = br.readLine()) != null){
s += line;
count++;
}
System.out.println("\n"+s+"\n");
it seems that you're appending your items into "s" and only in the end you're embracing it between newlines.
Instead, I think you should add the newline inside the while loop.
Of course, there are other issues like using StringBuilder or StringBuffer to concatenate strings.
Your format string (String.format) needs to have a line separator.
So I'm at a point in my program where I want to read from a csv file (which has two columns), do some light calculation on the first column (after I check whether or not it has any content), then print the new number (which I calculated from column 1 in the first file) and the contents of the second column from the original file to a new text file.
Without a while loop I have no trouble running calculations on the numbers from the original text file, then printing them to the new file. However ANY printing from inside the while loop is giving me an error. In fact, anything other than reading the file and parsing it into an array of strings is giving me an error from inside the while loop.
These are the top two lines of my stackTrace with the code I currently have posted below:
"Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
at finalProyect.User.makeMealPlan(User.java:476)"
Line 476 being the line in my while loop: "if (array2[0].isEmpty())"
After hours of searching and tinkering I thought it was time to ask for help. Thanks in advance for any help you can provide.
public void makeMealPlan() {
String fileIn = "mealPlan1.csv";
Scanner inputStream = null;
String fileOut = userName + ".txt";
PrintWriter outputStream = null;
try {
inputStream = new Scanner(new File(fileIn));//opens and reads pre-configured meal plan
outputStream = new PrintWriter(fileOut);//creates output file for meal plan
} catch(FileNotFoundException e3) {
fileNotFound();
e3.printStackTrace();
}
outputStream.println(toString());
outputStream.println();
String line0 = inputStream.nextLine();
String[] array0 = line0.split(","); //Splits line into an array of strings
int baseCalories = Integer.parseInt(array0[0]); //converts first item in array to integer
double caloricMultiplier = (caloricNeeds / baseCalories); //calculates the caloricMultiplier of the user
String line1 = inputStream.nextLine();//reads the next line
String[] array1 = line1.split(",");//splits the next line into array of strings
outputStream.printf("%12s %24s", array1[0], array1[1]); //prints the read line as column headers into text file
while(inputStream.hasNextLine()) {
String line = inputStream.nextLine(); //reads next line
String[] array2 = line.split(",");
if(array2[0].isEmpty()) {
outputStream.printf("%12s %24s", array2[0], array2[1]);
} else {
double quantity = Double.parseDouble(array2[0]);
quantity = (quantity * caloricMultiplier);
outputStream.printf("%12s %24s", quantity, array2[1]);
}
}
outputStream.close();
System.out.println(toString());
}
Okay, so there were a few things wrong. However with #NonSecwitter's suggestion I was able to pin it down. So first thing (again as NonSecwitter mentioned) I had empty fields in my .csv which was throwing the ArrayIndexOutOfBounds" error. So what I did was I filled every empty field in my .csv with the string "empty". Once I did that I was able to at least print the next line.
After that, I ran into another error which was that this line:
double quantity = Double.parseDouble(array2[0]);
could not be separated from the the preceding read/split statements by being inside of an if-loop. So I ended up rewriting the guts of the entire while-loop and needed to throw an exception like so:
while (inputStream.hasNextLine())
{
String[] array2 = null;
try
{
String line = inputStream.nextLine(); //reads next line
array2 = line.split(",");
double quantity = Double.parseDouble(array2[0]);
if (!isStringNumeric(array2[0]))
throw new NumberFormatException();
quantity = Math.ceil(quantity * caloricMultiplier);
outputStream.printf("%12.1f %15s\n", quantity, array2[1]);
}
catch(NumberFormatException e1)
{
if (array2[1].equals("empty"))
outputStream.printf("%12s %15s\n", " ", " ");
else
outputStream.printf("%12s %15s\n", " ", array2[1]);
}
}
While my program is now currently working just fine, I'd still really appreciate an explanation as to why I ended up having to throw an exception to get the code to work. Are there certain restrictions with using PrintWriter inside of a while-loop? Also, I very much appreciate everybody's feedback. I think with all the comments/suggestions combined I was able to determine where my problems were (just not WHY they were problems).
Thanks!!!
It would help if you provided sample CSV data and an example of the related output you expect in <userName>.txt.
Short of this I can only help insofar as saying I do not get an exception with your code.
Here is what I got with a quick Java project in Eclipse using project and class-file names gleaned from your exception output (finalProyect and User.java respectively), pasting your code into the class file (User.java), and massaging it a bit for a sanity check...
package finalProyect;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class User {
public void makeMealPlan()
{
String fileIn = "C:\\Temp\\mealPlan1.csv";//"mealPlan1.csv"; // FORNOW: adjusted to debug
Scanner inputStream = null;
String userName = "J0e3gan"; // FORNOW: added to debug
String fileOut = "C:\\Temp\\" + userName + ".txt"; // FORNOW: adjusted to debug
PrintWriter outputStream = null;
try
{
inputStream = new Scanner(new File(fileIn));//opens and reads pre-configured meal plan
outputStream = new PrintWriter(fileOut);//creates output file for meal plan
}
catch(FileNotFoundException e3)
{
//fileNotFound(); // FORNOW: commented out to debug
e3.printStackTrace();
}
outputStream.println(toString());
outputStream.println();
String line0 = inputStream.nextLine();
String[] array0 = line0.split(","); //Splits line into an array of strings
int baseCalories = Integer.parseInt(array0[0]); //converts first item in array to integer
int caloricNeeds = 2000; // added to debug
double caloricMultiplier = (caloricNeeds / baseCalories); //calculates the caloricMultiplier of the user
String line1 = inputStream.nextLine();//reads the next line
String[] array1 = line1.split(",");//splits the next line into array of strings
outputStream.printf("%12s %24s", array1[0], array1[1]); //prints the read line as column headers into text file
while (inputStream.hasNextLine())
{
String line = inputStream.nextLine(); //reads next line
String[] array2 = line.split(",");
if (array2[0].isEmpty())
outputStream.printf("%12s %24s", array2[0], array2[1]);
else
{
double quantity = Double.parseDouble(array2[0]);
quantity = (quantity * caloricMultiplier);
outputStream.printf("%12s %24s", quantity, array2[1]);
}
}
outputStream.close();
System.out.println(toString());
}
public static void main(String[] args) {
// FORNOW: to debug
User u = new User();
u.makeMealPlan();
}
}
...and an example of what it output to J0e3gan.txt...
finalProyect.User#68a6a21a
3000 40 2500.0 50 4000.0 25
...with the following (complete-WAG) data in mealPlan1.csv:
2000,20
3000,40
2500,50
4000,25
Comment out the offending code and try to println() array2[0] and see if it gives you anything.
while (inputStream.hasNextLine())
{
String line = inputStream.nextLine(); //reads next line
String[] array2 = line.split(",");
System.out.println(array2[0]);
//if (array2[0].isEmpty())
// outputStream.printf("%12s %24s", array2[0], array2[1]);
//
//else
//{
//
// double quantity = Double.parseDouble(array2[0]);
// quantity = (quantity * caloricMultiplier);
// outputStream.printf("%12s %24s", quantity, array2[1]);
//}
}
or, try to print the length. If the array were empty for some reason array2[0] would be out of bounds
System.out.println(array2.length);
I would also print line to see what it's picking up
System.out.println(line);
I'm trying to make an array of strings using a list of names coming from a txt file.
So for example: If I have string[] names = {all the names from the txtfile(one name perline)}
I want to pass "names" into a method that takes in a array like "names"(the one I made above). The method will then run the names through another for loop and create a linked list. I'm really confusing myself on this and tried number of things but nothing seems to work. Right now It'll print out the first name correctly but every name after that just says null. So I have about 70 nulls being printed out.
public static void main(String[] args) {
//String[] names = {"Billy Joe", "Alan Bowe", "Sally Mae", "Joe Blow", "Tasha Blue", "Malcom Floyd"}; // Trying to print theses names..Possibly in alphabetical order
BigNode x = new BigNode();
Scanner in = new Scanner(System.in);
System.out.println("Enter File Name: ");
String Finame = in.nextLine();
System.out.println("You Entered " + Finame);
try {File file = new File(Finame);
BufferedReader readers = new BufferedReader(new FileReader(file));
// String nameLine = ;
String[] name;
name = new String[73];
String[] nameTO;
String nameLine;
// while ((nameLine = readers.readLine()) != null) {
for (int i = 0; i < name.length; i++){
name[i] = readers.readLine();
x.populateNodes(name);
} //}
} catch(IOException e) {
}
Why is x.populateNodes(name) inside the loop? Wouldn't you be populating it after filling your array?
Since I've no idea what BigNode is, I assume it should be one of the following
x.populateNodes(name[i]) inside the loop or x.populateNodes(name) outside the loop.