[Java] Can't Get Writing to a File Working Properly.

Joined
Apr 14, 2008
Messages
3
Reaction score
0
Hey, This is my current Problem:

Step 1 - Read from a file (2 Lines, Single digit on Each) - DONE
Example:
Code:
5
25

Step 2 - Determine All of the Even numbers in between those two numbers - DONE
Example:
Code:
6
8
10
12
14
16
18
20
22
24

Step 3 - Write the Even numbers To a File (The Same Format, 2 Lines, accept now have 5 numbers per like) - STUCK!
Example:
Code:
6,8,10,12,14
16,18,20,22,24
As you can see, i am currently Stuck on step 3. Where i am stuck is that, Every time that it goes through the loop for the first 5, it saves the number in the txt file like it should. However when it goes through the loop for the 2nd time, it Overwrites the numbers that are currently there. If you can help me, i would Greatly Appriciate it.

PS. I am still trying to Learn Java, so if you think you have a solution, could you try not to confuse me :laugh:. Thanks!

Code:
import java.io.*;

public class Assignment10 {
	public static String GetString() {
		String line = " ";
		InputStreamReader input = new InputStreamReader (System.in);
		BufferedReader reader = new BufferedReader (input);
		try{
			line = reader.readLine();
		}catch(Exception e) { return line;}
		return line;
}
	public static void Output (String out) {
		System.out.println(out);
}
	public static void OutputSame (String out) {
		System.out.print(out);
}
	public static void ReadFile(String FileName, String content[],int num[]){
		try{
			FileReader inputfile = new FileReader(FileName);
			BufferedReader inFile = new BufferedReader(inputfile);
			String line = "";
				line = inFile.readLine();
				//content[counter] = line;
						int counter = 0;
				while(line !=null) {
					content[counter] = line;
					num[counter] = Integer.parseInt(content[counter]);
					line = inFile.readLine();
					counter = counter + 1;			
				}

			inFile.close();
		}
		catch(IOException e){
		}
} 
	public static void Write2File(String write){
			try{
				FileWriter WriteResult = new FileWriter("Assignment10Output.txt");
				PrintWriter ResultOutput = new PrintWriter(WriteResult,true);
				//print text to file
				ResultOutput.println(write);
		}
		catch(IOException e){
		}
		
}
	public static void InitializeArray(String content[]){
  		for(int counter = 0; counter < 100; counter++) {
    		content[counter] = null;
  		}
		
}
	public static void main (String args[]){
    String content[];
    int num[];
    int OutputArray[];
    content = new String[100];
    num = new int[100];
    OutputArray = new int[100];
    InitializeArray(content);
    ReadFile("Assignment10Input.txt",content,num);
    Output ("*****************");
   // For Testing Only - Outputs the the text that has been pulled from Assignment10Input.txt.
    	for(int counter = 0; content[counter] != null; counter++) {
     		Output(num[counter] + "");
    }
    int start = num[0];
    int end = num[1];
    int x = num[0];
    int counter = 0;
    Output ("*****************");
	while(start<end + 1){
			if(x % 2 == 0){
				Output(x + " - Even");
				OutputArray[counter] = x;
				counter = counter + 1;
			}else if(x % 2 == 1){
				//Output(x + " - Odd");
			}else{}
			start = start + 1;
			x=x+1;
 		 }
    Output ("*****************");
	//			for(int i=1;i<counter;i=i+1){
	//				Output (OutputArray[i] + "");
	//			}
    //Output ("*****************");
    int counter2 = 0;
    while(counter2 < end + 1){
    	if(counter2 < 5){
     		Write2File(OutputArray[counter2] + "-");
     		counter2 = counter2 + 1;
     		
    	}else if(counter2 > 5 && counter <= 10){
    	     		Write2File(OutputArray[(counter2 + 5)] + ",");
     				counter2 = counter2 + 1;
    	}else{
    		counter2 = counter2 + 1;
    	}
	
    }

	}
}
 
Not sure what your problem is 'exactly' but what you want to do is count o 5 and do a "\n:" while writing to the file. Just check if the number count is greater than and/or equal to 5 to add a "," (comma).

Oh and set filewriter(...,true) to append to the end of a file.

I would suggest you adding a toString that writes to the file so you can just print an object and you're done.
 
Well, I am unaware as to whether you're a student in a Java class, either as part of an AP subset or something along those lines, but seeing as you are probably trying to learn, you do have some bad coding habits, and you're passing arrays into methods and filling them into methods, which is a bad habit, and will not work for non static variables. (Your variables are static because of being in a static method).

Anyhow I provide you an example of what you have, except in a shorter neater way. It is simply as an example of how things can get easier, another approach to it.

Code:
import static java.lang.System.*; // allows me to just go out.println();
import java.io.*;
import java.util.ArrayList; // for ArrayLists, not super efficient but will work for this
import java.util.Scanner;

public class Assignment10 {
	
	public static String getString() {
		Scanner input = new Scanner(System.in);
		String line = "";
		
		line = input.nextLine();
		input.close();
		
		return line;
	}
	
	
	// This method will simply return an array containing integers and it can cause the FileNotFoundException
	public static ArrayList<Integer> readFile(String file) throws FileNotFoundException {
     	Scanner input = new Scanner(new File(file));
		ArrayList<Integer> ret = new ArrayList<Integer>();
		
		while(input.hasNext()) {
			ret.add(Integer.parseInt(input.nextLine()));			
		}
		input.close();
		return ret;
	}
	
