Java writing to file method writes nothing from arraylist - java

So here's the problem: File gets created, first line of text gets written, but the text within the logic loop of for>if>while doesn't write: PassengerSeats.println(nRowNum +cSeatLetter +" " +sPassengerName);
Here's the main method code in question:
else if (nMainChoice == 4) {
System.out.print("Please enter a flight number: ");
nMainFlight = input.nextInt();
input.nextLine();
System.out.println("Please enter a date of departure: ");
System.out.print("Month: (i.e For January, enter 1): ");
sMonth = input.nextLine();
System.out.print("Day: (i.e for the 15h, enter 15): ");
sDay = input.nextLine();
System.out.print("Year: (i.e for 2015, enter 15): ");
sYear = input.nextLine();
sDate = sMonth +"/" +sDay +"/" +sYear;
System.out.println(sDate);
PrintManifest newManifest = new PrintManifest(TicketsList,
FlyersList, nMainFlight, sDate, sMonth, sDay, sYear);
And here's the PrintManifest code it refers to:
public PrintManifest(ArrayList<Tickets> TicketsListing, ArrayList<Flyers> FlyersListing,
int nFlightID, String sFlightDate, String sFMonth, String sFDay,
String sFYear) throws Exception{
String sFlightManifest = "DataFiles/Manifest-nFlightID-sFMonth-sFDay-sFYear.txt";
File FlightManifest = new File(sFlightManifest);
PrintWriter PassengerSeats = new PrintWriter(FlightManifest);
PassengerSeats.println("Flight manifest for #" +nFlightID +" on " +sFlightDate);
for (nCount = 0; nCount < TicketsListing.size(); nCount++) {
if (nFlightID == TicketsListing.get(nCount).getFlightNumber()
&& sFlightDate == TicketsListing.get(nCount).getDate()) {
nRowNum = TicketsListing.get(nCount).getRow();
cSeatLetter = TicketsListing.get(nCount).getSeat();
while (TicketsListing.get(nCount).getFlyerID() != FlyersListing.get(nCountFly).getID()) {
nCountFly++;
} //End while loop
sPassengerName = FlyersListing.get(nCountFly).getFirst() +" "
+FlyersListing.get(nCountFly).getLast();
PassengerSeats.println(nRowNum +cSeatLetter +" " +sPassengerName);
} //End if
} //End for loop
PassengerSeats.close();
And a sample of the data it's pulling from TicketsList, which is already parsed and stored within an arraylist:
19836;1258;1359;1/2/15;A;5;A
19837;1215;1359;1/2/15;A;6;C
19838;1245;438;1/11/15;M;15;F
19839;1129;1014;1/5/15;M;17;F
19840;1139;703;1/11/15;M;14;C
19841;1353;689;1/11/15;F;3;D
19842;1296;1014;1/2/15;F;4;F

The boolean expression
sFlightDate == TicketsListing.get(nCount).getDate()
will always evaluate to false, which means nothing in your if statement will execute. The equals method should be used to evaluate string equality, like this
sFlightDate.equals(TicketsListing.get(nCount).getDate())
because it compares the contents of the strings. The == operator compares the object pointer, which will always be different in this case.

Related

How to make this code decline String other than q

I still a little bit new so I'm going to include all of my java code and then explain what I am looking for.
import java.util.Scanner;
public class Part_I{
public static Scanner input = new Scanner(System.in);
public static String strInfo;
public static int number;
public static void main(String[] args){
String presidents[][] = {
{"1 ","George"," ","Washington"," (1789-1797) ","John Adams"},
{"2 ","John"," ","Adams"," (1797-1801) ","Thomas Jefferson"},
{"3 ","Thomas"," ","Jefferson"," (1801-1809) ","Aaron Burr"},
{"4 ","James"," ","Madison"," (1809-1817) ","George Clinton"},
{"5 ","James"," ","Monroe"," (1817-1825) ","Daniel D. Tompkins"},
{"6 ","John"," Quincy ","Adams"," (1825-1829) ","John C. Calhoun"},
{"7 ","Andrew"," ","Jackson"," (1829-1837) ","John C. Calhoun"},
{"8 ","Martin"," Van ","Buren"," (1837-1841) ","Richard M. Johnson"},
{"9 ","William"," Henry ","Harrison"," (1841) ","John Tyler"},
{"10 ","John"," ","Tyler"," (1841-1845) ","None"},
{"11 ","James"," K. ","Polk"," (1845-1849) ","George M. Dallas"},
{"12 ","Zachary"," ","Taylor"," (1849-1850) ","Millard Fillmore"},
{"13 ","Millard"," ","Fillmore"," (1850-1853) ","None"},
{"14 ","Franklin"," ","Pierce"," (1853-1857) ","William King"},
{"15 ","James"," ","Buchanan"," (1857-1861) ","John C. Breckinridge"},
{"16 ","Abraham"," ","Lincoln"," (1861-1865) ","Hannibal Hamlin"},
{"17 ","Andrew"," ","Johnson"," (1865-1869) ","None"},
{"18 ","Ulysses"," S. ","Grant"," (1869-1877) ","Schuyler Colfax"},
{"19 ","Rutherford"," B. ","Hayes"," (1877-1881) ","William Wheeler"},
{"20 ","James"," A. ","Garfield"," (1881) ","Chester Arthur"},
{"21 ","Chester"," ","Arthur"," (1881-1885) ","None"},
{"22 ","Grover"," ","Cleveland"," (1885-1889) ","Thomas Hendricks"},
{"23 ","Benjamin"," ","Harrison"," (1889-1893) ","Levi P. Morton"},
{"24 ","Grover"," ","Cleveland"," (1893-1897) ","Adlai E. Stevenson"},
{"25 ","William"," ","McKinley"," (1897-1901) ","Garret Hobart"},
{"26 ","Theodore"," ","Roosevelt"," (1901-1909) ","None"},
{"27 ","William"," Howard ","Taft"," (1909-1913) ","James S. Sherman"},
{"28 ","Woodrow"," ","Wilson"," (1913-1921) ","Thomas R. Marshall"},
{"29 ","Warren"," G. ","Harding"," (1921-1923) ","Calvin Coolidge"},
{"30 ","Calvin"," ","Coolidge"," (1923-1929) ","None"},
{"31 ","Herbert"," ","Hoover"," (1929-1933) ","Charles Curtis"},
{"32 ","Franklin"," D. ","Roosevelt"," (1933-1945) ","John Nance Garner"},
{"33 ","Harry"," S. ","Truman"," (1945-1953) ","None"},
{"34 ","Dwight"," D. ","Eisenhower"," (1953-1961) ","Richard Nixon"},
{"35 ","John"," F. ","Kennedy"," (1961-1963) ","Lyndon B. Johnson"},
{"36 ","Lyndon"," B. ","Johnson"," (1963-1969) ","None"},
{"37 ","Richard"," ","Nixon"," (1969-1974) ","Spiro Agnew"},
{"38 ","Gerald"," ","Ford"," (1974-1977) ","Nelson Rockefeller"},
{"39 ","Jimmy"," ","Carter"," (1977-1981) ","Walter Mondale"},
{"40 ","Ronald"," ","Reagan"," (1981-1989) ","George Bush"},
{"41 ","George"," ","Bush"," (1989-1993) ","Dan Quayle"},
{"42 ","Bill"," ","Clinton"," (1993-2001) ","Al Gore"},
{"43 ","George"," W. ","Bush"," (2001-2009) ","Dick Cheney"},
{"44 ","Barack"," ","Obama"," (2009-2017) ","Joe Biden"},
};
System.out.println("This will display the President and VP of the United States based on the number you provide.");
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
while(strInfo != "q"){
if(isInteger(strInfo)){
number = Integer.parseInt(strInfo);
if (number >= 1 && number <=44){
System.out.println();
System.out.println(presidents[number-1][0] + "President " + presidents[number-1][1] + presidents[number-1][2] + presidents[number-1][3] + presidents[number-1][4] + "Vice President " + presidents[number-1][5]);
System.out.println();
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
}else{
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
}else{
System.out.println();
System.out.println("This program has been terminated. Good Bye!");
System.exit(0);
}
}
}
public static boolean isInteger(String strInfo){
if (strInfo == null) {
return false;
}
int length = strInfo.length();
if (length == 0) {
return false;
}
int i = 0;
if (strInfo.charAt(0) == '-') {
if (length == 1) {
return false;
}
i = 1;
}
for (; i < length; i++) {
char c = strInfo.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
}
My main concern is with the while loop.
while(strInfo != "q"){
if(isInteger(strInfo)){
number = Integer.parseInt(strInfo);
if (number >= 1 && number <=44){
System.out.println();
System.out.println(presidents[number-1][0] + "President " + presidents[number-1][1] + presidents[number-1][2] + presidents[number-1][3] + presidents[number-1][4] + "Vice President " + presidents[number-1][5]);
System.out.println();
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
}else{
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
}else{
System.out.println();
System.out.println("This program has been terminated. Good Bye!");
System.exit(0);
}
}
}
I want to make it so that it any string other than what is able to be converted to an int or "q" would say wrong input and make you input another string value. Right now, any string will make the program terminate. What should I change in that while loop and how should I change it or what should it look like instead so that if the string input is not q or convertible to an int will make wrong input display and ask for input again?
This will help you in achieving what you want to do
while (!strInfo.equals("q")) {
if (isInteger(strInfo)) {
number = Integer.parseInt(strInfo);
if (number >= 1 && number <= 44) {
System.out.println();
System.out.println(presidents[number - 1][0] + "President " + presidents[number - 1][1] + presidents[number - 1][2] + presidents[number - 1][3] + presidents[number - 1][4] + "Vice President " + presidents[number - 1][5]);
System.out.println();
System.out.println("Please enter a number between 1 and 44 to see information or q to quit: ");
strInfo = input.nextLine();
} else {
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
} else {
System.out.println();
System.out.println("Wrong Input! Please enter number 1-44 or q to quit.");
strInfo = input.nextLine();
}
}
System.out.println();
System.out.println("This program has been terminated. Good Bye!");
System.exit(0);
You shouldn't check string equality using normal operators like "=" and "!=". Use the String .equals() method.
So your first line would be
while(!strInfo.equals("q"))
More info:
http://www.leepoint.net/data/expressions/22compareobjects.html
The reason your code is not working is because you are trying to compare whether the contents of two strings are equal using == operator (which only compares if the two references point to the same object). == Operator does not compare the contents of the two strings.
In order to make your code work, you would need to use equals to compare the contents of the two strings as follows :
while(!strInfo.equals("q"))
Now lets try to delve deep into why your code is not working. For that we need to understand the basic difference between == & equals
== Operator is used to compare if both the references on its either side point to the same object (Basically you can say its similar to
comparing address of the object to which the references point to).
Whereas equals in case of String compares the content of the two Strings. It is the responsibility of the creator of the class to override the default equals method to compare the objects of that class depending on what makes sense for that object. For example in case of String class the creators of the class have overriden the equals method to compare the contents of the Strings.
String a = "test"; // lets say the object guy has address : 24
String b = a; // now b points to the same object that is being referenced by a
System.out.println(a == b); // this will be true as both point to the same reference
System.out.println(a.equals(b)); // this will be true as the contents of both these strings is the same.
// Now lets consider a new strings having same content "test"
String c = "test";
System.out.println(a == c); // this will be false as both point to the different references or memory location
System.out.println(a.equals(c)); // this will be true as the contents of both these strings is the same.

How do I make my cancel button function

I realized I made an infinite loop and everytime I enter that loop, my cancel button doesn't function and the dialog box continuously pops up.
Here's the code
String buffer = " "; //Input a string into console
boolean badInput = true;
boolean badInput2 = true;
String idNum = ""; //ask for id number
String skill = ""; // ask for skill number
int skillInt = 0; // skill is an int
//prompt user for file location
File loc = new File(JOptionPane.showInputDialog(null, "Please provide the file location: "));
RandomAccessFile store = new RandomAccessFile(loc, "rw");
//prompt user for a command
String cmd = "start";
int recLocation = 0;
while(cmd.compareToIgnoreCase("end")!=0){ //stay in program (loop) until end command is given
cmd = JOptionPane.showInputDialog(null, "Please input a command (new, old or end): ");
//creating new entry
if(cmd.compareToIgnoreCase("new")==0){
while(badInput){ //keep them in loop until they give the input in the right format
idNum = JOptionPane.showInputDialog(null, "Please input an ID number (1 - 20): ");
// else JOptionPane.CANCEL_OPTIONsetDefaultCloseOperation(JOptionPane.EXIT_ON_CLOSE);
try{
//corresponding int for ID number, which becomes the record location
//if number is not 1-20, code below
recLocation = Integer.parseInt(idNum);
if(recLocation<1 || recLocation>20){
System.out.println("Please check that your number is between 1 and 20.");
}else{
badInput = false;
break;
}
}
catch(NumberFormatException NF){ // if input isnt a number
System.out.println("Please check that your number is in the correct format.");
}
}
//ask for names
String pName = JOptionPane.showInputDialog(null, "Please input a player name: ");
String tName = JOptionPane.showInputDialog(null, "Please input a team name: ");
//ask for skill level
while(badInput2){ //keep them in the loop until they give the input in the right format
skill = JOptionPane.showInputDialog(null, "Please input a skill level (0 - 99): ");
try{
//corresponding int for skill number, to check if in the right format
skillInt = Integer.parseInt(skill);
if(skillInt<0 || skillInt>99){
System.out.println("Please check that your number is between 0 and 99.");
}else{
badInput2 = false;
break;
}
}
catch(NumberFormatException NF){ //exception or error thrown if input is not in correct format
System.out.println("Please check that your number is in the correct format.");
}
}
String date = JOptionPane.showInputDialog(null, "Please input today's date (ex: 25Jun2014): ");
//formatting id number
if (idNum.length() < 2){
idNum = idNum+buffer;
}
//formatting player name
if (pName.length() > 26){
pName = pName.substring(0, 26);
} else {
while(pName.length() < 26){
pName = pName+buffer;
}
}
//formatting team name
if (tName.length() > 26){
tName = tName.substring(0, 26);
} else {
while(tName.length() < 26){
tName = tName+buffer;
}
}
//formatting date
if (date.length() > 9){
date = date.substring(0, 9);
} else {
while(date.length() < 9){
date = date+buffer;
}
}
//formatting skill
if (skill.length() < 2){
skill = skill+buffer;
}
//create full, identifying string
String fullRecord = idNum + " " + pName + tName + skill + " " + date;
store.seek((RECORD_LENGTH+2) * (recLocation-1));
store.writeUTF(fullRecord);
//reset booleans
badInput = true;
badInput2 = true;
}
//accessing old entry
if(cmd.compareToIgnoreCase("old")==0){
idNum = JOptionPane.showInputDialog(null, "Please input an ID number (1 through 20): ");
recLocation = Integer.parseInt(idNum);
store.seek((RECORD_LENGTH+2)*(recLocation-1));
String fullRecord = store.readUTF();
//interpret information from full string
try
{idNum = fullRecord.substring(0, 5);
String pName = fullRecord.substring(5, 31);
String tName = fullRecord.substring(31, 57);
skill = fullRecord.substring(57, 62);
String date = fullRecord.substring(62, 71);
System.out.println("ID: "+idNum+" NAME: "+pName+" TEAM: "+tName+" SKILL: "+skill+" DATE: "+date);
}
catch(StringIndexOutOfBoundsException S){
System.out.println("No record found at that location.");
}
}
// JOptionPane.showMessageDialog(null, "good bye");
}
Sorry if I didn't format this right. It's my first time. I was wondering how I could get the cancel button to exit the loop. I tried using if (cmd == null) System.exit(0); but that doesn't seem to function. I'm really novice at java and I have little experience so bear with me please.
First I'd suggest using equalsIgnoreCase as your String comparison instead of compareIgnoreCase: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String)
while(!cmd.equalsToIgnoreCase("end")) {
Then if one of the JOptionPane.showInputDialog()'s returns null which would mean they'd cancelled, you could have an if statement that sets the cmd string to "end". I think though you should probably try to simplify the loop because it's got a lot in it all in the one block. That makes it hard to debug.

Trying to write to an outfile.txt using variables from an if block

I am trying to write to an outfile.txt using variables that are inside if statements.
when I compile it it keeps saying the variable has not been initialized when in fact they have been, one as a string and char as the other.
import java.io.*;
import java.util.Scanner;
public class program5{
// read string keyboard inputs
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
Scanner in = new Scanner(System.in);
public static void main(String[] args) throws IOException{
// read string keyboard inputs
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int i, gradeA_count = 0, gradeB_count = 0, gradeC_count = 0,
gradeD_count = 0, gradeF_count = 0, first_grade,
second_grade, third_grade, fourth_grade,
total_of_grades;
String remarks, course_name, semester, instructor_name, student_name;
char grade;
double average_grade;
int[] array_of_int_numbers = new int[10];
Scanner sc = new Scanner(System.in);
// set up a outfile to write to
Writer outfile = new BufferedWriter(new FileWriter("e:outfile.txt"));
// Write the class information to the outfile
outfile.write(" CMPS 161 Program Five, Fall 2015\n\n");
// separate top and next line for ease of sight
outfile.write(" -------------------------------- \n\n");
System.out.println("Enter the course name: ");
course_name=input.readLine();
System.out.println("Enter the Semester: ");
semester=input.readLine();
System.out.println("Enter the Instructor: ");
instructor_name=input.readLine();
outfile.write("Course: " +(String.format("%-8s",course_name))+ " Semester: " +(String.format("%-10s",semester))+ " Instructor: " +(String.format("%-12s",instructor_name))+ "\n\n");
outfile.write("Array Item Student Name T1 T2 T3 T4 Avg Grade Remarks\n\n");
outfile.write("=================================================================\n\n");
// array initialization
for (i = 0; i < 1; i++) array_of_int_numbers[i] = 0;
// prompt user for a value into the array
for (i = 0; i < 1; i++){
System.out.println("Enter a Students Name: ");
student_name=input.readLine();
System.out.println("Enter the first grade: ");
first_grade=sc.nextInt();
System.out.println("Enter the second grade: ");
second_grade=sc.nextInt();
System.out.println("Enter the third grade: ");
third_grade=sc.nextInt();
System.out.println("Enter the fourth grade: ");
fourth_grade=sc.nextInt();
total_of_grades = first_grade + second_grade + third_grade + fourth_grade;
average_grade = (double) total_of_grades / 4.0;
System.out.println("Your average grade is " +(String.format("%.1f",average_grade))+ "\n");
if (average_grade >= 90){
remarks = "Excellent";
grade = 'A';
gradeA_count++;
}else if (average_grade >= 80){
remarks = "Very Good";
grade = 'B';
gradeB_count++;
}else if (average_grade >= 70){
remarks = "Good";
grade = 'C';
gradeC_count++;
}else if (average_grade >= 60){
remarks = "Poor";
grade = 'D';
gradeD_count++;
}else if (average_grade >= 0){
remarks = "Fail";
grade = 'F';
gradeF_count++;
}
outfile.write("["+i+"]"+ student_name +
"" + first_grade +
"" + second_grade +
"" + third_grade +
""+ fourth_grade +
"%" + average_grade +
"" + grade +
"" + remarks + "\n");
}
for (i = 0; i < array_of_int_numbers.length; i++){
System.out.println("array_of_int_numbers["+(i+1)+ "] = "+array_of_int_numbers[i]);
}
System.out.println("Number of A's : " + gradeA_count);
System.out.println("Number of B's : " + gradeB_count);
System.out.println("Number of C's : " + gradeC_count);
System.out.println("Number of D's : " + gradeD_count);
System.out.println("Number of F's : " + gradeF_count);
outfile.close();
} // end program
} // end class
I am new to coding (only my fifth program) and this is my first semester in college, any help would be greatly appreciated.
I am using JGrasp as my professor requires it and coding in java.
Edit:
Here are the exceptions being thrown:
program5.java:107: error: variable grade might not have been initialized
"" + grade +
^
program5.java:108: error: variable remarks might not have been initialized
"" + remarks + "\n");
^
At the beginning of the program, when you declare grade and remarks, you aren't initializing it. You must set these variables to a default value.
For example:
String remarks = "";
char grade = '0';
It doesn't really matter what they're set to right now, because they'll be changed later.
Now, if you know that average_grade will never be negative, then you can replace that last else if statement with a simple else. This is why Java thinks that the variables may not be initialized, because there is the possibility that average_grade could become negative.

Error with next int versus next line

The other question I asked was excellently answered, but at the end the person mentioned an issue with taking an int and not clearing to the next line in the file. I tried a few different things (the commented out stuff in my code that you will see) and nothing seems to work. I always get the same error no matter what I changed. Here is the error, my code, my class code, then the file in that order.
The error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at HuntowskiSamuel.main(HuntowskiSamuel.java:25)
The code section:
import java.util.Scanner; //I'm only gonna need scanner for this project I think
import java.io.*;
public class HuntowskiSamuel //This is what the file name should be as well as the class name
{
public static void main (String [] args) throws IOException
{
File cFile = new File("cipcs115.txt"); //This will be the file and scanner variable used to pull the data for the candidates
Scanner scan = new Scanner(cFile);
File cFileReadIn = new File("cipcs115.txt"); //While this file and scanner will be used to pull the number of candidates from the same file...hopefully
Scanner scanReadIn = new Scanner(cFileReadIn);
String StateName = "No name yet"; //This is where the state value will be held, that controls the input of the file
int NumberOfCandidates = 0; // This will pull the number of candidates for the array size
String garbage = "Empty"; //This is where the ReadIn scanner can dump excess stuff
StateName = scanReadIn.next(); //The prime read for the while loop
//garbage = scan.nextLine(); //Consuming the newline character
int NumberOfLettersEntered [] = new int [8]; //Since we only have the letters L, C, V, S, D, P, Q, and X (others/errors) that were entered, IN THAT ORDER. Its not graceful but it works
while(StateName != "END_OF_FILE") //While we haven't reached the end of the file
{
int i = scanReadIn.nextInt();
garbage = scan.nextLine(); //Getting rid of the whitespace after the int is taken
for(i=i; i > 0; i--) //Read in the number of candidates, then run the loop that number of times
{
NumberOfCandidates++; //Every time this loop runs, it means there is one more candidate for the total amount
garbage = scanReadIn.nextLine(); //This will take all the important info and dump it, seeing as we only need the number of candidates and the state name
}
StateName = scanReadIn.next(); //Pull the next state name
//garbage = scan.nextLine(); //Consuming the newline after the state pull
}
Candidate_Info candidates [] = new Candidate_Info [NumberOfCandidates]; //This creates an array of the exact size of the number of candidates in the file
for(int i = 0; i < NumberOfCandidates; i++) //Running the constructor for each and every candidate created
{
candidates[i] = new Candidate_Info();
}
StateName = scan.next(); //Prime read for the data taking loop
//garbage = scan.nextLine(); //Getting rid of the whitespace after the state
while(StateName != "END_OF_FILE") //The same as the other loop, only using the real file and scanner variables
{
int CandidateNumber = 0; //This will keep the array number straight from 0 to however many candidates - 1
int candidatesPerState = scan.nextInt();
garbage = scan.nextLine(); //To get rid of the rest of the whitespace after the int return
for(int i = 0; i < candidatesPerState; i++) //This will loop for each of the candidates in ONE STATE, it pulls the number of candidates as an int
{
candidates[CandidateNumber].setState(StateName);
candidates[CandidateNumber].setName(scan.next());
candidates[CandidateNumber].setOffice(scan.next());
candidates[CandidateNumber].setParty(scan.next().charAt(0)); //This might not work because it is just a single character versus the string that it would be passed
candidates[CandidateNumber].setVotes(scan.nextInt());
candidates[CandidateNumber].setSpent(scan.nextDouble());
candidates[CandidateNumber].setMotto(scan.nextLine());
CandidateNumber++;
}
StateName = scan.next();
//garbage = scan.nextLine(); //To get rid the whitespace after taking the state value
}
}
}
The class code:
//Samuel James Huntowski
// started: 11-18-2014
// last modified: 11-18-2014
public class Candidate_Info
{
private String State; //All the variables that were given to me in the specification
private String Name_of_Candidate;
private String Election_Office;
private char Party;
private int Number_of_Votes;
private double Dollars_Spent;
private String Motto;
private final double DOLLARS_SPENT_MIN = 0.0; //Mutator method for Dollars_Spent must check to see if greater then this value
private final int NUMBER_OF_ATTRIBUTES = 7; //for use in the equals method
public Candidate_Info()
{
State = "No state assigned"; //Giving empty values to all of the variables
Name_of_Candidate = "No name yet";
Election_Office = "No office assigned";
Party = 'X';
Number_of_Votes = 0;
Dollars_Spent = 0.0;
Motto = "No motto yet";
}
//These are all of the Accessor Methods
public String getState()
{
return State;
}
public String getName()
{
return Name_of_Candidate;
}
public String getOffice()
{
return Election_Office;
}
public char getParty()
{
return Party;
}
public int getVotes()
{
return Number_of_Votes;
}
public double getSpent()
{
return Dollars_Spent;
}
public String getMotto()
{
return Motto;
}
//Mutator methods will go here
public void setState(String newState)
{
State = newState;
System.out.println("The candidate's state is now set to " + newState + ".");
}
public void setName(String newName)
{
Name_of_Candidate = newName;
System.out.println("The candidate's name is now set to " + newName + ".");
}
public void setOffice(String newOffice)
{
Election_Office = newOffice;
System.out.println("The candidate's office is now set to " + newOffice + ".");
}
public void setParty(char newParty)
{
if(!((newParty == 'd') || (newParty == 'r') || (newParty == 'i') || (newParty == 'o'))) //If the value of newParty DOES NOT EQUAL 'o', 'd', 'r', or 'i' then do the next set of code
{
System.out.println("Invalid party input. Candidate's party remains unchanged. Please try again.");
}
else
{
Party = newParty;
System.out.println("The candidate's party is now set to " + newParty + ".");
}
}
public void setVotes(int newNumberOfVotes)
{
Number_of_Votes = newNumberOfVotes;
System.out.println("The candidate's number of votes is now set to " + newNumberOfVotes + ".");
}
public void setSpent(double newDollarsSpent)
{
if(newDollarsSpent < DOLLARS_SPENT_MIN) //If the amount of money spent is less then zero (Which just wouldn't make sense, so that's why I set the variable to zero)
{
System.out.println("New amount of dollars spent is invalid. Candidate's dollars spent remains unchanged. Please try again.");
}
else
{
Dollars_Spent = newDollarsSpent;
System.out.println("The candidate's dollars spent is now set to " + newDollarsSpent + ".");
}
}
public void setMotto(String newMotto)
{
Motto = newMotto;
System.out.println("The candidate's motto is now set to \"" + newMotto + "\"");
}
public void displayAll()
{
System.out.println(State + "\t" + Name_of_Candidate + "\t"
+ Election_Office + "\t" +
Party + "\t" + Number_of_Votes +
"\t" + Dollars_Spent + "\t" + Motto); //Display all info separated by tabs
}
public String toString()
{
String ReturnThis = (State + "\t" + Name_of_Candidate + "\t" +
Election_Office + "\t" + Party +
"\t" + Number_of_Votes + "\t" +
Dollars_Spent + "\t" + Motto); //same as displayAll() just in one string
return ReturnThis;
}
public boolean equals(Candidate_Info PassedCandidate)
{
boolean TF [] = new boolean [NUMBER_OF_ATTRIBUTES]; //An array of booleans that match the number of attributes above
boolean finalResult; //This will hold the final boolean result of all the below calculations
if(State.equals(PassedCandidate.getState())) TF[0] = true; //This isn't the most graceful method of doing this, but it works
else TF[0] = false;
if(Name_of_Candidate.equals(PassedCandidate.getName())) TF[1] = true;
else TF[1] = false;
if(Election_Office.equals(PassedCandidate.getOffice())) TF[2] = true;
else TF[2] = false;
if(Party == PassedCandidate.getParty()) TF[3] = true;
else TF[3] = false;
if(Number_of_Votes == PassedCandidate.getVotes()) TF[4] = true;
else TF[4] = false;
if(Dollars_Spent == PassedCandidate.getSpent()) TF[5] = true;
else TF[5] = false;
if(Motto.equals(PassedCandidate.getMotto())) TF[6] = true;
else TF[6] = false;
if(TF[0] && TF[1] && TF[2] && TF[3] && TF[4] && TF[5] && TF[6]) finalResult = true; //If ALL OF THE ATTRIBUTES equal the attributes of the passed candidate, therefore making all the TF variables true, then they are equal
else finalResult = false;
return finalResult;
}
}
And the file:
Illinois
3
Obama President d 131313 19.21 Great in 2008!
Daley Mayor d 5678 89000.45 My dad was good!
Stevenson Governor d 2367 43877.45 My hair is bad!
Wisconsin
6
Smith Mayor r 3 5.98 You can count on me daily!
Bush President r 11004 1222888.44 My dad was good too!
Gore President d 11003 54.34 Hear my Gore-y details!
Kim Governor r 111 3212.16 I'm the other Guy!
Hanrath Instructor i 6 0.12 What, me worry?
Jones Instructor o 9 14.56 You'd better worry!
Alaska
4
Nader President o 2 50.00 Nader's Raiders!
Alexander Mayor i 13 13.13 What am I doing?
Thompson Governor o 1 0.00 And you thought I was gone!
Schwarzenegger President o 123 1233377.94 I'll be back!
Delaware
2
Allen Instructor i 147 16.71 No exams in cs105!
Stewart President o 3 27367.67 I'm a good thing!
END_OF_FILE
Each of the data values of the file is seperated by a tab, but I didn't think that would matter as the methods that I use stop at the whitespace. Was I wrong? Where did I screw up? This is all happening at run time by the way. It compiles fine after you guys helped me earlier.

Issue with writing and reading from file

I am in a situation where I want to write something(writing employee details with punchin & punchout) to a file and read it back(to show as a report of who all the employees punchedin & punchedout).
package Test;
import java.io.*;
import java.text.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws IOException {
String lastName = "";
String firstName = "";
String choice = "y";
String customerChoice = "x";
int empid = 0;
Scanner sc = new Scanner(System.in);
int currentIndex;
File file = new File("E:/output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
int[] punchedArray;
punchedArray = new int[100];
// System.out.println(t);
while (!customerChoice.equalsIgnoreCase("d") && customerChoice != "invalid" && choice.equalsIgnoreCase("y")) {
customerChoice = getValidCustomerChoice(sc);
if (customerChoice.equalsIgnoreCase("a")) {
// System.out.println("In Create Customer");
System.out.print("Enter your first name: ");
firstName = sc.next();
System.out.print("Enter your last name: ");
lastName = sc.next();
System.out.println(firstName + lastName + "with employee id" + empid);
//System.out.println(firstNameArray[newEmployeeIndex] + " " + lastNameArray[newEmployeeIndex] + " your employee ID is: " + employeeIDArray[newEmployeeIndex]);
empid++;
//sc.next();
}
if (customerChoice.equalsIgnoreCase("b")) {
System.out.println("Welcome to the punch in/out screen"+"\n");
System.out.print("Enter your employee ID: ");
currentIndex = Integer.parseInt(sc.next());
if (punchedArray[currentIndex] == 0)
{
System.out.println("You are now punched in");
punchedArray[currentIndex] = 1;
}
else if (punchedArray[currentIndex] == 1)
{
System.out.println("You are now punched out");
punchedArray[currentIndex] = 0;
}
System.out.print(firstName + " "+ lastName + " "+ "your employee ID is " + currentIndex + " and your clock date and time is: " + " "+ cal.getTime() +"\n");
String content = firstName + lastName + empid + cal.getTime();
bw.write(content);
bw.newLine();
bw.close();
}
if (customerChoice.equalsIgnoreCase("c")) {
System.out.print("Welcome to the report screen." + "\n");
System.out.print("Enter your selection (I = individual report or A= all employees):" + "\n");
customerChoice = sc.next();
if (customerChoice.equalsIgnoreCase("i")) {
System.out.println("In Individual Report");
} else if (customerChoice.equalsIgnoreCase("a")) {
System.out.println("In Consoldated Report");
}
}
if(customerChoice.equalsIgnoreCase("d"))
{
//bw.close();
break;
}
}
}
public static String getValidCustomerChoice(Scanner sc) {
String customerChoice = "";
// sc.nextLine();
boolean isValid = false;
int invalidCounter = 0;
System.out.print("Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):");
while (isValid == false && invalidCounter < 3) {
customerChoice = sc.next();
if (!customerChoice.equalsIgnoreCase("a")
&& !customerChoice.equalsIgnoreCase("b") && !customerChoice.equalsIgnoreCase("c") && !customerChoice.equalsIgnoreCase("d") && !customerChoice.equalsIgnoreCase("I") && !customerChoice.equalsIgnoreCase("A")) {
System.out.println("Invalid choice. Try again.\n");
invalidCounter++;
} else {
isValid = true;
}
sc.nextLine();
}
if (invalidCounter >= 3) {
System.out.println("Invalid three times. Program Exiting.\n");
return "invalid";
}
return customerChoice;
}
}
At line[75] bw.write(content) I am writing to a file called "output.txt"(I also want to add timestamp to those employees whom I wrote to file). But somehow the data is not going into the file, I am sure that I am making a mistake somewhere in closing that and I want to read from the same file which I wrote. Can someone please suggest me where I am going wrong?
Adding more details:
run:
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):a
Enter your first name: Sa
Enter your last name: Ka
SaKawith employee id0
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):b
Welcome to the punch in/out screen
Enter your employee ID: 0
You are now punched in
Sa Ka your employee ID is 0 and your clock date and time is: Sun Jun 08 20:19:42 EDT 2014
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):a
Enter your first name: Ka
Enter your last name: Ma
KaMawith employee id1
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):b
Welcome to the punch in/out screen
Enter your employee ID: 1
You are now punched in
Ka Ma your employee ID is 1 and your clock date and time is: Sun Jun 08 20:19:42 EDT 2014
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):c
Welcome to the report screen.
Enter your selection (I = individual report or A= all employees):
a
In Consoldated Report
Enter your selection (a= Add New Employee, b = Punch in/out, c= Report, d = Exit):BUILD STOPPED (total time: 1 minute 8 seconds)
So,when I go now to E drive of my Pc I just see a file named output.txt(latest modified time) but there's nothing in it. I tried to close my buffer after the loop but no luck with it. Also, Please advise on reading the data which I wrote to the file
Please advise!
Thanks
I'm not sure if I understand your issue, but like this, you can only write to the file once, since you close it after writing to it. Instead, you can use the flush() method to ensure the contents are written to the file.
Consider reading the documentation at http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html.
In my test it works fine . but change bw.close(); to bw.flush(); Because the outputstream will be closed after first input. and att second input you got an exception
Right off the bat I'd suggest trying to replace your file name with E:\output.txt. I believe windows file paths use backslashes.

Categories

Resources