Main method input file keeps giving me IndexOutOfBoundsException (even with right arguments) - java

I'm trying to use args[0] as an input file, but when I run the program, I keep getting an IndexOutOfBoundsException, although I'm quite sure that args[0] is the correct argument. I ran into this problem with my last program as well, but I can't figure out what I'm doing wrong.
Code:
import java.io.*;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class SortTest {
public static void main(String args[]) throws FileNotFoundException {
try {
Scanner read = new Scanner(new File(args[0]));
while (read.hasNextLine()) {
String name = read.nextLine();
read.nextLine();
String line1 = read.nextLine();
int sh = Integer.parseInt(line1.substring(0,2));
int sm = Integer.parseInt(line1.substring(3));
read.nextLine();
String line2 = read.nextLine();
int fh = Integer.parseInt(line2.substring(0,2));
int fm = Integer.parseInt(line2.substring(3));
if (fh<sh) {
System.out.println("Times not in correct order.");
return;
} else if (fh==sh) {
if (fm<sm) {
System.out.println("Times not in correct order.");
return;
}
} else {
System.out.println(name + "\n" + sh + ":" + sm + "\n" + fh + ":" + fm);
}
}
read.close();
}
catch (FileNotFoundException e) {
System.out.println("Invalid file path.");
}
catch (NoSuchElementException n) {
System.out.println("No readable text in file.");
}
catch (IndexOutOfBoundsException x) {
System.out.println("Proper format is java LectureSortTest <input>");
}
catch (NumberFormatException num) {
System.out.println("File contents not formatted correctly");
}
}
}

Related

Read CSV containing Strings & int to arraylist with try/catch

I'm hoping some might be able to suggest an alternate method to a program I'm working on. I've done the below test code to display my query without having to post my full code.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Main {
ArrayList<Students> chemistry = new ArrayList<>();
public void loadClass() {
try (BufferedReader br = new BufferedReader(new FileReader("Chemistry.csv"))) {
String line;
line = br.readLine();
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
try {
chemistry.add(new Students(values[0], values[1], Integer.parseInt(values[2]),
Integer.parseInt(values[3]), Integer.parseInt(values[4])));
} catch (NumberFormatException e) {
System.out.println("You have some text in a number field for entry: " + values[0] + " " + values[1]);
}
}
} catch (FileNotFoundException e) {
System.out.println("The file has not been found in the path \"" + (new File(".").getAbsoluteFile()) + "\"");
System.out.println("Please place the CSV file at this location");
} catch (IOException e) {
System.out.println("Sorry an input/output error has occured.");
e.printStackTrace();
}
System.out.println("students loaded from the file are:");
for (Students pupils : chemistry) {
System.out.println("Student " + pupils.getFirstName() + " " + pupils.getSurname() + " was born in "
+ pupils.getBirthYear() + "/" + pupils.getBirthMonth() + " /"
+ pupils.getBirthDay());
}
System.out.println("\nThe number of students in the class is: " + chemistry.size());
}
public static void main(String[] args) {
Main main = new Main();
main.loadClass();
}
}
public class Students {
private String firstName;
private String surname;
private int birthYear;
private int birthMonth;
private int birthDay;
// All-args constructor, getters and setters omitted for brevity
}
Here is the CSV data I'm using in the Chemistry.csv file
First Name,Surname,Year of Birth,Month of Birth,Day of Birth
Joe,Bloggs,2002,12,8
Jane,Bloggs,2003,11,15
Harry,Smith,2004,10,2
William,Wallace,2001,9,7
Philip,Jones,2002,Aug,9th
As you can see in my CSV file, I've deliberately put a string entry for the month and day in the last line. This is to test my NumberFormatException try/catch.
It works and the user gets prompted that there's an error with that line entry, but this is a small dataset. I'm wondering what I can do when there may be hundreds of lines.
I was thinking that in the catch I could have something that would replace the invalid String with a valid int number. I know in this case I would have to engineer an if/else or switch statement to account for the 12 months and 30(ish) days, however I would just like '0' to be entered for now.
I'm not sure how to pass int 0 as a default value for this as my chemistry.add line parses the file.
I also thought there may be an alternate way of entering the values into my ArrayList so I can put the try/catch around just the Integer.parseInt bits, but again, I'm not sure of another method.
Can anyone suggest a good option to investigate?
EDIT:
After the comment by g00se below, I used this instead and it seemed to work:
while ((line = br.readLine()) != null) {
int third, fourth, fifth;
String[] values = line.split(",");
String first = values[0];
String second = values[1];
try {
third = Integer.parseInt(values[2]);
} catch (NumberFormatException e3) {
third = 0;
}
try {
fourth = Integer.parseInt(values[3]);
} catch (NumberFormatException e4) {
fourth = 0;
}
try {
fifth = Integer.parseInt(values[4]);
} catch (NumberFormatException e5) {
fifth = 0;
}
chemistry.add(new Student(first, second, third, fourth, fifth));
}
Needs some tidying up but at least I have a way forward...

