Only outputting last line of loop - java

import java.io.*;
import java.util.Random;
public class LargeDataset {
public static void main(String[] args) throws Exception {
File file = new File("src/Salary.txt");
if (file.exists()) {
System.out.print("Sorry this file already exists.");
System.exit(0);
}
String firstName = "";
String lastName = "";
String rank = "";
double salaryRange = 0.0;
for (int i = 1; i <= 1000; i++) {
try (PrintWriter output = new PrintWriter(file))
{
firstName = "FirstName" + i;
lastName = "LastName" + i;
rank = generateRandomRank();
if (rank == "assistant")
salaryRange = generateSalary(50000.00, 80000.00);
else if (rank == "associate")
salaryRange = generateSalary(60000.00, 110000.00);
else
salaryRange = generateSalary(75000.00, 130000.00);
output.printf("%s %s %s $%.2f", firstName, lastName, rank, salaryRange);
output.println();
}
}
}
public static String generateRandomRank() {
String[] rank = {"assistant", "associate", "full"};
Random random1 = new Random();
return rank[random1.nextInt(3)];
}
public static double generateSalary(double minSalary, double maxSalary) {
double randomSalary = minSalary + Math.random() * (maxSalary - minSalary);
return randomSalary;
}
}
Hi everyone. I have a program that generates 1000 lines of text and saves it into a file named Salary. The format of each line is: firstNamei, lastNamei, a random rank, and a random salary that is suited to the rank. However when I run this program it only outputs the 1000th line of the loop. I noticed however, when I don't put the PrintWriter in the try statement and close it after the loop by myself, it runs fine and generates all 1000 lines. Why is it only generating the last line based on how it is right now though?

