need help with writing to and receiving from the text files
it seems to go almost all the way but then it says that no file exists, at that point it should create one and then start writing to it. it says that it failed to find one and then it just ends itself. I don't know why
package sorting;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
public class Sorting {
private static int[] oneToFiftyThou = new int[50000];
private static int[] fiftyThouToOne = new int[50000];
private static int[] randomFiftyThou = new int[50000];
public static void main(String[] args) {
if(args.length>0) {
if(args[0].equalsIgnoreCase("init")) {
// initialize the 3 files
// 1-50000 file1
// 50000-1 file2
// random 50000 file3
initializeFiles();
writeFiles();
}
} else {
readFilestoArray();
System.out.println(""+oneToFiftyThou[0] + " - " +
oneToFiftyThou[oneToFiftyThou.length-1]);
System.out.println(""+fiftyThouToOne[0] + " - " +
fiftyThouToOne[fiftyThouToOne.length-1]);
System.out.println(""+randomFiftyThou[0] + " - " +
randomFiftyThou[randomFiftyThou.length-1]);
intInsertionSort(oneToFiftyThou);
intInsertionSort(fiftyThouToOne);
intInsertionSort(randomFiftyThou);
}
}
private static void initializeFiles() {
//Array one
for(int i=1; i<oneToFiftyThou.length+1; i++) {
oneToFiftyThou[i-1] = i;
}
//Array two
for(int i=50000; i>0; i--) {
fiftyThouToOne[fiftyThouToOne.length-(i)] = i;
}
//Array Three Random. Copy Array one into a new Array and shuffle.
System.arraycopy(oneToFiftyThou, 0, randomFiftyThou, 0,
randomFiftyThou.length);
Random random = new Random();
for(int i=randomFiftyThou.length-1; i>0; i--) {
int index = random.nextInt(i+1);
//Swap the values
int value = randomFiftyThou[index];
randomFiftyThou[index] = randomFiftyThou[i];
randomFiftyThou[i] = value;
}
}
public static void writeFiles() {
ArrayList<int[]> arrayList = new ArrayList<int[]>();
arrayList.add(oneToFiftyThou);
arrayList.add(fiftyThouToOne);
arrayList.add(randomFiftyThou);
int fileIter = 1;
for(Iterator<int[]> iter = arrayList.iterator();
iter.hasNext(); ) {
int[] array = iter.next();
try {
File file = new File("file"+fileIter+".txt");
//check for file, create it if it doesn't exist
if(!file.exists()) {
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferWriter = new BufferedWriter
(fileWriter);
for(int i = 0; i<array.length; i++) {
bufferWriter.write(""+array[i]);
if(i!=array.length-1) {
bufferWriter.newLine();
}
}
bufferWriter.close();
fileIter++;
}catch(IOException ioe) {
ioe.printStackTrace();
System.exit(-1);
}
}
}
public static void readFilestoArray() {
ArrayList<int[]> arrayList = new ArrayList<int[]>();
arrayList.add(oneToFiftyThou);
arrayList.add(fiftyThouToOne);
arrayList.add(randomFiftyThou);
int fileIter = 1;
for(Iterator<int[]> iter = arrayList.iterator();
iter.hasNext(); ) {
int[] array = iter.next();
try {
File file = new File("file"+fileIter+".txt");
//check for file, exit with error if file doesn't exist
if(!file.exists()) {
System.out.println("file doesn't exist "
+ file.getName());
System.exit(-1);
}
FileReader fileReader = new FileReader(file);
BufferedReader bufferReader = new BufferedReader
(fileReader);
for(int i = 0; i<array.length; i++) {
array[i] = Integer.parseInt
(bufferReader.readLine());
}
bufferReader.close();
fileIter++;
}catch(IOException ioe) {
ioe.printStackTrace();
System.exit(-1);
}
}
}
private static void intInsertionSort(int[] intArray) {
int comparisonCount = 0;
long startTime = System.currentTimeMillis();
for(int i=1; i<intArray.length;i++) {
int tempValue = intArray[i];
int j = 0;
for(j=i-1; j>=0 && tempValue<intArray[j];j--){
comparisonCount++;
intArray[j+1] = intArray[j];
}
intArray[j+1] = tempValue;
}
long endTime=System.currentTimeMillis();
System.out.println("Comparison Count = " + comparisonCount
+ " running time (in millis) = " +
(endTime-startTime) );
}
}
Well, works for me. Execute it in console like that:
java Sorting init
Then execute it another time:
java Sorting
Works perfectly. If you are in Eclipse go to run configuration > arguments and put init there.
Point is in your main method you are checking if someone invoked the program with init parameter, if yes then you create those files and write to them, if not - you are reading from them. You are probably invoking without init and the files are not there yet, that's why it doesn't work.
Related
I am having difficulty passing a directory to the code below. When I am prompted to enter a directory, I do as shown below: C:\Users. I get a 0 byte output, which is not accurate. Meaning that the program is not registering the typed directory.
code:
//import jdk.internal.icu.text.UnicodeSet;
import java.io.File;
import java.util.Scanner;
import java.util.Queue;
import java.util.LinkedList;
public class Hwk2018
{
public static void main(String[] args)
{
//String s = "C:\\Users\\
//File filess = new File(s);
System.out.println("Enter a directory or a file: ");
Scanner input = new Scanner(System.in);
String directory = input.nextLine();
Hwk2018 obj = new Hwk2018();
System.out.println(obj.getSize(new File(directory)) + " bytes");
}
int i = 0;
Queue<File> que = new LinkedList<>();
public long getSSize(File directory)
{
long size = 0;
que.add(directory);
while(!que.isEmpty())
{
File t = que.poll();
if(!t.isDirectory())
{
size += t.length();
}
else
{
//for(int i = 0; )
que.add(directory);
}
}
return size;
}
public static long getSize(File file)
{
long size = 0;
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; files != null && i < files.length; i++) {
size += getSize(files[i]);
}
} else {
size += file.length();
}
return size;
}
}
output when running ' MBP src % java Hwk2018 ' on the terminal and subsequently typing C:\Users:
0 bytes
Expected Output:
87 bytes (or some numerical value other than 0)
I would use File#exists to verify that the user input is a valid path, you could also add File#isDirectory check, but since getSize is doing this, it's probably not required.
subsequently typing C:\Users:
I'm using a Mac
Mac's don't have a concept of "drives" like windows, they have "volumes" and as such it should probably be /Users, but you could run into other issues, since you won't have read access to other users.
The following will print the path of your "home" directory and also uses File#exist to verify the user input
import java.io.File;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//String s = "C:\\Users\\
//File filess = new File(s);
String directory = System.getProperty("user.home");
System.out.println("Your home directory is [" + directory + "]");
System.out.println("Enter a directory or a file: ");
Scanner input = new Scanner(System.in);
directory = input.nextLine();
File parent = new File(directory);
if (parent.exists()) {
Main obj = new Main();
System.out.println(obj.getSize(new File(directory)) + " bytes");
} else {
System.out.println(directory + " is not a valid directory");
}
}
public static long getSize(File file) {
long size = 0;
System.out.println("Scanning " + file.getName());
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; files != null && i < files.length; i++) {
size += getSize(files[i]);
}
} else {
size += file.length();
}
return size;
}
}
I have a flat file with the name cartList.txt, and I have two classes with the names GetCachedCartList.java and AddToShoppingList.java.
I am using the class GetCachedCartList.java to get numbers (which are ids of products (I am working on aproject of a Shopping Cart)) from the flat file, these numbers are written in the file in form num1#num2#num3# etc., these numbers gets stored into the int array variable of this class.
As you can see, I have used '#' as the delimiter to distinguish between different numbers.
I am using the class AddToShoppingList.java to add the text "num#" to existing text present in the flat file.
The problem comes when I try to test these two classes, while the GetCachedCartList.java correctly outputs the numbers present in cartList.txt in its own main method, but when I use its object initialised in the main method of the AddToShoppingList.java after adding the piece of text like "num#", its giving very unexpected results.The number num seems to have get added in the helping array many times instead of only one time, and the text "num#" also gets added in the flat file's text more than one time but less than it has in the array.
I suspected that this might be due to incorrect use of loops, but couldn't spot any error.
cartList.txt
2#3#
GetCachedCartList.java
package Resources.utils.queries;
/**
*
* #author Aditya
*/
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
public class GetCachedCartList {
private static ArrayList<String> StringcartProdIdList = new ArrayList<String>();
private static int[] cartProdIdList;
public GetCachedCartList(){
try{
File cartListFile = new File("src/SessionData/productCachedData/cartList.txt");
Scanner scann = new Scanner(cartListFile);
scann.useDelimiter("#");
while(scann.hasNext()){
String s = scann.next();
StringcartProdIdList.add(s);
}
scann.close();
cartProdIdList = new int[StringcartProdIdList.size()];
for(int i = 0; i < StringcartProdIdList.size(); i++){
cartProdIdList[i] = Integer.parseInt(StringcartProdIdList.get(i));
}
}
catch (Exception ex) {
System.out.println("Error:"+ex.getMessage());
}
}
/**
* #return the IDs of Items added in the Shopping Cart
*/
public static int[] getCartProdIdList() {
return cartProdIdList;
}
public static void main(String[] args){
GetCachedCartList g = new GetCachedCartList();
System.out.println("Length: "+g.getCartProdIdList().length);
for(int i: g.getCartProdIdList()){
System.out.println(i);
}
}
}
AddToShoppingList.java
package Resources.utils.queries;
/**
*
* #author Aditya
*/
import java.io.File;
import java.util.Scanner;
import java.io.PrintWriter;
import Resources.utils.queries.GetCachedCartList;
public class AddToShoppingList {
public AddToShoppingList(int pid){
try{
GetCachedCartList gCCl = new GetCachedCartList();
int[] initialCartListArr = gCCl.getCartProdIdList();
String initialCartList = "";
for(int i = 0; i < initialCartListArr.length; i++){
initialCartList += initialCartListArr[i] + "#";
}
File cartListFile = new File("src/SessionData/productCachedData/cartList.txt");
PrintWriter writer = new PrintWriter(cartListFile);
writer.print("");
writer.write(initialCartList);
writer.write(pid+"#");
writer.close();
}
catch(Exception e){
System.out.println("Error:"+e.getMessage());
}
}
public static void main(String[] args){
GetCachedCartList gCCl1 = new GetCachedCartList();
int[] initialCartListArr = gCCl1.getCartProdIdList();
System.out.println("Initial cart list");
for(int i = 0; i < initialCartListArr.length; i++){
System.out.println(initialCartListArr.length+" : "+initialCartListArr[i]);
}
AddToShoppingList aTSL = new AddToShoppingList(9);
System.out.println("Updated cart list");
GetCachedCartList gCCl2 = new GetCachedCartList();
int[] finalCartListArr = gCCl2.getCartProdIdList();
for(int i = 0; i < finalCartListArr.length; i++){
System.out.println(finalCartListArr.length+" : "+finalCartListArr[i]);
}
}
}
The outputs the above codes, if you first run GetCachedCartList.java, and then AddToShoppingList.java, is:
GetCachedCartList.java
Length: 2
2
3
AddToShoppingList.java
Initial cart list
2 : 2
2 : 3
Updated cart list
9 : 2
9 : 3
9 : 2
9 : 3
9 : 2
9 : 3
9 : 2
9 : 3
9 : 9
And now the flat file have the text
2#3#2#3#9#
Where's is the mistake happening? Thanks~
I hope I correctly get your idea of the application. Sorry if not.
You have 0s because of String s = scann.next(); returns "2, 3, \n"
You have duplicates because of
AddToShoppingList.main {
...
GetCachedCartList gCCl1 = new GetCachedCartList();
...
GetCachedCartList gCCl2 = new GetCachedCartList();
}
I would suggest flowing code:
Output:
Error:null
Initial cart list
2 : 2
2 : 3
Error:null
Updated cart list
4 : 2
4 : 3
4 : 2
4 : 3
Code:
public class AddToShoppingList {
public AddToShoppingList(int pid) {
try {
GetCachedCartList gCCl = new GetCachedCartList();
List<Integer> initialCartListArr = gCCl.getCartProdIdList();
String initialCartList = "";
for (int i = 0; i < initialCartListArr.size(); i++) {
initialCartList += initialCartListArr.get(i) + "#";
}
File cartListFile = new File("/home/ibondarenko/projects/demo/src/main/resources/cartList.txt");
PrintWriter writer = new PrintWriter(cartListFile);
writer.print("");
writer.write(initialCartList);
writer.write(pid + "#");
writer.close();
} catch (Exception e) {
System.out.println("Error:" + e.getMessage());
}
}
public static void main(String[] args) {
GetCachedCartList gCCl1 = new GetCachedCartList();
List<Integer> initialCartListArr = gCCl1.getCartProdIdList();
System.out.println("Initial cart list");
for (int i = 0; i < initialCartListArr.size(); i++) {
System.out.println(initialCartListArr.size() + " : " + initialCartListArr.get(i));
}
AddToShoppingList aTSL = new AddToShoppingList(9);
System.out.println("Updated cart list");
// GetCachedCartList gCCl2 = new GetCachedCartList();
List<Integer> finalCartListArr = gCCl1.getCartProdIdList();
for (int i = 0; i < finalCartListArr.size(); i++) {
System.out.println(finalCartListArr.size() + " : " + finalCartListArr.get(i));
}
}
}
public class GetCachedCartList {
private static ArrayList<Integer> StringcartProdIdList = new ArrayList<Integer>();
public GetCachedCartList() {
try {
File cartListFile = new File("/home/ibondarenko/projects/demo/src/main/resources/cartList.txt");
Scanner scann = new Scanner(cartListFile);
scann.useDelimiter("#");
while (scann.hasNext()) {
int s = scann.nextInt();
StringcartProdIdList.add(s);
}
scann.close();
} catch (Exception ex) {
System.out.println("Error:" + ex.getMessage());
}
}
/**
* #return the IDs of Items added in the Shopping Cart
*/
public static ArrayList<Integer> getCartProdIdList() {
return StringcartProdIdList;
}
public static void main(String[] args) {
GetCachedCartList g = new GetCachedCartList();
System.out.println("Length: " + StringcartProdIdList.size());
for (int i : g.getCartProdIdList()) {
System.out.println(i);
}
}
}
I think you can simplify your code first:
One class with logic to read ids from the file and retrieve List<Integer>:
public final class ReadCartProdIds {
private final File file;
public ReadCartProdIds(File file) {
this.file = file;
}
public List<Integer> apply() throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
scan.useDelimiter("#");
List<Integer> cartProdIds = new ArrayList<>();
while (scan.hasNext()) {
cartProdIds.add(scan.nextInt());
}
return cartProdIds.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(cartProdIds);
}
}
}
Another one to add to this file new pid (you even do not have to reread existed file, just append new text to it):
public final class AddCarProdId {
private final File file;
public AddCarProdId(File file) {
this.file = file;
}
public void apply(int pid) throws IOException {
Files.write(file.toPath(), (pid + "#").getBytes(), StandardOpenOption.APPEND);
}
}
And finally your main program could look like this:
public static void main(String[] args) throws IOException {
File file = new File("d:/cartList.txt");
printFile(file, "Initial cart list:");
new AddCarProdId(file).apply(9);
printFile(file, "Updated cart list");
}
private static void printFile(File file, String message) throws FileNotFoundException {
System.out.println(message);
List<Integer> cartProdIds = new ReadCartProdIds(file).apply();
cartProdIds.forEach(cartProdId -> System.out.println(cartProdIds.size() + " : " + cartProdId));
}
I am new in java. Firstly, I'm sorry for my English. I wrote a code to merge two different txt files in the mergedFile.txt with determined data from the data1.txt and data2.txt. I create 5 different arrays to use them better but I cannot learn the length of words in the textfiles so arrays are using determined parameter. If I want to add another student, this codes don't work. Can you help me?
data1.txt
ID,Name,LastName,Department
12345,John,Samon,Computer Science
14524,David,Souza,Electric and Electronic
.
.
data2.txt
ID,Q1,Q2,Q3,Midterm,Final
12345,100,90,75,89,100
14524,80,70,65,15,90
.
margedFile.txt
ID,Name,Q_Average,Midterm,Final,Department
12345,John,88.3,89,100,Computer Science
14524,David,67.0,100,70,Electric and Electronic
This is ReadData Class
import java.io.FileInputStream;//import java.io library
import java.util.Scanner;//import scanner library
public class ReadData {
public static String[] Read(String filename,String filename2) {
Scanner scan = null;
Scanner scan1 = null;/
FileInputStream input1 = null;
FileInputStream input = null;
String[] result = new String[3];
try {
input = new FileInputStream(filename);
scan = new Scanner(input);
input1 = new FileInputStream(filename2);
scan1 = new Scanner(input1);
String[][] myArray = new String[4][4];
String[][] myArray1 = new String[4][6];
while(scan.hasNext() || scan1.hasNext()) {
for (int i = 0; i < myArray.length; i++) {
String[] split =
scan.nextLine().trim().split(",");
for (int j = 0; j < split.length; j++)
{
myArray[i][j] = split[j];
}
}
for (int i = 0; i < myArray1.length; i++) {
String[] split1 = scan1.nextLine().trim().split(",");
for (int j = 0; j < split1.length; j++) {
myArray1[i][j] = split1[j];
}
}
}
int[][] quiz = new int[3][3];
double[] average = new double[3];
int sum = 0;
double averagee = 0;
for (int i = 0; i < quiz.length; i++) {
for (int j = 0; j < quiz.length; j++) {
quiz[i][j] = Integer.parseInt(myArray1[i+1][j+1]);
sum += quiz[i][j];
}
averagee = sum/quiz.length;
average[i] = averagee;
sum = 0;
}
for (int i = 1; i < myArray1.length; i++) {
for (int j = 1; j < myArray1.length; j++) {
if(myArray[i][0].equalsIgnoreCase(myArray1[j][0])) {
result[i-1] = "\n" + myArray[i][0] + " "+ myArray[i][1] + " " + (average[j-1]) +" "+ myArray1[j][4] +" " + myArray1[j][5] + " "+ myArray[i][3];
//System.out.println(Arrays.deepToString(myArray[i]) + " " + Arrays.deepToString(myArray1[j]));
}
}
}
//System.out.println(Arrays.deepToString(quiz));
//System.out.println(Arrays.toString(average));
}
catch(Exception e) {
System.out.println(e);
}
return result;
}
}
This is WriteData class
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
public class WriteData extends ReadData {
void Write(String filename) {
PrintWriter writer = null;
FileOutputStream output = null;
try {
output = new FileOutputStream(filename);
writer = new PrintWriter(output);
writer.print("ID,Name,Q_Average,Midterm,Final,Department ");
writer.print(Arrays.toString(Read("data1.txt",
"data2.txt")));
writer.flush();
writer.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
I am reading a file with a disease name and its remedies. Therefore, i want to save the name as key and remedies in a set as the value. How can i reach that? It seems there is some problems in my code.
public static HashMap<String,Set<String>> disease = new HashMap <> ();
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner (new File ("diseases.txt"));
while (fin.hasNextLine()) {
HashSet <String> remedies = null;
String [] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0],remedies);
}
fin.close();
}catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
try {fin.close();} catch(Exception e) {}
}
Set <String> result = disease.get("thrombosis");
display(result);
public static <T> void display (Set<T> items) {
if (items == null)
return;
int LEN = 80;
String line = "[";
for (T item:items) {
line+= item.toString() + ",";
if (line.length()> LEN) {
line = "";
}
}
System.out.println(line + "]");
}
here is my code
cancer,pain,swelling,bleeding,weight loss
gout,pain,swelling
hepatitis A,discoloration,malaise,tiredness
thrombosis,high heart rate
diabetes,frequent urination
and here is what the txt contains.
In your code , you haven't initialized the remedies HashSet(thats why it is throwing NullPointerException at line number 14).
and second issue is : i is getting incremented by 1 and you are not checking with size of your pats array ( i > parts.length) .
I edited your code :
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<String>();
String[] parts = fin.nextLine().split(",");
int i = 1;
while (fin.hasNext()&&parts.length>i) {
remedies.add(parts[i].trim());
i++;
}
disease.put(parts[0], remedies);
}
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.io.File;
import java.util.Set;
public class Solution {
public static HashMap<String, Set<String>> disease = new HashMap<>();
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner (new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet <String> remedies = new HashSet<>();
String [] parts = fin.nextLine().split(",");
for (int i=1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
disease.put(parts[0],remedies);
}
fin.close();
}catch(Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
try {fin.close();} catch(Exception e) {}
}
Set <String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display(Set<T> items) {
if (items == null)
return;
int LEN = 80;
String line = "[";
for (T item : items) {
line += item.toString() + ",";
if (line.length() > LEN) {
line = "";
}
}
System.out.println(line + "]");
}
}
Here is full working code. As suggested by #Pratik that you forget to initialize HashSet that's why NullPointerException error was coming.
You have a few issues here:
no need for inner while loop (while (fin.hasNext()) {) - instead use `for(int i=1; i
HashSet <String> remedies = null; - this means the set is not initialized and we cannot put items in it - nede to change to: HashSet<String> remedies = new HashSet<>();
It is better practice to close() the file in the finally part
The 'display' method will delete the line (if it is longer than 80 characters) before printing it.
it is better to use StringBuilder when appending strings
So the corrected code would be:
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class TestSOCode {
public static HashMap<String,Set<String>> disease = new HashMap<>();
private static int LINE_LENGTH = 80;
public static void main(String[] args) {
Scanner fin = null;
try {
fin = new Scanner(new File("diseases.txt"));
while (fin.hasNextLine()) {
HashSet<String> remedies = new HashSet<>();
String[] parts = fin.nextLine().split(",");
disease.put(parts[0], remedies);
for (int i = 1; i < parts.length; i++) {
remedies.add(parts[i].trim());
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
try {
fin.close();
} catch (Exception e) {
System.out.println("Error when closing file: " + e.getMessage());
}
}
Set<String> result = disease.get("thrombosis");
display(result);
}
public static <T> void display (Set<T> items) {
if (items == null)
return;
StringBuilder line = new StringBuilder("[");
int currentLength = 1; // start from 1 because of the '[' char
for (T item:items) {
String itemStr = item.toString();
line.append(itemStr).append(",");
currentLength += itemStr.length() + 1; // itemStr length plus the ',' char
if (currentLength >= LINE_LENGTH) {
line.append("\n");
currentLength = 0;
}
}
// replace last ',' with ']'
line.replace(line.length() - 1, line.length(), "]");
System.out.println(line.toString());
}
}
Working on a program that will read input from a file (using the Declaration of Independence as a test) and write the number of ints, chars, strings, etc. into another new file. But I'm running into a problem with my array index being out of bounds. I've looked over my loops a dozen times now, but I can't figure out what could be causing the problem. Thanks in advance for any help =]
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class P5 {
static String arrayString[] = new String[100];
static int numberLines = 0;
static int numberWords = 0;
static int numberChars = 0;
static int numberUpper = 0;
static int numberLower = 0;
static int numberDigits = 0;
static int numSpaces = 0;
static int numberTabs = 0;
static int numberSpecial = 0;
private static void readFile(String inputFile) {
try{
Scanner fileScan = new Scanner(new File("Declaration.txt"));
while(fileScan.hasNext()){
arrayString[numberWords] = fileScan.next();
numberWords++;
}
while(fileScan.hasNextLine()){
numberLines++;
}
fileScan.close();
}
catch(IOException e){
}
}
private static void gatherStatistics(String sArray[]) {
for (int i = 0; i < sArray.length; i++){
String line = sArray[i];
numberChars += line.length();
for (int j = 0; j < line.length(); j++){
char c = line.charAt(j);
if(Character.isUpperCase(c))
numberUpper++;
else if(Character.isLowerCase(c))
numberLower++;
else if(Character.isDigit(c))
numberDigits++;
else if(Character.isSpaceChar(c))
numSpaces++;
else if(c == '\t')
numberTabs++;
else
numberSpecial++;
}
}
}
private static void writeFile(String outputFile) {
try{
PrintWriter fileOut = new PrintWriter(new File("Statistics.txt"));
fileOut.println("Number of Lines: " + numberLines);
fileOut.println("Number of Words: " + numberWords);
fileOut.println("Number of Lines: " + numberChars);
fileOut.println("Number of Lines: " + numberUpper);
fileOut.println("Number of Lines: " + numberLower);
fileOut.println("Number of Lines: " + numberDigits);
fileOut.println("Number of Lines: " + numSpaces);
fileOut.println("Number of Lines: " + numberTabs);
fileOut.println("Number of Lines: " + numberSpecial);
fileOut.close();
System.exit(1);
} catch (FileNotFoundException e){}
}
public static void main(String[] args) {
readFile(args[0]);
gatherStatistics(arrayString);
writeFile(args[1]);
System.exit(1);
}
}
You have read a file with more than 100 lines.
Instead of using array, use ArrayList
Change this line:
static String arrayString[] = new String[100];
to:
static ArrayList<String> arrayString = new ArrayList<String>();
Change this line:
private static void gatherStatistics(String sArray[]) {
to:
private static void gatherStatistics(ArrayList<String> sArray) {
Change this line:
arrayString[numberWords] = fileScan.next();
to
arrayString.add(fileScan.next());