read from text file using try/catch blocks

so im trying to read from a file the number of words and adding them up to give and int answer? And help and or suggestions would be nice, and i can only use a try/catch while for loop and if/else/if.... Thanks!
Here what i got so far:
package filereadingexercise2;
import java.io.*;
import java.util.Scanner;
/**
*
* #author theGreggstar
*/
public class FileReadingExercise2
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
Scanner keys = new Scanner(System.in);
String nameOfFile;
System.out.print("Please Enter The Name Of A File Or Directory, or Type Quit To Exit: ");
nameOfFile = keys.nextLine();
Scanner input = null;
try
{
input = new Scanner(new File(nameOfFile));
}
catch(FileNotFoundException s)
{
System.out.println("File does Not Exist Please Try Again: ");
}
while(input.hasNext())
{
String contents = input.next();
int length;
System.out.print(contents);
}
}
}
If I understand you correctly, you want something like this -
public static void main(String[] args) {
Scanner keys = new Scanner(System.in);
for (;;) { // Loop forever.
System.out.print("Please Enter The Name Of A File Or "
+ "Directory, or Type Quit To Exit: ");
String nameOfFile = keys.nextLine().trim(); // get the User input.
if (nameOfFile.equalsIgnoreCase("quit")) { // check for exit condition.
break;
}
File f = new File(nameOfFile); // Construct a File.
if (f.exists()) { // Does it exist?
if (f.isFile() && f.canRead()) { // is it a File and can I read it?
Scanner input = null;
try {
input = new Scanner(f); // The Scanner!
while (input.hasNextLine()) {
String contents = input.nextLine();
System.out.println(contents); // Print the lines.
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (input != null) {
input.close(); // Close the file scanner.
}
}
} else if (f.isDirectory()) { // No, it's a directory!
try {
System.out.println("File "
+ f.getCanonicalPath()
+ " is a directory");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Store 100 strings and search file i/o java

In this program I am trying write a program that reads the first 100 strings from a set of text files and then counts how many times those strings appear in the whole of each file. Well I keep getting a crazy output and I asked this question earlier but butchered it. One thing has changed but now my output is null = 0. for 100 times
my output: http://i.imgur.com/WVZJnTp.png
package program6;
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Program6 {
public static final String INPUT_FILE_NAME = "myths.txt";
public static final String INPUT_FILE_NAME2 = "pnp.txt";
public static final String INPUT_FILE_NAME3 = "tsawyer.txt";
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
Scanner in = null;
Scanner fin = null;
Scanner fin2 = null;
Scanner fin3 = null;
String[] character = new String[100];
int[] counter = new int[100];
try {
fin = new Scanner(new File(INPUT_FILE_NAME));
} catch (FileNotFoundException e) {
System.err.println("Error opening the file " + INPUT_FILE_NAME);
System.exit(1);
}
try {
fin2 = new Scanner(new File(INPUT_FILE_NAME2));
} catch (FileNotFoundException e) {
System.err.println("Error opening the file " + INPUT_FILE_NAME2);
System.exit(1);
}
try {
fin3 = new Scanner(new File(INPUT_FILE_NAME3));
} catch (FileNotFoundException e) {
System.err.println("Error opening the file " + INPUT_FILE_NAME3);
System.exit(1);
}
for (int i = 0; i < character.length; i++) {
}
System.out.println("Word: Count:");
for (int i = 0; i < 100; i++) {
System.out.println(character[i] + " " + counter[i]);
}
}
}
Simply replace
System.out.println(character + " " + counter);
by
System.out.println(character[i] + " " + counter[i]);
On this line System.out.println(character + " " + counter);
It should be:
System.out.println(character[i] + " " + counter[i]);

Using Two OutputStreams and BufferedWriters in Java [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I was curious if anyone could help me understand what I'm doing wrong. I'm just learning how to use OutputStreams and BufferedWriters in Java and I'm not sure I'm doing it right. I know how to use one OutputStream and BufferedWriter but my problem is trying to use two of them in one class.
Right now the main errors I'm getting lies in my LowerAndUpper class and is between my try/catch statements and in my if/else statements and I'm not sure what I'm doing wrong. So I'd appreciate any help you guys could give on the matter and in helping me understand how to use two of these items at once.
These are the errors I'm getting and since I'm still a beginner with Java in general I don't exactly understand what's going on here:
line 40 error: ')' expected
if (creditsEarned>60 writerUpper.write){
line 40 error: not a statement
if (creditsEarned>60 writerUpper.write){
line 40 error: ';' expected
if (creditsEarned>60 writerUpper.write){
line 43 error: 'else' without 'if'
else (writerLower.write){
line 43 error: not a statement
else (writerLower.write){
line 43 error: ';' expected
else (writerLower.write){
Here is my code:
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LowerAndUpper {
public static void main(String[] args) {
Path file1 =
Paths.get("C:/temp/lowerclassman.txt");
Path file2 =
Paths.get("C:/temp/upperclassman.txt");
String s = "";
String delimiter = ",";
int id;
String name;
double creditsEarned;
final int QUIT = 999;
try {
OutputStream output = new BufferedOutputStream(Files.newOutputStream(file1));
BufferedWriter writerUpper = new BufferedWriter(new OutputStreamWriter(output));
OutputStream output2 = new BufferedOutputStream(Files.newOutputStream(file2));
BufferedWriter writerLower = new BufferedWriter(new OutputStreamWriter(output2));
while (true) {
id = Validate.collectInt("Enter student ID number or " + QUIT
+ " to quit >> ");
if (id == QUIT) {
break;
}
name = Validate.collectString(2, "Enter student name "
+ id + " >> ");
creditsEarned = Validate.collectWage("Enter credit hours >> ");
s = id + delimiter + name + delimiter + creditsEarned;
if (creditsEarned>60 writerUpper.write){
System.out.println("Student is a Lowerclassman");
else (writerLower.write){
System.out.println("Student is an Upperclassman");
}
}
writerUpper.write(s, 0, s.length());
r.newLine();
} //end while
writer.close();
writer2.close();
} catch (Exception e) {
System.out.println("Message: " + e);
}
}
}
// **************************************************************************
class Validate {
public static int collectInt(String messageIn) {
Scanner input = new Scanner(System.in);
int intOut = 0;
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
intOut = input.nextInt();
valid = false;
} catch (InputMismatchException ie) {
input.nextLine();
System.out.println("You must enter a whole number");
} //end catch
} //end while
return intOut;
}//end collectInt method
//*************************************************************************
public static String collectString(int strLen, String messageIn) {
Scanner input = new Scanner(System.in);
String strOut = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
strOut = input.nextLine();
if (strOut.length() < strLen) {
throw new Exception();
}
valid = false;
} catch (Exception e) {
System.out.printf("You must be at least %s characters\n",
strLen);
} //end catch
} //end while
return strOut;
} //end collectString method
//*************************************************************************
public static String collectZipcode(String messageIn) {
Scanner input = new Scanner(System.in);
String strOut = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
strOut = input.nextLine();
Integer.parseInt(strOut);
if (strOut.length() != 5) {
throw new Exception();
}
valid = false;
} catch (NumberFormatException ne) {
System.out.println("Please enter a valid zip code");
} catch (Exception e) {
System.out.printf("A zip code should be 5 numbers long");
} //end catch
} //end while
return strOut;
}//end collectZipcode method
//*************************************************************************
public static String collectEmail(String messageIn) {
String expression = "^[\\w\\.-]+#([\\w\\-]+\\.)+[A-Z]{2,4}$";
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Scanner input = new Scanner(System.in);
String strOut = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
strOut = input.nextLine();
CharSequence emailChk = strOut;
Matcher matcher = pattern.matcher(emailChk);
if (!matcher.matches()) {
throw new Exception();
}
valid = false;
} catch (Exception e) {
System.out.printf("Please try again with a valid email "
+ "address\n");
} //end catch
} //end while
return strOut;
}//end collectEmail method
//*************************************************************************
public static Double collectWage(String messageIn) {
Scanner input = new Scanner(System.in);
double dblOut = 0;
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
dblOut = input.nextDouble();
valid = false;
} catch (InputMismatchException ie) {
input.nextLine();
System.out.println("You must enter a whole number ");
} //end catch
} //end while
return dblOut;
}//end collectInt method
//*************************************************************************
public static String collectPhone(String messageIn) {
String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Scanner input = new Scanner(System.in);
String strOut = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
strOut = input.nextLine();
CharSequence phoneChk = strOut;
Matcher matcher = pattern.matcher(phoneChk);
if (!matcher.matches()) {
throw new Exception();
}
valid = false;
} catch (Exception e) {
System.out.printf("Please try again with a valid phone "
+ "number\n");
} //end catch
} //end while
return strOut;
}//end collectPhone method
//*************************************************************************
public static String collectSsn(String messageIn) {
String expression = "^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$";
Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
Scanner input = new Scanner(System.in);
String strOut = "";
boolean valid = true;
System.out.println(messageIn);
while (valid) {
try {
strOut = input.nextLine();
CharSequence ssnChk = strOut;
Matcher matcher = pattern.matcher(ssnChk);
if (!matcher.matches()) {
throw new Exception();
}
valid = false;
} catch (Exception e) {
System.out.printf("Please try again with a valid social security "
+ "number\n");
} //end catch
} //end while
return strOut;
}//end collectSsn
} //end Validate Class
Thanks in advance for all your help.
Firstly, you have initialised:
BufferedWriter writerUpper = new BufferedWriter(new OutputStreamWriter(output));
But then used two other varible names:
writer.close();
And:
r.newLine();
Correct usage of BufferedWriter can be found in this documentation:http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html
As for the if and else statements, make sure you format your code correctly. General usage of an if statement is to have a condition:
if(condition)
{
//do something
}
else
{
//do something else
}
Ie for your circumstance:
if (creditsEarned>60 writerUpper.write){
System.out.println("Student is a Lowerclassman");
else (writerLower.write){
System.out.println("Student is an Upperclassman");
}
}
Should be:
if (creditsEarned> 60){
writerUpper.write(s, 0, s.length());
writerUpper.newLine();
}
else
{
writerLower.write(s, 0, s.length());
writerLower.newLine();
}
And then make sure you use the same variable names as you initialised:
writerLower.close();
writerUppder.close();