You should open your PrintWriter once, and then write to it many times from your loop, not the other way around:
try (PrintWriter output = new PrintWriter(file)) {
for (int i = 1; i <= 1000; i++) {
firstName = "FirstName" + i;
lastName = "LastName" + i;
rank = generateRandomRank();
if (rank == "assistant")
salaryRange = generateSalary(50000.00, 80000.00);
else if (rank == "associate")
salaryRange = generateSalary(60000.00, 110000.00);
else
salaryRange = generateSalary(75000.00, 130000.00);
output.printf("%s %s %s $%.2f", firstName, lastName, rank, salaryRange);
output.println();
}
}
You should use the above pattern instead of what you have. If you want an exact fix to your current code, then you may try opening the PrintWriter in append mode:
for (int i=1; i <= 1000; i++) {
try (PrintWriter output = new PrintWriter(new FileOutputStream(file, true)) {
// same logic
}
}
This should also work, because now, even though you create a new PrintWriter for each iteration of the loop (inefficient), you open the underlying file in append mode, so each new line should get written properly.

Every time that you are iterating through your 1000 you are creating a new file
for (int i = 1; i <= 1000; i++) {
try (PrintWriter output = new PrintWriter(file))
...
}
move it before the loop
try (PrintWriter output = new PrintWriter(file)) {
for (int i = 1; i <= 1000; i++) {
}
}

Related

Set boolean to true, but filewriter still overwrites the file, any advice?

I have created a simple program that sorts integers in an input file using different algorithms. I also use filewriter to output results to another file. Unfortunately no matter how I change my code, file gets overridden. Any advice?
Been searching for answer on google and tried changing the way I input the syntax but nothing works.
important bits:
setting the writer up
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
outputting to the file
out.println("User's own data set sorted using bubble sort.");
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println("Sorted Array looks like this:" + Arrays.toString(intArrayBubble));
out.println(timeToSort + bubbleSortIs + bubbleTime + "ms");
it works fine, however its used in a do while loop, with nested if statements, and each one overrides the other.
Rest of code in case its required - UPDATED - still not working
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class PDD_Sorting {
public static void main (String [] pArgs)
{
//Array for a file
String[] FileOne;
FileOne = new String[0];
int optionOne = 1,
optionTwo = 2,
optionThree = 3,
secondaryOptionOne = 1,
secondaryOptionTwo = 2,
secondaryOptionThree = 3,
userSelection,
subUserSelection;
String unsortedArray = "Unsorted array is: ",
bubbleSort = "Sorted array using bubble sort: ",
selectionSort = "Sorted array using selection sort: ",
insertionSort = "Sorted array using insertion sort: ",
timeToSort = "Time needed to sort this array using ",
bubbleSortIs = "bubble sort is ",
selectionSortIs = "selection sort is ",
insertionSortIs = "insertion sort is ",
welcomeToSorter = "Welcome to the SORTER - program that can sort your txt files containing integeres in an ascending order!",
notFiles = "Integers, not files :)",
pleaseSelect = "Please select one of the following options, by enetering a number asociated with it.",
optionOneUserInput = "1. Sort your own data set - input your own set of data (integers, separated by colons, no spaces) into the Input file.",
optionTwoPredefined = "2. Use predetermind set of data to test the algorythms.",
optionThreeExit = "3. Exit the program.",
subMenuPleaseSelect = "Please select which algorythm would you like to use to sort this file.",
optionBubble = "(1) - Bubble Sort.",
optionSelection = "(2) - Selection Sort.",
optionInsertion = "(3) - Insertion Sort.",
usersDataBubble = "User's own data set sorted using bubble sort.",
sortedArrayLooks = "Sorted Array looks like this:",
msTime = "ms",
usersDataSelection = "User's own data set sorted using selection sort.",
usersDataInsertion = "User's own data set sorted using insertion sort.",
validOption = "Please enter a valid option i.e. 1,2 or 3",
lessThanZero = "If time shown in ms is 0, that means the time needed to conduct the sort is shorter than 1ms.",
fileCreated = "File created.",
terminatingProgram = "Terminating the program.",
unableToWriteFile = "Unable to write to file";
System.out.println(welcomeToSorter);
System.out.println(notFiles);
Scanner tInput = new Scanner (System.in);
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
System.out.println(pleaseSelect);
System.out.println(optionOneUserInput);
System.out.println(optionTwoPredefined);
System.out.println(optionThreeExit);
// Scanner tInput = new Scanner (System.in);
userSelection = tInput.nextInt();
if (userSelection == optionOne) {
//System.out.println("Please enter a valid path for your file.");
String[] splitFile = null;
//String userFile = tInput.next();
FileOne = getAndPrepareFile(splitFile);
System.out.println(subMenuPleaseSelect);
System.out.println(optionBubble);
System.out.println(optionSelection);
System.out.println(optionInsertion);
subUserSelection = tInput.nextInt();
if (subUserSelection == secondaryOptionOne) {
int size = FileOne.length;
int [] intArrayBubble = new int [size];
for(int i=0; i<size; i++) {
intArrayBubble[i] = Integer.parseInt(FileOne[i]);
}
bubbleSort(intArrayBubble);
long bubbleTime = timeCount(intArrayBubble);
out.println(usersDataBubble);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArrayBubble));
out.println(timeToSort + bubbleSortIs + bubbleTime + msTime);
}
else if (subUserSelection == secondaryOptionTwo) {
int size2 = FileOne.length;
int [] intArraySelection = new int [size2];
for(int i=0; i<size2; i++) {
intArraySelection[i] = Integer.parseInt(FileOne[i]);
}
doSelectionSort(intArraySelection);
long selectionTime = timeCount(intArraySelection);
out.println(usersDataSelection);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArraySelection));
out.println(timeToSort + selectionSortIs + selectionTime + msTime);
}
else if (subUserSelection == secondaryOptionThree) {
int size3 = FileOne.length;
int [] intArrayInsertion = new int [size3];
for(int i=0; i<size3; i++) {
intArrayInsertion[i] = Integer.parseInt(FileOne[i]);
}
doInsertionSort(intArrayInsertion);
long insertionTime = timeCount(intArrayInsertion);
out.println(usersDataInsertion);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArrayInsertion));
out.println(timeToSort + insertionSortIs + insertionTime + msTime);
}
else {
System.out.println(validOption);
tInput.next();
}
}
else if (userSelection == optionTwo){
//file being prepared and loaded via function
String[] splitFilePredefined = null;
FileOne = getAndPrepareFilePredefined(splitFilePredefined);
//converting string array into int array so the method can sort it.
int size = FileOne.length;
int [] intArrayBubble = new int [size];
for(int i=0; i<size; i++) {
intArrayBubble[i] = Integer.parseInt(FileOne[i]);
}
int size2 = FileOne.length;
int [] intArraySelection = new int [size2];
for(int i=0; i<size2; i++) {
intArraySelection[i] = Integer.parseInt(FileOne[i]);
}
int size3 = FileOne.length;
int [] intArrayInsertion = new int [size3];
for(int i=0; i<size3; i++) {
intArrayInsertion[i] = Integer.parseInt(FileOne[i]);
}
//inserting pre-prepared int arrays into variables including a timecount method
int bubbleTime = timeCount(intArrayBubble);
int selectionTime = timeCount(intArraySelection);
int insertionTime = timeCount(intArrayInsertion);
//sorting array using various sorts
bubbleSort(intArrayBubble);
doSelectionSort(intArraySelection);
doInsertionSort(intArrayInsertion);
//out.println("Sorted arrray using insertion sort looks like this: " + Arrays.toString(intArrayInsertion));
out.println(timeToSort + bubbleSortIs + bubbleTime + "ms");
out.println(timeToSort + selectionSortIs + selectionTime + "ms");
out.println(timeToSort + insertionSortIs + insertionTime + "ms");
out.println(lessThanZero);
System.out.println(fileCreated);
}
else if (userSelection == optionThree){
System.out.println(terminatingProgram);
System.exit(0);
}
else {
System.out.println(validOption);
tInput.next();
}
out.flush();
out.close();
//tInput.close();
}while (userSelection != optionThree);
}
catch (Exception e)
{
System.out.println(unableToWriteFile);
tInput.next();
}
tInput.close();
}//end main
//method that fetches the file from predefined, hardcoded location and removes comas, esentially prepares the file for the next phase
private static String[] getAndPrepareFile (String[] splitFile)
{
Scanner fileIn = null;
try
{
fileIn = new Scanner(new FileInputStream("C:\\Users\\Greg\\Documents\\Programming\\PDD - Assignment 1\\Input.txt"));
String fileNew = fileIn.next();
splitFile = fileNew.split(",");
//System.err.println(Arrays.toString(splitFile)); //Arrays.toString needed to print the array correctly, otherwise it prints the address of the object
fileIn.close();
}
catch (IOException e)
{
System.out.println("File not found.");
//System.exit(0);
}
return splitFile;
}
//as above but works for predefined file, that can be generated using randomNumber.java program
private static String[] getAndPrepareFilePredefined (String[] splitFilePredefined)
{
Scanner fileIn = null;
try
{
fileIn = new Scanner(new FileInputStream("C:\\Users\\Greg\\Documents\\Programming\\PDD - Assignment 1\\Generated input.txt"));
String fileNew = fileIn.next();
splitFilePredefined = fileNew.split(",");
//System.err.println(Arrays.toString(splitFile)); //Arrays.toString needed to print the array correctly, otherwise it prints the address of the object
fileIn.close();
}
catch (IOException e)
{
System.out.println("File not found.");
//System.exit(0);
}
return splitFilePredefined;
}
//method used to sort a file using bubble sort
private static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
//method used to sort a file using selection sort
private static int[] doSelectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
//method used to sort a file using sinsertion sort
private static int[] doInsertionSort(int[] input){
int temp;
for (int i = 1; i < input.length; i++) {
for(int j = i ; j > 0 ; j--){
if(input[j] < input[j-1]){
temp = input[j];
input[j] = input[j-1];
input[j-1] = temp;
}
}
}
return input;
}
//method used to calculate how much time has lapsed while using any of the given sort methods, outputs in ms, if less than 1 ms, outputs 0ms
private static int timeCount (int[] anArray)
{
long start = System.nanoTime();
Arrays.sort(anArray);
long end = System.nanoTime();
long timeInMillis = TimeUnit.MILLISECONDS.convert(end - start, TimeUnit.NANOSECONDS);
//System.out.println("Time spend in ms: " + timeInMillis);
return (int) timeInMillis;
}
}//end class
File gets constantly overridden, how do i stop this and make it add to file instead?
You don't need the first FileWriter fileWriter = new FileWriter("Sorted output.txt");; this is actually creating/overwriting the file, after which your PrintWriter opens it again for appending.
So, just change
// ... omitting beginning
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
// ... omitting rest
to
// ... omitting beginning
try {
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
// ... omitting rest
Move out.close() outside the loop
else {
System.out.println("Please enter a valid option i.e. 1,2 or 3");
tInput.next();
}
out.flush();
/* THIS -> out.close(); <- THIS */
//tInput.close();
}while (userSelection != optionThree);
out.close();
}
I tried your code and your problem is not that the file is being overwritten, but that you are closing the outputstream in the first iteration.