	// I have rewritten your writing code into this method
	public static void writeToFile(ArrayList<Integer> ints) {
		/*
		 * To be implemented
		 */
	}
	
	public static void main(String args[]) {
		ArrayList<Integer> inputted = new ArrayList<Integer>();
		ArrayList<Integer> calculated = new ArrayList<Integer>();
		
		try {
			inputted = readFile("Assignment10Input.txt");
		} catch(FileNotFoundException e) {
			out.println("Error: File wasn't found");
			exit(0); // same as System.exit(0); due to static import
		}
		for(int number: inputted) 
			out.println(number);
		
		int start = inputted.get(0);
		int end = inputted.get(1);
		
		while(start<=end) {
			if(start % 2 == 0) {
				out.println(start + " - Even");
				calculated.add(start);
				start+=2; 	// now we now it is even, so if we just add two we will get the next even number
			} else
				start++; // simply add one as it is odd
		}
		
		writeToFile(calculated);
	}
    
    
}

Now onto printing them all to a file, I see you already have a PrintWriter setup, with your way of doing things, and if you were to do the same with mine it would look significantly different than yours, but here is what you need to do, and I'll try to explain it off of how your code looks.

You will need to create a counter variable like your counter2. Then, what you need to do is a simple check every time it is on the fifth number, which can be done somewhat like this:

if counter2 < 4
write the number to the file
if counter2 == 4
write the number to file, with a '\n' behind it
set counter2 to zero


This should correctly write it out into a file for you, the reason for 4, is if you start counter2 at zero, you will have 5 numbers once you hit 4:
0 1 2 3 4 = 5 numbers

Anymore questions feel free to ask them here, just keep in mind we don't necessarily like to do your homework for you, if that's the case.
 
Well, I am unaware as to whether you're a student in a Java class, either as part of an AP subset or something along those lines, but seeing as you are probably trying to learn, you do have some bad coding habits, and you're passing arrays into methods and filling them into methods, which is a bad habit, and will not work for non static variables. (Your variables are static because of being in a static method).

Anyhow I provide you an example of what you have, except in a shorter neater way. It is simply as an example of how things can get easier, another approach to it.

Code:
import static java.lang.System.*; // allows me to just go out.println();
import java.io.*;
import java.util.ArrayList; // for ArrayLists, not super efficient but will work for this
import java.util.Scanner;

public class Assignment10 {
	
	public static String getString() {
		Scanner input = new Scanner(System.in);
		String line = "";
		
		line = input.nextLine();
		input.close();
		
		return line;
	}
	
	
	// This method will simply return an array containing integers and it can cause the FileNotFoundException
	public static ArrayList<Integer> readFile(String file) throws FileNotFoundException {
     	Scanner input = new Scanner(new File(file));
		ArrayList<Integer> ret = new ArrayList<Integer>();
		
		while(input.hasNext()) {
			ret.add(Integer.parseInt(input.nextLine()));			
		}
		input.close();
		return ret;
	}
	
	// I have rewritten your writing code into this method
	public static void writeToFile(ArrayList<Integer> ints) {
		/*
		 * To be implemented
		 */
	}
	
	public static void main(String args[]) {
		ArrayList<Integer> inputted = new ArrayList<Integer>();
		ArrayList<Integer> calculated = new ArrayList<Integer>();
		
		try {
			inputted = readFile("Assignment10Input.txt");
		} catch(FileNotFoundException e) {
			out.println("Error: File wasn't found");
			exit(0); // same as System.exit(0); due to static import
		}
		for(int number: inputted) 
			out.println(number);
		
		int start = inputted.get(0);
		int end = inputted.get(1);
		
		while(start<=end) {
			if(start % 2 == 0) {
				out.println(start + " - Even");
				calculated.add(start);
				start+=2; 	// now we now it is even, so if we just add two we will get the next even number
			} else
				start++; // simply add one as it is odd
		}
		
		writeToFile(calculated);
	}
    
    
}

Now onto printing them all to a file, I see you already have a PrintWriter setup, with your way of doing things, and if you were to do the same with mine it would look significantly different than yours, but here is what you need to do, and I'll try to explain it off of how your code looks.

You will need to create a counter variable like your counter2. Then, what you need to do is a simple check every time it is on the fifth number, which can be done somewhat like this:

if counter2 < 4
write the number to the file
if counter2 == 4
write the number to file, with a '\n' behind it
set counter2 to zero


This should correctly write it out into a file for you, the reason for 4, is if you start counter2 at zero, you will have 5 numbers once you hit 4:
0 1 2 3 4 = 5 numbers

Anymore questions feel free to ask them here, just keep in mind we don't necessarily like to do your homework for you, if that's the case.

Thanks - I will try and wrap my Head around the code that you have just put forth. Also, to answer your Question, i am a Student (Grade 11) in a First year Coding Class. Most of what you said still does not make much sense, but i will try to work it out with you, everyone Here, Myself, and my Teacher if Necessary. Oh, and This is not really homework, i got an Assignment -> Assignment 10 -> And i went home sick for 2 Days; I was just given how to Input a file that Day, and i figured out, via forums and simply thinking, how to Export. And, usually we have Guidance and Others that help us when we are stuck, so im happy that i got that far on my Own.

Thanks Again!:laugh:
 
Back