Java-Greatest number of friends (from .txt file)

I'm trying to create a program that reads in a .txt file with multiple lines containing lists of names. A sample of the test file is below:
Joe Sue Meg Ry Luke
Kay Trey Phil George
I have three classes(also below). Everything works fine, but I would like to know which friend-set has the greatest number of friends (i.e. in the test file Joe would have the greatest number of friends)
The data isn't limited to only two friend-sets though...
import java.io.*;
//Finds the file
public class ReadFileLine {
public static void main(String[] args) throws Exception {
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in),1);
System.out.println("Hello! " + "Please enter the name of your test file: " +
"\n**Hint** for this assignment the file name is: friendsFile.txt\n");
String fileName= keyboard.readLine();
System.out.println(fileName);//
FileLine doLine = new FileLine();
doLine.readList(fileName);
}
}
Class 2:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class InStringFile {
//read the file
private BufferedReader in;
//read each line
private String nextLine;
//handle exceptions
public InStringFile(String filename) {
//line by line input
try {
in = new BufferedReader(new FileReader(filename));
nextLine = in.readLine();
}
catch (FileNotFoundException ee){
System.out.println("We're sorry,\n" +"File " + filename + " cannnot be found.");
System.exit(0);
}
catch (IOException e){
System.out.println("We're sorry,\n" +"File " + filename + " cannot be read.");
System.exit(0);
}
}
//reads the file as string
public String read() {
String current = nextLine;
try {
nextLine = in.readLine();
}
//catch exception
catch (IOException e){
System.out.println("We're sorry, this file cannot be read.");
System.exit(0);
}
return current;
}
public boolean endOfFile() {
return (nextLine == null);
}
//close the file
public void close(){
try {
in.close();
in = null;
}
//catch if file cannot be closed
catch (IOException e){
System.out.println("Problem closing file.");
System.exit(0);
}
}
}
Class 3:
import java.util.StringTokenizer;
public class FileLine {
public void readList (String fileName) throws Exception {
//opens the file and controls file reading
InStringFile reader = new InStringFile(fileName);
System.out.println("\nFile Found!" +
" Now reading from file: " + fileName + "\n");
// line by line read
String line;
do {
line = (reader.read());
//print the friend list
System.out.println("The following friend-set exists: " + line);
this.TokenizeString(line);
}while (!reader.endOfFile());
reader.close();
}
//number of friends
public void TokenizeString(String nameList){
StringTokenizer tokens = new StringTokenizer(nameList);
System.out.println("The number of friends in this friend-set is: " + tokens.countTokens());
}
}
Okay, so I modified the fileLine class to be the following:
import java.util.StringTokenizer;
public class FileLine {
public void readList (String fileName) throws Exception {
//opens the file and controls file reading
InStringFile reader = new InStringFile(fileName);
System.out.println("\nFile Found!" +
" Now reading from file: " + fileName + "\n");
// line by line read
String line;
do {
line = (reader.read());
//print the friend list
System.out.println("The following friend-set exists: " + line);
this.TokenizeString(line, line);
}while (!reader.endOfFile());
reader.close();
}
//number of friends
public void TokenizeString(String nameList, String nameByName) {
StringTokenizer tokens = new StringTokenizer(nameList);
System.out.println("The number of friends in this friend-set is: " + tokens.countTokens());
StringTokenizer st = new StringTokenizer(nameByName, " ");
String firstName = st.nextToken();
System.out.println("Friend-set Leader: " + firstName);
}
}
So now the code returns the first name in each line... I still am stuck on how to store the number of tokens. IF I could do that then I could compare and return the greatest number (right?)...
Let tokenizeString(..) return the number of friends. Then:
int maxFriends = 0;
int maxFriendsLine = 0;
int currentLine = 0;
while (..) {
int friends = tokenizeString(..);
if (friends > maxFriends) {
maxFriendsLine = currentLine;
maxFriends = friends;
}
currentLine++;
}
A few notes:
see if you can use commons-lang FileUtils.readLines(..) or guava Files.readLines(..)
prefer str.split(" ") instead of StringTokenizer
use lower-case methods - that's what the java convention prescribes.

Categories