FileIO to .csv files

So I'm working on a project for school. I need to record the data from my arrays into Excel and I'm having some trouble. This is part of my experiment class.
public static void exp(Params params) {
Scanner s = new Scanner(System.in);
String temp;
for (temp = ""; temp.isEmpty(); temp = s.nextLine()) {
System.out.println("Enter a directory and filename that you want the results to be saved under.");
System.out.println("(If no directory is specified, results will be in same folder as the jar.)");
}
params.setFileName(temp);
s.close();
System.out.println("Executing...");
long timeArray[] = new long[params.getFinalSize() / params.getIncrement()];
int counter = 0;
SortFacade facade = new SortFacade();
for (int n = params.getInitialSize(); n <= params.getFinalSize(); n += params.getIncrement()) {
System.out.println((new StringBuilder("Array of size: ")).append(n).toString());
long tempTime = 0L;
for (int j = 0; j < params.getNumTrials(); j++) {
System.out.println((new StringBuilder("Trial #")).append(j + 1).toString());
params.generateArrays(n, params.getTypeList());
tempTime += facade.sort(params);
}
timeArray[counter] = tempTime / (long) params.getNumTrials();
counter++;
}
params.setTimeArray(timeArray);
System.out.println("Times for each array size(ms): " + Arrays.toString(timeArray));
System.out.println("Writing to File...");
System.out.println("Complete.");
}
}
Start with Filewriter
Make sure what you write is comma-delimeted and saved as a .csv
Also, take a look at this existing question.

