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());
Related
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
}
}
}
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.
I try to create a stack that will be interactive to the user. It will give a choice to pop a data one by one or all of the data. My problem is, when I try to pop just a data, it gives me empty string.
Here's my code :
package Tugas;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;
import java.util.logging.Level;
import java.util.logging.Logger;
public class myStack {
private static Stack<Integer> stack;
private static int size;
public static void main(String[] args) {
System.out.println("Enter amount numbers : ");
size = inputData();
createStack(size);
readData();
Scanner scanner = new Scanner(System.in);
System.out.println("Take it All (y) or one by one (n)");
String input = scanner.next();
if (input.equals("y")) {
writeData();
} else {
popData();
writeData();
String confirm;
Scanner scanner2 = new Scanner(System.in);
System.out.println("Take again ? ");
confirm = scanner2.next();
if (confirm.equals("y")) {
popData();
writeData();
}
}
}
private static void createStack(int size) {
stack = new Stack<>();
}
private static void writeData() {
int dataStack;
System.out.println(" The contains of data: ");
for (int i = 0; i < size; i++) {
try {
dataStack = stack.pop();
System.out.println("Value of stack at " + (i + 1) + " : " + dataStack);
} catch (EmptyStackException e) {
}
}
}
private static void readData() {
int data;
System.out.println("===== all data =====");
for (int i = 0; i < size; i++) {
System.out.print("The data at : " + (i + 1) + " : ");
data = inputData();
stack.push(data);
}
}
private static void popData() {
int dataStack;
System.out.println("=== Pop a data : ===");
dataStack = stack.pop();
}
private static Integer inputData() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = null;
try {
input = br.readLine();
} catch (IOException ex) {
Logger.getLogger(Tumpukan.class.getName()).log(Level.SEVERE, null, ex);
}
int data = Integer.parseInt(input);
return data;
}
}
Thanks for the help ...
You pop data twice :
Once in :
popData();
And then in a loop in :
writeData();
This means writeData will be one element short, since it was already popped by popData.
I'm taking Java Introductory Programming class and currently i'm working on a final project. The assignment description can be found here link
I'm having hard time with accomplishing this "Write the output from your Instrument class methods to a text file that a user entered from the command line arguments (e.g. java Mynamep3tst myfilename.txt)." Here's some of my code:
import java.io.*;
public class Test{
public static void main(String[] args) {
String outputFile = "";
if (0 < args.length) {
outputFile = args[0];
System.out.println("This program will write output to this file: " + outputFile + "\n");
try {
File file = new File(outputFile);
PrintWriter output = new PrintWriter(outputFile);
output.println("hello"); //to check if ir prints anything
Violin[] simpleViolin = new Violin[5];
//Create 5 violin objects
for (int i = 0; i < simpleViolin.length; i++){
simpleViolin[i] = new Violin();
}
output.println("\nLet's tune " + Violin.getNumberOfViolins() + " violins.");
for(int i = 0; i < simpleViolin.length; i++){
output.print(i + 1);
simpleViolin[i].tuneOn();
}
output.println("\nNow let's start playing " + Violin.getNumberOfViolins() + " violins.");
for(int i = 0; i < simpleViolin.length; i++){
output.print(i + 1);
simpleViolin[i].startPlaying();
}
output.println("\nIt looks like " + Violin.getNumberOfViolins() + " violins have untuned.");
for(int i = 0; i < simpleViolin.length; i++){
output.print(i + 1);
simpleViolin[i].tuneOff();
}
output.println("\nThis music is terrible! Let's stop it!");
for(int i = 0; i < simpleViolin.length; i++){
output.print(i + 1);
simpleViolin[i].stopPlaying();
}
output.close();
}
catch (IOException io){
System.out.println("Sorry that file is not found " + io);
}
}//end if
}//end main
}//end Test
class Violin{
private final int numberOfStrings = 4;
private final char[] stringNames = {'E', 'A', 'D', 'G'};
private boolean isTuned = false;
private boolean isPlaying = false;
private static int numberOfViolins = 0;
private PrintWriter output;
public Violin(){
numberOfViolins++;
}
public void startPlaying() {
isPlaying = true;
System.out.println(" violin is now playing.");
}
public void stopPlaying() {
isPlaying = false;
System.out.println(" violin has stopped playing.");
}
public void tuneOn() {
isTuned = true;
System.out.println(" violin is now tuned.");
}
public void tuneOff() {
isTuned = false;
System.out.println(" violin is untuned.");
}
static int getNumberOfViolins(){
return numberOfViolins;
}
}//end class Violin
So my question is how do I make my Violin class methods to print to a user specified file?
When you create your Violin object you can pass the output as a reference on the constructor so inside the violin you will use output instead of System.out.println.
Change the Violoin constructor to:
public Violin (PrintStream output){
this.output = output;
}
And then just use the outpu inside the violin.
I'm using random access files to write a raf using an arrayList store. I do not know if it can be done, but I'm giving it a try because it is the best solution for me to create this application.
Here is the run-time error that I am getting:
Exception in thread "main" java.io.EOFException
at java.io.RandomAccessFile.readChar(Unknown Source)
at Student.read(Student.java:93)
at MainApp.start(MainApp.java:60)
at MainApp.main(MainApp.java:17)
And here is my code:
MainApp
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
public class MainApp
{
public static void main(String[] args) throws Exception
{
new MainApp().start();
}
public void start()throws Exception
{
StudentStore details = new StudentStore();
//Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "bexo#hotmail.com");
//details.print();
RandomAccessFile raf = new RandomAccessFile("ContactDetails.txt", "rw");
Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "bexo#hotmail.com");
Student b = new Student("Fabio Borini", "DKIT28", "0876136944", "fabioborini#gmail.com");
Student c = new Student("Gaston Ramirez", "DKIT29", "0419834501", "gramirez#webmail.com");
Student d = new Student("Luis Suarez", "DKIT7", "0868989878", "luissuarez#yahoo.com");
Student e = new Student("Andy Carroll", "DKIT9", "0853456788", "carroll123#hotmail.com");
details.add(a);
details.add(b);
details.add(c);
details.add(d);
details.add(e);
for (int i = 0; i < details.size(); i++)
{
//a.setStudentName(a[i]);
//a.setLastName(lnames[i]);
// a.setAddress(addresses[i]);
// a.setAge(ages[i]);
// a.setSalary(salaries[i]);
a.write(raf);
}
raf = new RandomAccessFile("employee.dat", "rw");
// er = new Student();
int numRecords = (int) raf.length() / details.size();
for (int i = 0; i < numRecords; i++) {
a.read(raf);
System.out.print(a.getStudentName() + " ");
System.out.print(a.getStudentId() + " ");
System.out.print(a.getStudentEmail() + " ");
System.out.print(a.getStudentTelephoneNumber() + " ");
}
raf.seek(0);
for (int i = 0; i < numRecords; i++)
{
a.read(raf);
raf.seek(raf.getFilePointer() - details.size());
a.write(raf);
raf.seek(raf.getFilePointer() - details.size());
a.read(raf);
}
System.out.print(a.getStudentName() + " ");
System.out.print(a.getStudentId() + " ");
System.out.print(a.getStudentEmail() + " ");
System.out.print(a.getStudentTelephoneNumber() + " ");
}
}
Student
import java.io.IOException;
import java.io.RandomAccessFile;
public class Student
{
//---------------------------------------------------------------------------
// Class Variables.
//---------------------------------------------------------------------------
private String studentName;
private String studentId;
private String studentTelephoneNumber;
private String studentEmail;
//---------------------------------------------------------------------------
// Constructor.
//---------------------------------------------------------------------------
public Student(String studentName, String studentId,String studentTelephoneNumber, String studentEmail)
{
this.studentName = studentName;
this.studentId = studentId;
this.studentTelephoneNumber = studentTelephoneNumber;
this.studentEmail = studentEmail;
}
//---------------------------------------------------------------------------
// Getters.
//---------------------------------------------------------------------------
public String getStudentName()
{
return studentName;
}
public String getStudentId()
{
return studentId;
}
public String getStudentTelephoneNumber()
{
return studentTelephoneNumber;
}
public String getStudentEmail()
{
return studentEmail;
}
//---------------------------------------------------------------------------
// Setters.
//---------------------------------------------------------------------------
public void setStudentName(String studentName)
{
this.studentName = studentName;
}
public void setStudentId(String studentId)
{
this.studentId = studentId;
}
public void setStudentTelephoneNumber(String studentTelephoneNumber)
{
this.studentTelephoneNumber = studentTelephoneNumber;
}
public void setStudentEmail(String studentEmail)
{
this.studentEmail = studentEmail;
}
//---------------------------------------------------------------------------
// toString.
//---------------------------------------------------------------------------
public String toString()
{
return "---------------------------Student--------------------------- " +
"\nStudent Name:" + studentName +
"\nStudent Id:"+ studentId +
"\nStudent Telephone Number:"+ studentTelephoneNumber +
"\nStudent Email:" + studentEmail;
}
void read(RandomAccessFile raf) throws IOException
{
char[] temp = new char[15];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
studentName = new String(temp);
temp = new char[15];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
studentId = new String(temp);
temp = new char[30];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
studentEmail = new String(temp);
temp = new char[30];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
studentTelephoneNumber = new String(temp);
temp = new char[30];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
}
void write(RandomAccessFile raf) throws IOException
{
StringBuffer sb;
if (studentName != null)
sb = new StringBuffer(studentName);
else
sb = new StringBuffer();
sb.setLength(15);
raf.writeChars(sb.toString());
if (studentId != null)
sb = new StringBuffer(studentId);
else
sb = new StringBuffer();
sb.setLength(15);
raf.writeChars(sb.toString());
if (studentEmail != null)
sb = new StringBuffer(studentEmail);
else
sb = new StringBuffer();
sb.setLength(30);
raf.writeChars(sb.toString());
if (studentTelephoneNumber != null)
sb = new StringBuffer(studentTelephoneNumber);
else
sb = new StringBuffer();
sb.setLength(30);
raf.writeChars(sb.toString());
}
}
You are reading beyond the end of the file. Reading data that isn't there.
The basic problem is that you are reading more data than you are writing.
You are reading 30 char at the end of each record which you didn't write. Given you discard them it appears you don't need to be doing this. I would delete the code which reads after studentTelephoneNumber
If load just one detail do you get the problem? I think your problem is that you are reading off the end of the file. Your read function which reads 15/30 characters seem dangerous because you may not have written that much. Why not read until you get a comma or some other separator? (eg tab)
It's this sort of thing that looks dangerous
char[] temp = new char[15];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
Where does the 15 come from?
Try and break it down with just one detail and bulid up from there. You should find the error. I would personally read until you find a particular separator.