I am having trouble with a ticketing system that I am trying to create using java. I am trying to utilize two files to read and write my inputs. I am testing with just salesSell method at the moment. I am passing the args using terminal. The problem that I am having is an arrayoutofbounds exception that gets thrown.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at cisc_327_frontend.Frontend_try1.main(Frontend_try1.java:763)
the two array parameters that I am passing are parsed from the same line in my current events file. an example of a line in the file is : "testevent1__________0003". I cannot seem to figure out where I am having this problem. Any type of guidance would be much appreciated.
package cisc_327_frontend;
import java.io.*;
import java.util.*;
public class Frontend_try1 {
private static File fileOutput;
private static List<StringBuilder> eventTrans = new ArrayList<>();
public static void consoleInput(String[] namesArray, int[] ticketArray,File fileCurrentEvents){
System.out.println("Enter command:");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
boolean correct = true;
do{
if(inputString.toUpperCase().equals( "LOGIN")) {
//enter login mode
login(namesArray, ticketArray,fileCurrentEvents);
correct = true;
}
if(inputString.toUpperCase().equals("LOGOUT")){
logout(namesArray, ticketArray,fileCurrentEvents);
correct=true;
}
if (!"LOGIN".toUpperCase().equals(inputString) || !"LOGOUT".toUpperCase().equals(inputString)){
System.out.println("Incorrect command, please enter command:");
input = new Scanner(System.in);
inputString = input.nextLine();
correct = false;
}
}while(!correct);
}
public static void login(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
System.out.println("Sales or Admin?");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
boolean correct = true ;
do {
if(inputString.toUpperCase().equals("LOGOUT")){
logout(null, null, null);
}
else if(inputString.toUpperCase().equals("SALES")) {
//enter sales mode
sales(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("ADMIN")) {
//enter admin mode
admin(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("LOGOUT")) {
//enter logout mode
logout( namesArray, ticketArray, fileCurrentEvents);
correct = true;
} else {
//ask again
System.out.println("Invalid Input");
System.out.println("Sales or Admin?");
input = new Scanner(System.in);
inputString = input.nextLine();
correct = false;
}
}while(!correct);
}
public static void sales(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
//System.out.println("SALES");
System.out.println("Sales Mode");
System.out.println("Enter Command:");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
boolean correct = true ;
do {
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
else if(inputString.toUpperCase().equals("SELL")) {
//enter sales Sell mode
salesSell(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("RETURN")) {
//enter sales Return mode
salesReturn(namesArray, ticketArray,fileCurrentEvents);
correct = true;
} else if (inputString.toUpperCase().equals("LOGOUT")) {
//enter Logout mode
logout( namesArray, ticketArray, fileCurrentEvents);
correct = true;
} else {
//ask again
System.out.println("Invalid Input");
System.out.println("Enter Command:");
input = new Scanner(System.in);
inputString = input.nextLine();
correct = false;
}
}while(!correct);
}
public static void salesSell(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
int index = 0;
String eventName = null;
int numberTickets = 0;
System.out.println("Sales Sell Mode");
System.out.println("What is the name of your event?");
Scanner input = new Scanner(System.in);
String inputString = input.nextLine();
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
try{
for(int i = 0; i < namesArray.length; i++) {
if(namesArray[i].equals(inputString)){
index = i;
}
}
eventName= namesArray[index];
numberTickets=ticketArray[index] ;
} catch (Exception e) {
System.out.println("Error: Event not found within file");
System.exit(1);
}
int event = inputString.length();
boolean charnumber = true;
do{
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
if(event< 0 || event >20){
System.out.println("No more than 20 characters allowed for name!");
System.out.println("Enter name:");
input = new Scanner(System.in);
inputString = input.nextLine();
event=inputString.length();
charnumber = false;
}
else{
charnumber = true;
}
} while(!charnumber);
System.out.println("How many tickets?");
input = new Scanner(System.in);
inputString = input.nextLine();
int digit;
while(true){
try {
digit = Integer.parseInt(inputString);
break;
}
catch(NumberFormatException e){
}
System.out.println("Please type a number!");
inputString = input.nextLine();
}
if( numberTickets - digit <0){
System.out.println("Illegal amount of tickets! Buy less ticket please.");
}
else{
int tickets = numberTickets - digit;
ticketArray[index]=tickets;
}
boolean dignumber = true;
do{
if(inputString.toUpperCase().equals("LOGOUT")){
logout( namesArray, ticketArray, fileCurrentEvents);
}
if(digit<0 || digit>8){
System.out.println("Only 8 tickets allowed to be sold!");
inputString = input.nextLine();
event=inputString.length();
dignumber = false;
digit= Integer.parseInt(inputString);
}
else{
dignumber= true;
}
}while(!dignumber);
}
public static boolean logout(String[] namesArray, int[] ticketArray,File fileCurrentEvents) {
FileWriter logoutFileWriter;
FileWriter currEventsFileWriter;
int numSpaces = 0;
try{
currEventsFileWriter = new FileWriter(fileCurrentEvents, true);
for(int i = 0; i < namesArray.length; i++ ) {
currEventsFileWriter.write(namesArray[i]);
numSpaces = 20 - (namesArray[i].length() + 4);
for(int j = 0; j < numSpaces; j++) {
currEventsFileWriter.write("_");
}
currEventsFileWriter.write(ticketArray[i]);
currEventsFileWriter.write(String.format("%n"));
}
} catch(IOException e) {
System.out.println("Rewriting Current Events File Error");
System.exit(1);
}
try {
logoutFileWriter = new FileWriter(fileOutput, true);
//Cycle through event trans file and write via filewriter
for(int i = 0; i < eventTrans.size(); i++ ) {
String transact = eventTrans.get(i).toString();
logoutFileWriter.write(transact);
logoutFileWriter.write(String.format("%n"));
}
// Signify end of file
logoutFileWriter.write("00 000000 00000");
logoutFileWriter.write(String.format("%n"));
logoutFileWriter.close();
fileOutput.createNewFile();
} catch(IOException e) {
System.out.println("Output File Error");
System.exit(1);
}
return true;
/*
for( int i = 0; i < 20; i++ ) {
System.out.println("");
}
System.out.println("Logged Out");
consoleInput();
*/
}
public static void main(String[] args){
try {
File fileCurrentEvents = new File(args[0]);
fileOutput = new File(args[1]);
// Read current events file for events & dates
FileReader fileRead = new FileReader(fileCurrentEvents);
BufferedReader buffRead = new BufferedReader(fileRead);
// Create strings for data in current events file
String currentLine;
String eventName;
Integer numberTickets;
List<Integer> numticket = new ArrayList<Integer>();
List<String> list = new ArrayList<String>();
int[] numarray= new int[numticket.size()];
String[] linesArray = list.toArray(new String[list.size()]);
// Cycle through current events file line by line
while((currentLine = buffRead.readLine()) != null) {
if (currentLine.equals("END_________________00000")){
break; // End of file
}
//Parse for event name & number of tickets
eventName = currentLine.substring(0, currentLine.lastIndexOf("_")).trim();
numberTickets = Integer.parseInt(currentLine.substring(currentLine.lastIndexOf
("_") + 1));
// Place event name and # tickets into data structure
// Add event name to event array list with same index as # tickets
// Parse int to get # tickets & add to arraylist for tickets with same index
while((eventName = buffRead.readLine()) != null){
list.add(eventName);
}
for (int i =0 ; i< list.size();i++){
linesArray[i]= list.get(i);
}
while((eventName = buffRead.readLine()) != null){
numticket.add(numberTickets);
}
for (int i =0 ; i< numticket.size();i++){
numarray[i]= numticket.get(i);
}
}
while(true) {
consoleInput(linesArray, numarray, fileCurrentEvents);
}
} catch (IOException e) {
System.out.println("File I/O Error"); //Print to console to signify error
e.printStackTrace();
System.exit(1);
}
}
}
If you are getting an ArrayOutOfBoundsIndexException at this line
File fileCurrentEvents = new File(args[0]);
Then it probably means the array (args) index (0) you are using is out of bounds in that it is higher than the size of the array.
If you have an array that looks like
[] //Zero entries
You can't get element 0 (the first item), because there are none.
So you must be passing in zero parameters when you run the code. Either when you run it at the command line, add the filename after it or change the build settings in your IDE (Eclipse, IntelliJ, Sublime) to add it to the build steps.
the error is being thrown on this line in the main method. File fileCurrentEvents = new File(args[0]);
Then your args is empty (e.g. you haven't run your program with any command line arguments, like a file). You could add a default, something like
File fileCurrentEvents = new File(args.length > 0 ? args[0] : "default.txt");
In your original code, line 763 is actually:
for (int i = 0 ; i< list.size(); i++){
linesArray[i] = list.get(i); //<--------------THIS ONE!
}
which can cause an ArrayIndexOutOfBoundsException when linesArray is shorter that list. This is happening because you instantiated linesArray earlier via
String[] linesArray = list.toArray(new String[list.size()]);
when list was empty, then added to list making it longer than your array.
Since the outer while-loop doesn't appear to use the linesArray in any other capacity, you can probably remove the above for-loop and, and place
linesArray = list.toArray(new String[list.size()]);
after the first while loop to create the appropriate array with all the elements.
Related
I'm trying to prompt the user to input the name a file they'd like to write to, create that .txt file and then write the qualifying lines of text into that file and save it. inside the do while, it seems to be skipping over the user input for the name of the file they'd like to save to, looping back around and then getting a FileNotFoundException, and it shouldn't even be looking for a file.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you
would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
do {
System.out.println("please enter a name for the file to write to
(end with .txt): ");
String out = user.nextLine(); //PROBLEM HERE! SKIPS USER INPUT
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0],
Integer.parseInt(elements[1]),
Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]),
Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost &&
bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
I just needed to skip a line before the loop began.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
user.nextLine(); //SOLUTION HERE
do {
System.out.println("please enter a name for the file to write to (end with .txt): ");
String out = user.nextLine();
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0], Integer.parseInt(elements[1]), Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]), Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost && bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
I am having issues with this program. I cannot get it to read more than the first line of code in the dictionary file. The dictionary file has around 22000 words. If someone could figure this out that would be great. I then could move along with the rest of my code.
public class Program2 {
private String[] array;
private String[] array2;
public void readFile(){
File f = new File ("dictionary.txt");
try {
Scanner input = new Scanner (f);
int i = 0;
array = new String [10];
while (i<array.length && input.hasNext()){
String word = input.nextLine();
String[] wordarray = word.split(" ");
array[i] = wordarray[i];
i++;
for (i = 0 ; i<array.length; i++)
System.out.println(array[i]);
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
public void readFile2(){
File f = new File ("oliver.txt");
try {
Scanner input = new Scanner (f);
int i = 0;
array = new String [10];
while (i<array.length && input.hasNext()){
String book = input.nextLine();
String[] bookarray = book.split(" ");
array2[i] = bookarray[i];
i++;
for (i = 0 ; i<array2.length; i++)
System.out.println(array2[i]);
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
public int binarysearchrecursive(double key, int first, int last) {
int mid;
if (first > last) {
return -1;
}
mid = (first + last) / 2;
if (key == wordArray[mid]) {
return mid;
} else if (key < wordArray[mid]) {
return binarysearchrecursive(key, first, mid - 1);
} else {
return binarysearchrecursive(key, mid + 1, last);
}
}
}
Ok, as someone commented, I think the problem is in the loops :P
This is what we want to do when we read all the words:
Create an ArrayList (better than Array, because you don't know exactly how many words you have in the text file).
Then create a double loop (1 while + 1 for) which goes through the file and stores strings in that ArrayList
The loops will go through all the lines, and then add every word in the line to the ArrayList (using the split on " " like you are trying).
So:
public ArrayList<String> readFile(){
File f = new File ("dictionary.txt");
ArrayList<String> array = new ArrayList<String>();
try {
Scanner input = new Scanner (f);
while (input.hasNext()){
//Goes through all lines
String line = input.nextLine();
//Array of all words:
String[] wordArray = line.split(" ");
//Goes through all words:
for(String str : wordArray){
array.add(str);
}
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
return array;
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am asked to do a program in which I have check if the names entered by the user is in the file I have created on my computer. I wrote the code and it does not show any compilation error but when it runs the boolean expression is always false. Please do help me out with this. The sample names on the boy names file is Martin and on the girl names is Emily.
import java.util.*;
import java.io.*;
public class nameSearch1
{
public boolean readingGirlNames () throws IOException
{
String[] girlNames = new String [200];
int i = 0;
File file = new File ("GirlNames.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i < girlNames.length )
{
girlNames [i] = inputFile.nextLine();
i++;
}
inputFile.close();
Scanner keyboard=new Scanner(System.in);
boolean girlName = false ;
nameSearch object4 = new nameSearch();
System.out.println(" Enter the Girl Name you wish to see : ");
String nameCheckGirl = keyboard.nextLine();
for ( int index = 0 ; index < 200 ; index ++ )
{
if( nameCheckGirl == girlNames[index])
{
girlName = true;
}
}
return girlName;
}
public boolean readingBoyNames () throws IOException
{
String[] boyNames = new String [200];
int i = 0;
File file = new File ("BoyNames.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i < boyNames.length )
{
boyNames [i] = inputFile.nextLine();
i++;
}
inputFile.close();
nameSearch object2 = new nameSearch ();
Scanner keyboard=new Scanner(System.in);
boolean boyName = false ;
System.out.println(" Enter the Boy Name you wish to see : ");
String nameCheckBoy = keyboard.nextLine();
for ( int index = 0 ; index < 200 ; index ++ )
{
if( nameCheckBoy == boyNames[index])
{
boyName = true;
}
}
return boyName;
}
public static void main(String[]Args)
{
Scanner keyboard = new Scanner(System.in);
nameSearch1 object1 = new nameSearch1 ();
try
{
System.out.println(" The search result for the Girl's name is : " + object1.readingGirlNames ());
}
catch (IOException ioe)
{
System.out.println(" Exception!!! ");
ioe.printStackTrace();
}
try
{
System.out.println(" The search result for the Boy's name is : " + object1.readingBoyNames ());
}
catch (IOException ioe)
{
System.out.println(" Exception!!! ");
ioe.printStackTrace();
}
}
}
Why you are comparing the String with == operator change with equals()
if( nameCheckBoy.equals(boyNames[index]))
{
boyName = true;
}
I had this program with which i have to check if the value the user entered is present in the text file i created in the source file. However it throws me an error everytime i try to call the method with IOException. Please help me out thanks.
import java.util.*;
import java.io.*;
public class chargeAccountModi
{
public boolean sequentialSearch ( double chargeNumber ) throws IOException
{
Scanner keyboard= new Scanner(System.in);
int index = 0;
int element = -1;
boolean found = false;
System.out.println(" Enter the Charge Account Number : " );
chargeNumber = keyboard.nextInt();
int[] tests = new int[18];
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i < tests.length )
{
tests [i] = inputFile.nextInt();
i++;
}
inputFile.close();
for ( index = 0 ; index < tests.length ; index ++ )
{
if ( tests[index] == chargeNumber )
{
found = true;
element = index;
}
}
return found;
}
public static void main(String[]Args)
{
double chargeNumber = 0;
chargeAccountModi object1 = new chargeAccountModi();
try
{
object1.sequentialSearch(chargeNumber);
}
catch (IOException ioe)
{
}
System.out.println(" The search result is : " + object1.sequentialSearch (chargeNumber));
}
}
After looking on your method sequentialSearch there is everythink ok. But try to change main:
But remember that in your Names.txt file you should have only numbers because you use scanner.nextInt();, so there should be only numbers or method will throw exeption InputMismatchException.
Check also path to Names.txt file you should have it on classpath because you use relative path in code File file = new File ("Names.txt"); Names.txt should be in the same folder.
public static void main(String[]Args)
{
double chargeNumber = 0;
chargeAccountModi object1 = new chargeAccountModi();
try
{
System.out.println(" The search result is : " + object1.sequentialSearch(chargeNumber));
}
catch (IOException ioe)
{
System.out.println("Exception!!!");
ioe.printStackTrace();
}
}
Few tips and suggestions:
First of all: Don't forget to close the Scanner objects! (you left one unclosed)
Second of all: Your main method is highly inefficient, you are using two loops, in the first one you read and store variables, in the second one you check for a match, you can do both at the same time (I've written an alternative method for you)
Third little thing: The variable "element" is not used at all in your code, I've removed it in the answer.
And last but not least: The file "Names.txt" needs to be located (since you've only specificied it's name) in the root folder of your project, since you mention an IOException, I figure that's what's wrong with the app. If your project is called Accounts, then it's a folder called Accounts with it's source and whatever else is part of your project, make sure the file "Accounts/Names.txt" exists! and that it is in the desired format.
import java.util.*;
import java.io.*;
public class ChargeAccountModi {
public boolean sequentialSearch(double chargeNumber) throws IOException {
Scanner keyboard= new Scanner(System.in);
int index = 0;
boolean found = false;
System.out.print("Enter the Charge Account Number: " );
chargeNumber = keyboard.nextInt();
int[] tests = new int[18];
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i < tests.length ) {
tests [i] = inputFile.nextInt();
i++;
}
inputFile.close();
for (index = 0 ; index < tests.length ; index ++ ) {
if (tests[index] == chargeNumber) {
found = true;
}
}
keyboard.close();
return found;
}
public boolean sequentialSearchAlternative(double chargeNumber) throws IOException {
Scanner keyboard= new Scanner(System.in);
boolean found = false;
System.out.print("Enter the Charge Account Number: " );
chargeNumber = keyboard.nextInt();
int tests = 18;
int i = 0;
File file = new File ("Names.txt");
Scanner inputFile = new Scanner(file);
while(inputFile.hasNext() && i<tests) {
if (inputFile.nextInt() == chargeNumber) {
found = true;
break;
}
i++;
}
inputFile.close();
keyboard.close();
return found;
}
public static void main(String[] args) {
double chargeNumber = 0;
ChargeAccountModi object1 = new ChargeAccountModi();
try {
System.out.println("The search result is : " + object1.sequentialSearch(chargeNumber));
} catch (Exception e) {
//Handle the exceptions here
//The most likely exceptions are:
//java.io.FileNotFoundException: Names.txt - Cannot find the file
//java.util.InputMismatchException - If you type something other than a number
e.printStackTrace();
}
}
}
I want to use boolean to search duplicate when I need to print out a list of names. So I need to write a program to read names in a text file and print it out to console. But the compiler doesn't work in this case. I don't know why? Can you guys help me?
import java.io.*;
import java.util.*;
public class NameSorter
{
public static void main(String[] args) throws Exception
{
BufferedReader cin, fin;
cin = new BufferedReader(new InputStreamReader(System.in));
//Description
System.out.println("Programmer: Minh Nguyen");
System.out.println("Description: This program is to sort names stored in a file.");
System.out.println();
//Get input
String fileName;
System.out.print("Enter the file's name: ");
fileName = cin.readLine();
fin = new BufferedReader(new FileReader(fileName));
int nNames = 0;
String[] name = new String[8];
//initialize array elements
for(int i=0; i<name.length;i++)
{
name[i]=" ";
}
// read text file
while(fin.ready())
{
String aName = fin.readLine();
String temp = aName;
boolean check;
if(temp.compareTo(" ")>0)
{
for(int i=0; i<name.length;i++)
{
if(temp.compareToIgnoreCase(name[i])==0)
{
check = true;
break;
}
}
}
if(nNames<name.length&& check = false)
{
name[nNames++] = temp;
}
}
}
fin.close();
// Sort the names aphabetically.
for(int i=0;i<nNames; i++)
{
int j;
for(j=i+1;j<nNames; j++)
{
if(name[i].compareToIgnoreCase(name[j])>0)
{
String temp = name[i];
name[i] = name[j];
name[j] = temp;
}
}
}
for(int i=0; i<name.length;i++)
System.out.println(name[i]);
}
}
Your code is :
if(nNames<name.length && check = false)
check= false , assigns false to check. To compare check with false you can use
check==falseor !check.
Depending on what you are trying to validate. The below code will remove the compilation error:
check == false //checks if check is false
Or,
if(nNames<name.length && (check = false))
// above is same as if(nNames<name.length && false) // which will always be false