String index out of Bounds Exception error

I am making a program to read .java files and extract all comments from it and write it to an html file. The file works mostly but i am having trouble extracting the names of each method as it confuses "Exception{" as a separate class/method.
So far this is the code i have and i believe it is almost done.
http://pastebin.com/qrbJAaW3
public class ParseDoc {
static String fileName = null;
static String outputR = "";
static String inputR = "";
static String[] lines;
static String [] classnames;
static StringBuilder classn = new StringBuilder();
static String classnam = "";
/**
* This Method asks the user for path to input and output file
* then it reads the file and places it on a string for easier sorting.
* The string is sorted line by line into an array and cleaned.
* #return Array of DOC comments
* #throws Exception
*/
public static String[] scanread() throws Exception{
System.out.println("NOTICE: If a valid file path is not entered, the program will not return a DOCHTML document.");
Scanner inputReader = new Scanner(System.in);
System.out.println("Please enter path to input file (ex: C:/Program Files/Code.java : " );
inputR = inputReader.nextLine();
System.out.println("Please enter path to html output file (ex: C:/Program Files/Output.html : " );
outputR = inputReader.nextLine();
inputReader.close();
FileReader file = new FileReader(inputR);
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
//NAME OF THE SOURCE FILE
int index = inputR.lastIndexOf("/");
fileName = inputR.substring(index + 1);
int z = 0;
//This loop turns the input file into an String for easier access
while (line!= null){
line = reader.readLine();
z += 1;
}
reader.close();
file.close();
FileReader file2 = new FileReader(inputR);
BufferedReader reader2 = new BufferedReader(file2);
String line2 = reader2.readLine();
lines = new String[z];
int j = 0;
while(line2 != null)
{
line2 = line2.trim();
lines[j] = line2;
line2 = reader2.readLine();
j += 1;
}
reader2.close();
file2.close();
return lines;
}
/**
* Removes all the comments from the Array containing strings
* #param lines contains strings made of input file
* #return Array with removed strings
*/
public static String[] removeComments(String[] lines){
for (int i=0; i <lines.length;i++){
if (lines[i].startsWith("//"))
{
lines[i]="";
}
}
return lines;
}
/**
* This method scans the entire code for name of the classes and methods
* along with their parameters and stores them in an Array for further use
* #param lines
* #return lines array without changing any content
*/
public static String[] classNames(String[] lines)
{
int total = 0;
String[] matches = new String[] {"public ", "class ","private "};
for(int b = 0; b <lines.length;b++)
{
Matcher num = Pattern.compile("\\S+\\s*\\(([^)]*)\\)").matcher(lines[b]);
for (int n = 0; n < 3 ;n++)
{
if (lines[b].contains(matches[n]))
{
while(num.find())
{
total += 1;
}
}
}
}
classnames = new String[total];
for(int z = 0; z<lines.length;z++)
{
Matcher mzz = Pattern.compile("\\w+\\s*\\{").matcher(lines[z]);
for (int k = 0; k < 3; k++)
{
if (lines[z].contains(matches[k])&& !(lines[z].contains("throws "))) //&& !(lines[z].contains("throws "))
{
while(mzz.find())
{
classn.append( mzz.group()+"break");
}
}
}
}
for(int z = 0; z <lines.length;z++)
{
//This matcher with Regex looks for class/method names along with any parameters inside
Matcher m = Pattern.compile("\\S+\\s*\\(([^)]*)\\)").matcher(lines[z]);
int i = 0;
for (int k = 0; k < 3; k++)
{
if (lines[z].contains(matches[k]) )
{
while(m.find())
{
classn.append( m.group()+"break");
continue;
}
}
}
}
classnam = classn.toString();
classnames = classnam.split("break");
/*for(int step = 0; step<classnames.length;step++)
{
System.out.println(classnames[step]);
}*/
return lines;
}
/**
* This method removes all the code from the Array and leaves on the
* Doc comments intact.
* #param lines
* #return lines array with only comments remaining ( code is removed )
*/
public static String[] removeCode(String[] lines)
{
int rep = 0;
while ( rep <lines.length){
lines[rep] = lines[rep].replaceAll("\\*", "Z");
if(!(lines[rep].startsWith("Z") || (lines[rep].startsWith("/")))){
lines[rep]="";
}
lines[rep] = lines[rep].replaceAll("Z", "\\*");
rep += 1;
}
for(int num = 0; num <lines.length; num++)
{
if(lines[num].isEmpty()){
lines[num] = null;
}
}
return lines;
}
/**
* This method removes the remaining stars, slashes and properly formats each comment
* before printing it.
* #param lines The array contains parsed Java Doc comments
* #return
* #throws Exception
*/
public static String[] writeTo(String[] lines) throws Exception
{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(outputR));
StringBuilder writeTo = new StringBuilder();
writeTo.append("<html>\n<body>\n<h2><mark> JAVA DOC COMMENTS</mark> </h2>\n<pre>\n"
+"<big><b>Source File:</b> </big>" +"<big>"+ fileName+"</big>" + "\n\n");
for(int step = 0; step<lines.length;step++)
{
if(!(lines[step] == null))
{
lines[step] = lines[step].replace("#author", "<b>Author: </b>\n&nbsp&nbsp&nbsp");
lines[step] = lines[step].replace("#since", "<b>Since: </b>\n&nbsp&nbsp&nbsp");
lines[step] = lines[step].replace("#version", "<b>Version: </b>\n&nbsp&nbsp&nbsp");
lines[step] = lines[step].replace("#param", "<b>Parameter: </b>\n&nbsp&nbsp&nbsp");
lines[step] = lines[step].replace("#return", "<b>Return: </b>\n&nbsp&nbsp&nbsp");
//lines[step] = lines[step].replace("*", "");
}
}
outputWriter.write(writeTo.toString());
//write to HTML
int countz = 0;
int comcount = 0;
//classnames[]
for(int resum = 0; resum<lines.length;resum++)
{
if(lines[resum] != null)
{
if( lines[resum].charAt(0) == '*' )
{
lines[resum] = lines[resum].replace("*","");
}
}
}
for(int i = 0; i < classnames.length; i++)
{
System.out.println(classnames[i]);
}
for(int resum = 0; resum<lines.length;resum++)
{
if(lines[resum] != null)
{
if( lines[resum].charAt(0) == '/' )
{
if(lines[resum].endsWith("*"))
{
lines[resum] = lines[resum].replace("/**","<b>"+classnames[countz]+"</b>");
countz++;
}
}
if( lines[resum].charAt(0) == '/' )
{
lines[resum] = lines[resum].replace("/","\n");
}
}
}
/*for(int resum = 0; resum<lines.length;resum++)
{
}*/
for(int f = 0; f<lines.length;f++)
{
if(lines[f] != null)
{
/*if(lines[f].startsWith("//") && lines[f].length() == 2)
{
lines[f] = "TEEEST";
countz++;
}*/
outputWriter.write(lines[f]+"\n");
}
}
outputWriter.close();
return null;
}
}
Console:
Please enter path to input file (ex: C:/Program Files/Code.java :
I:\ICS4U0\DocParse\src\java_doc_parse\ParseDoc.java
Please enter path to html output file (ex: C:/Program Files/Output.html :
I:\ICS4U0\DocParse\src\java_doc_parse\ParseDochh.html
ParseDoc {
scanread()
removeComments(String[] lines)
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at java_doc_parse.ParseDoc.writeTo(ParseDoc.java:285)
at java_doc_parse.Execute.main(Execute.java:14)
classNames(String[] lines)
removeCode(String[] lines)
writeTo(String[] lines)
I am not sure what is causing this error. Is there a way to fix it or should i just give up on adding class names to comments altogether?
Sorry if i am lacking some information, but i am quite confused myself.
The error seems to be because you call charAt(0) on what appears to be an empty string.
You already have a null check above, I don't know if it's valid (can your lines ever be null?), but I would change that to a length check, possibly combined with the existing null check.
if (lines[resum] != null && lines[resum].length > 0) {
I think this is where your error resides:
for(int resum = 0; resum<lines.length;resum++)
{
if(lines[resum] != null)
{
if( lines[resum].charAt(0) == '/' )
{
if(lines[resum].endsWith("*"))
{
lines[resum] = lines[resum].replace("/**","<b>"+classnames[countz]+"</b>");
countz++;
}
}
if( lines[resum].charAt(0) == '/' )
{
lines[resum] = lines[resum].replace("/","\n");
}
}
}
Try this instead, move the null check before entering the for loop:
if(lines[0] != null)
{
for(int resum = 0; resum<lines.length;resum++)
{
if( lines[resum].charAt(0) == '/' )
{
if(lines[resum].endsWith("*"))
{
lines[resum] = lines[resum].replace("/**","<b>"+classnames[countz]+"</b>");
countz++;
}
}
if( lines[resum].charAt(0) == '/' )
{
lines[resum] = lines[resum].replace("/","\n");
}
}
}

The program throws NullPointerException [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Not sure why it gives me the NullPointerException. Please help.
I am pretty sure all the arrays are full, and i restricted all the loops not to go passed empty spaces.
import java.util.;
import java.io.;
public class TextAnalysis {
public static void main (String [] args) throws IOException {
String fileName = args[0];
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int MAX_WORDS = 10000;
String[] words = new String[MAX_WORDS];
int unique = 0;
System.out.println("TEXT FILE STATISTICS");
System.out.println("--------------------");
System.out.println("Length of the longest word: " + longestWord(fileScanner));
read(words, fileName);
System.out.println("Number of words in file wordlist: " + wordList(words));
System.out.println("Number of words in file: " + countWords(fileName) + "\n");
System.out.println("Word-frequency statistics");
lengthFrequency(words);
System.out.println();
System.out.println("Wordlist dump:");
wordFrequency(words,fileName);
}
public static void wordFrequency(String[] words, String fileName) throws IOException{
File file = new File(fileName);
Scanner s = new Scanner(file);
int [] array = new int [words.length];
while(s.hasNext()) {
String w = s.next();
if(w!=null){
for(int i = 0; i < words.length; i++){
if(w.equals(words[i])){
array[i]++;
}
}
for(int i = 0; i < words.length; i++){
System.out.println(words[i] + ":" + array[i]);
}
}
}
}
public static void lengthFrequency (String [] words) {
int [] lengthTimes = new int[10];
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(w!=null){
if(w.length() >= 10) {
lengthTimes[9]++;
} else {
lengthTimes[w.length()-1]++;
}
}
}
for(int j = 0; j < 10; j++) {
System.out.println("Word-length " + (j+1) + ": " + lengthTimes[j]);
}
}
public static String longestWord (Scanner s) {
String longest = "";
while (s.hasNext()) {
String word = s.next();
if (word.length() > longest.length()) {
longest = word;
}
}
return (longest.length() + " " + "(\"" + longest + "\")");
}
public static int countWords (String fileName) throws IOException {
File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
int count = 0;
while(fileScanner.hasNext()) {
String word = fileScanner.next();
count++;
}
return count;
}
public static void read(String[] words, String fileName) throws IOException{
File file = new File(fileName);
Scanner s = new Scanner(file);
while (s.hasNext()) {
String word = s.next();
int i;
for ( i=0; i < words.length && words[i] != null; i++ ) {
words[i]=words[i].toLowerCase();
if (words[i].equals(word)) {
break;
}
}
words[i] = word;
}
}
public static int wordList(String[] words) {
int count = 0;
while (words[count] != null) {
count++;
}
return count;
}
}
There are two problems with this code
1.You didn't do null check,although the array contains null values
2.Your array index from 0-8,if you wan't to get element at 9th index it will throw ArrayIndexOutOfBound Exception.
Your code should be like that
public static void lengthFrequency (String [] words) {
int [] lengthTimes = new int [9];
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(null!=w) //This one added for null check
{
/* if(w.length() >= 10) {
lengthTimes[9]++;
} else {
lengthTimes[w.length()-1]++;
}
}*/
//Don't need to check like that ...u can do like below
for(int i = 0; i < words.length; i++) {
String w = words[i];
if(null!=w)
{
lengthTimes[i] =w.length();
}
}
}
//here we should traverse upto length of the array.
for(int i = 0; i < lengthTimes.length; i++) {
System.out.println("Word-length " + (i+1) + ": " + lengthTimes[i]);
}
}
Your String Array String[] words = new String[MAX_WORDS]; is not initialized,you are just declaring it.All its content is null,calling length method in line 31 will give you null pointer exception.
`
Simple mistake. When you declare an array, it is from size 0 to n-1. This array only has indexes from 0 to 8.
int [] lengthTimes = new int [9];
//some code here
lengthTimes[9]++; // <- this is an error (this is line 29)
for(int i = 0; i < 10; i++) {
System.out.println("Word-length " + (i+1) + ": " + lengthTimes[i]); // <- same error when i is 9. This is line 37
When you declare:
String[] words = new String[MAX_WORDS];
You're creating an array with MAX_WORDS of nulls, if your input file don't fill them all, you'll get a NullPointerException at what I think is line 37 in your original file:
if(w.length() >= 10) { // if w is null this would throw Npe
To fix it you may use a List instead:
List<String> words = new ArrayList<String>();
...
words.add( aWord );
Or perhaps you can use a Set if you don't want to have repeated words.

Java File I/O help

I have a problem with my code. I need to do several operations on a log file with this structure:
190.12.1.100 2011-03-02 12:12 test.html
190.12.1.100 2011-03-03 13:18 data.html
128.33.100.1 2011-03-03 15:25 test.html
128.33.100.1 2011-03-04 18:30 info.html
I need to get the number of visits per month, number of visits per page and number of unique visitors based on the IP. That is not the question, I managed to get all three operations working. The problem is, only the first choice runs correctly while the other choices just return values of 0 afterwards, as if the file is empty, so i am guessing i made a mistake with the I/O somewhere. Here's the code:
import java.io.*;
import java.util.*;
public class WebServerAnalyzer {
private Map<String, Integer> hm1;
private Map<String, Integer> hm2;
private int[] months;
private Scanner input;
public WebServerAnalyzer() throws IOException {
hm1 = new HashMap<String, Integer>();
hm2 = new HashMap<String, Integer>();
months = new int[12];
for (int i = 0; i < 12; i++) {
months[i] = 0;
}
File file = new File("webserver.log");
try {
input = new Scanner(file);
} catch (FileNotFoundException fne) {
input = null;
}
}
public String nextLine() {
String line = null;
if (input != null && input.hasNextLine()) {
line = input.nextLine();
}
return line;
}
public int getMonth(String line) {
StringTokenizer tok = new StringTokenizer(line);
if (tok.countTokens() == 4) {
String ip = tok.nextToken();
String date = tok.nextToken();
String hour = tok.nextToken();
String page = tok.nextToken();
StringTokenizer dtok = new StringTokenizer(date, "-");
if (dtok.countTokens() == 3) {
String year = dtok.nextToken();
String month = dtok.nextToken();
String day = dtok.nextToken();
int m = Integer.parseInt(month);
return m;
}
}
return -1;
}
public String getIP(String line) {
StringTokenizer tok = new StringTokenizer(line);
if (tok.countTokens() == 4) {
String ip = tok.nextToken();
String date = tok.nextToken();
String hour = tok.nextToken();
String page = tok.nextToken();
StringTokenizer dtok = new StringTokenizer(date, "-");
return ip;
}
return null;
}
public String getPage(String line) {
StringTokenizer tok = new StringTokenizer(line);
if (tok.countTokens() == 4) {
String ip = tok.nextToken();
String date = tok.nextToken();
String hour = tok.nextToken();
String page = tok.nextToken();
StringTokenizer dtok = new StringTokenizer(date, "-");
return page;
}
return null;
}
public void visitsPerMonth() {
String line = null;
do {
line = nextLine();
if (line != null) {
int m = getMonth(line);
if (m != -1) {
months[m - 1]++;
}
}
} while (line != null);
// Print the result
String[] monthName = {"JAN ", "FEB ", "MAR ",
"APR ", "MAY ", "JUN ", "JUL ", "AUG ", "SEP ",
"OCT ", "NOV ", "DEC "};
for (int i = 0; i < 12; i++) {
System.out.println(monthName[i] + months[i]);
}
}
public int count() throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream("webserver.log"));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
while ((readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n')
++count;
}
}
return count;
} finally {
is.close();
}
}
public void UniqueIP() throws IOException{
String line = null;
for (int x = 0; x <count(); x++){
line = nextLine();
if (line != null) {
if(hm1.containsKey(getIP(line)) == false) {
hm1.put(getIP(line), 1);
} else {
hm1.put(getIP(line), hm1.get(getIP(line)) +1 );
}
}
}
Set set = hm1.entrySet();
Iterator i = set.iterator();
System.out.println("\nNumber of unique visitors: " + hm1.size());
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + " - ");
System.out.println(me.getValue() + " visits");
}
}
public void pageVisits() throws IOException{
String line = null;
for (int x = 0; x <count(); x++){
line = nextLine();
if (line != null) {
if(hm2.containsKey(getPage(line)) == false)
hm2.put(getPage(line), 1);
else
hm2.put(getPage(line), hm2.get(getPage(line)) +1 );
}
}
Set set = hm2.entrySet();
Iterator i = set.iterator();
System.out.println("\nNumber of pages visited: " + hm2.size());
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + " - ");
System.out.println(me.getValue() + " visits");
}
}
Any help figuring out the problem would be much appreciated as I am quite stuck.
I didn't read the code thoroughly yet, but I guess you're not setting the read position back to the beginning of the file when you start a new operation. Thus nextLine() would return null.
You should create a new Scanner for each operation and close it afterwards. AFAIK scanner doesn't provide a method to go back to the first byte.
Currently I could also think of 3 alternatives:
Use a BufferedReader and call reset() for each new operation. This should cause the reader to go back to byte 0 provided you didn't call mark() somewhere.
Read the file contents once and iterate over the lines in memory, i.e. put all lines into a List<String> and then start at each line.
Read the file once, parse each line and construct an apropriate data structure that contains the data you need. For example, you could use a TreeMap<Date, Map<Page, Map<IPAdress, List<Visit>>>>, i.e. you'd store the visits per ip address per page for each date. You could then select the appropriate submaps by date, page and ip address.
The reset method of BufferedReader that Thomas recommended would only work if the file size is smaller than the buffer size or if you called mark with a large enough read ahead limit.
I would recommend reading throught the file once and to update your maps and month array for each line. BTW, you don't need a Scanner just to read lines, BufferedReader has a readLine method itself.
BufferedReader br = ...;
String line;
while (null != (line = br.readLine())) {
String ip = getIP(line);
String page = getPage(line);
int month = getMonth(line);
// update hashmaps and arrays
}

Categories

Resources