I am working on a simple project in which a tab delimited text file is read into a program.
My problem:
When reading the text file there are regularly empty data spaces. This lack of data is causing an unexpected output. For lines that do not have data in the token[4] position all data read is ignored and "4" is displayed when I run a System.out.println(Just a test that the data is being read properly). When I incorporate a value in the token[4] position the data reads fine. It is not acceptable that I input a value in the token[4] position. See below for file and code.
2014 Employee Edward Rodrigo 6500
2014 Salesman Patricia Capola 5600 5000000
2014 Executive Suzy Allen 10000 55
2015 Executive James McHale 12500 49
2015 Employee Bernie Johnson 5500
2014 Salesman David Branch 6700 2000000
2015 Salesman Jonathan Stein 4600 300000
2014 Executive Michael Largo 17000 50
2015 Employee Kevin Bolden 9200
2015 Employee Thomas Sullivan 6250
My code is:
// Imports are here
import java.io.*;
import java.util.*;
public class EmployeeData {
public static void main(String[] args) throws IOException {
// Initialize variables
String FILE = "employees.txt"; // Constant for file name to be read
ArrayList<Employee> emp2014; // Array list for 2014 employees
ArrayList<Employee> emp2015; // Array list for 2015 employees
Scanner scan;
// Try statement for error handling
try {
scan = new Scanner(new BufferedReader(new FileReader(FILE)));
emp2014 = new ArrayList();
emp2015 = new ArrayList();
// While loop to read FILE
while (scan.hasNextLine()) {
String l = scan.nextLine();
String[] token = l.split("\t");
try {
String year = token[0];
String type = token[1];
String name = token[2];
String monthly = token[3];
String bonus = token[4];
System.out.println(year + " " + type + " " + name + " " + monthly + " " + bonus);
} catch (Exception a) {
System.out.println(a.getMessage());
}
}
} catch(Exception b) {
System.out.println(b.getMessage());
}
}
}
The output I receive for lines with "Employee" returns in an unexpected way.
Output:
run:
4
2014 Salesman Patricia Capola 5600 5000000
2014 Executive Suzy Allen 10000 55
2015 Executive James McHale 12500 49
4
2014 Salesman David Branch 6700 2000000
2015 Salesman Jonathan Stein 4600 300000
2014 Executive Michael Largo 17000 50
4
4
BUILD SUCCESSFUL (total time: 0 seconds)
I tried to use an if-then to test for null value in token[4] position but that didn't really help me. I've done quite a bit of searching with no success.
I am still very new to the programming world, so please pardon my coding inefficiencies. Any support and general feedback to improve my skills is greatly appreciated!
Thank you,
Bryan
Java Devil is right that the underlying issue because of an ArrayOutOfBoundsException. But it's also worth exploring why you didn't see that. As we discussed in the comments your "Try statement for error handling" is in fact not handling your errors at all, instead it is suppressing them, which is generally a poor plan as it allows your program to continue running even after your assumption (that it works correctly) has been violated.
Here's a slightly cleaned up version of your code. The underlying problem that causes the ArrayOutOfBoundsException is still there, but the issue would be immediately apparent if you'd structured your code this way instead. There's a few comments calling out issues inline.
public class EmployeeData {
// constants should be declared static and final, and not inside main
private static final String FILE = "employees.txt";
// If you have an exception and you don't know how to handle it the best thing
// to do is throw it higher and let the caller of your method decide what to do.
// If there's *nothing* you want to do with an exception allow main() to throw
// it as you do here; your program will crash, but that's a good thing!
public static void main(String[] args) throws IOException {
// Notice the <> after ArrayList - without it you're defining a "raw type"
// which is bad - https://stackoverflow.com/q/2770321/113632
ArrayList<Employee> emp2014 = new ArrayList<>();
ArrayList<Employee> emp2015 = new ArrayList<>();
// A try-with-resources block automatically closes the file once you exit the block
// https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
try (Scanner scan = new Scanner(new BufferedReader(new FileReader(FILE)))) {
while (scan.hasNextLine()) {
String l = scan.nextLine();
String[] token = l.split("\t");
// The code below this line assumes that token has at least five indicies;
// since that isn't always true you need to handle that edge case before
// accessing the array indicies directly.
String year = token[0];
String type = token[1];
String name = token[2];
String monthly = token[3];
String bonus = token[4];
System.out.println(year + " " + type + " " + name + " " + monthly + " " + bonus);
}
}
}
}
This is happening because you are actually getting an ArrayOutOfBoundsException and the message for that is '4'. Because the index of 4 is greater than the length of the array. You should put in your catch statement b.printStackTrace() as this will give you greater details when ever the caught exception occurs.
You can get around this by adding the following:
String bonus = "";
if(token.length > 4)
bonus = token[4];
Related
I've only been coding for a couple months so I'm still fairly new.
I'm writing a program using Java in Eclipse IDE that reads a file containing data about the changing popularity of various baby names over time and displays the data about a particular name (which is entered via keyboard by the user). Each line of the file stores a name followed by integers representing the name's popularity in each decade: 1900, 1910, 1920, and so on. My program prompts the user for a name, searchs the file for that name, and displays the data for that name from the file to the screen.
Example of data from txt file: Sam 58 69 99 131 168 236 278 380 467 408 466
Example of what should be displayed on screen:
Statistics on name "Sam"
1900: 58
1910: 69
1920: 99
1930: 131
...
This is my program:
public class fileAndExceptionHanding {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
FileInputStream fileByteStream = null;
Scanner inFS = null;
String userName = "";
String fileName = "";
File file = new File("names.txt");
List<Integer> numNamesOfYear = new ArrayList<Integer>();
boolean repeatSearch = true;
boolean repeatNameSearch = true;
int startingYear = 1900;
int yearCounter = startingYear;
char userKey;
fileByteStream = new FileInputStream("names.txt");
inFS = new Scanner(fileByteStream);
if (!file.exists()) {
file.createNewFile();
}
System.out.println("This program allows you to search through the data from the Social
Security Administration to see how popular a particular name has been since 1900.");
do {
System.out.println("Name? ");
userName = keyboard.next();
do {
while (!(fileName.equals(userName)) && inFS.hasNextLine()) {
fileName = inFS.next();
}
if (!(fileName.equals(userName))) {
System.out.println("Error! Name was not found. Please enter another name for our
system to search.");
userName = keyboard.next();
repeatNameSearch = true;
}
else {
repeatNameSearch = false;
}
} while (repeatNameSearch);
while (inFS.hasNextInt()) {
numNamesOfYear.add(inFS.nextInt());
}
System.out.println("Statistics on name " + "\"" + userName + "\"");
yearCounter = startingYear;
for (int i = 0; i < numNamesOfYear.size(); ++i) {
System.out.println(" " + yearCounter + ": " + numNamesOfYear.get(i));
yearCounter += 10;
}
numNamesOfYear.clear();
System.out.println("If you would like to search another name for popularity data,
please enter \"y\" to continue.");
System.out.println("If you wish to exit, please press any other key.");
userKey = keyboard.next().charAt(0);
if (!(userKey == 'y' || userKey == 'Y')) {
repeatSearch = false;
}
}while (repeatSearch);
fileByteStream.close(); // Closing file and input stream.
keyboard.close(); // Closing keyboard scanner.
inFS.close(); // Closing file scanner.
}
}
My program is running perfectly at first until the prompt for the user to enter "y" to continue or any other key to exit. When I enter "Y/y" and enter another name to search, my program doesn't repeat the name search and instead displays my "error invalid name, please enter a different name to search" message even though the name I entered is valid and inside the txt file.
Example of another name and data within the txt file that I tried to repeat search for:
Abbey 0 0 0 0 0 0 0 0 537 451 428
If you would like to search another name for popularity data, please enter "y"
to continue.
If you wish to exit, please press any other key.
y
Name?
Abbey
Error! Name was not found. Please enter another name for our system to search.
Entering "Sam" gives me correct data but if I press y to repeat loop and enter "Sam" again, it prints the following (Skips year data output):
This program allows you to search through the data from the Social Security Administration to see how popular a particular name has been since 1900.
Name?
Sam
Statistics on name "Sam"
1900: 58
1910: 69
1920: 99
1930: 131
1940: 168
1950: 236
1960: 278
1970: 380
1980: 467
1990: 408
2000: 466
If you would like to search another name for popularity data, please enter "y"
to continue.
If you wish to exit, please press any other key.
y
Name?
Sam
Statistics on name "Sam"
If you would like to search another name for popularity data, please enter "y"
to continue.
If you wish to exit, please press any other key.
I assume the problem lies somewhere within my loops, however it's proving difficult for me to find.
Any help or advice on where my looping problem lies would be greatly appreciated!
Thank you in advance.
I was wondering if I could have some help with this NumberFormatException with code using a text input.
The result should be it being able to run properly and be able to first put 50 strings into the hashTable and then remove 10 afterwards.
I have tried placing the removeLine.next() inside a String datatype and then placing the String back inside the Integer.parseInt which didn't work.
Here is the class:
import java.io.*;
import java.util.*;
public class hashTest {
public static void main(String args[]) throws FileNotFoundException {
HashTable hashTable = new HashTable();
Scanner insert = new Scanner(new File("data1.txt"));
while(insert.hasNext()) {
String line = insert.nextLine();
Scanner insertLine = new Scanner(line);
insertLine.next();
insertLine.next();
int index = Integer.parseInt(insertLine.next());
String data = insertLine.nextLine();
hashTable.put(index, data);
}
Scanner remove = new Scanner(new File("data2.txt"));
while(remove.hasNext()) {
String line = remove.nextLine();
Scanner removeLine = new Scanner(line);
removeLine.next();
removeLine.next();
int index = Integer.parseInt(removeLine.next());
hashTable.remove(index);
}
}
}
data1.txt :
003 : 68682774 MALIK TULLER
004 : 24248685 FRANCE COELLO
005 : 25428367 DUSTY BANNON
006 : 79430806 MELVINA CORNEJO
007 : 98698743 MALIA HOGSTRUM
008 : 20316453 TOMASA POWANDA
009 : 39977566 CHONG MCOWEN
010 : 86770985 DUSTY CONFER
011 : 92800393 LINNIE GILMAN
012 : 31850991 WANETA DEWEES
013 : 81528001 NEAL HOLSTEGE
014 : 46531276 BRADLY BOMBACI
data2.txt :
92800393 LINNIE GILMAN
86770985 DUSTY CONFER
31850991 WANETA DEWEES
46531276 BRADLY BOMBACI
25428367 DUSTY BANNON
68682774 MALIK TULLER
18088219 PENNY JOTBLAD
48235250 KENNITH GRASSMYER
20316453 TOMASA POWANDA
54920021 TYSON COLBETH
22806858 LAVERNE WOLNIK
32244214 SHEMEKA HALLOWAY
81528001 NEAL HOLSTEGE
24248685 FRANCE COELLO
23331143 JUSTIN ADKIN
79430806 MELVINA CORNEJO
59245514 LESLEE PHIFER
64357276 SCOT PARREIRA
50725704 GENARO QUIDER
52298576 AUDIE UNCAPHER
54657809 MARTY ENOCHS
54526749 TOBI HEATLEY
24903965 ALONSO GILSTAD
84936051 DEONNA STRAZZA
62522327 AHMAD THAYER
90572271 ELIJAH METEVIER
88999386 ISMAEL ELKAN
NumberFormatExceptions with Integer.parseInt() are most often caused by attempting to read something into an int that is not actually an int. Try printing each line as it is read in. If you have a line that is not purely an int (e.g., Hello123), you will get this exception with Integer.parseInt(). A cleaner debugging method (and better coding practice) would be to catch the exception and print the problematic line. You will probably see right away what's causing the issue. When reading text input from anywhere, it's never good to assume that the data is of the format you're expecting.
When your input contains data other than the int values you need, you can read each line's values into an array and extract the proper value(s). Here's an example of how you might extract the values from a single line in your second data file. Keep in mind that this still makes assumptions about the input format and therefore, is not completely fool-proof.
try {
// Split the line by whitespace, saving the values into an array
String[] singleLineVals = someLine.split("\\s+");
// Extract the first value
int firstValue = Integer.parseInt(singleLineVals[0]);
} catch (NumberFormatException nfe) {
// Handle the exception
}
I'm trying to create custom chatbot using program ab. below is the class i've created
public class Test{
public static void main(String args[]){
String botname="super";
String path="F:/Jars/NLP";
Bot bot = new Bot(botname, path);
Chat chatSession = new Chat(bot);
Scanner sc=new Scanner(System.in);
String request = "Hello";
do{
request = sc.next();
String response = chatSession.multisentenceRespond(request);
System.out.println(response);
}while(!request.equals("exit"));
}}
When i run this class, I get following output
Name = super Path = F:/Jars/NLP/bots/super
c:/ab
F:/Jars/NLP/bots
F:/Jars/NLP/bots/super
F:/Jars/NLP/bots/super/aiml
F:/Jars/NLP/bots/super/aimlif
F:/Jars/NLP/bots/super/config
F:/Jars/NLP/bots/super/logs
F:/Jars/NLP/bots/super/sets
F:/Jars/NLP/bots/super/maps
Preprocessor: 0 norms 0 persons 0 person2
Get Properties: F:/Jars/NLP/bots/super/config/properties.txt
Loading AIML Sets files from F:/Jars/NLP/bots/super/sets
Loading AIML Map files from F:/Jars/NLP/bots/super/maps
AIML modified Thu Jun 15 19:03:38 IST 2017 AIMLIF modified Thu Jun 15 19:32:05 I
ST 2017
No deleted.aiml.csv file found
No deleted.aiml.csv file found
Loading AIML files from F:/Jars/NLP/bots/super/aimlif
Reading Learnf file
Loaded 2 categories in 0.015 sec
--> Bot super 2 completed 0 deleted 0 unfinished
Setting predicate topic to unknown
I like Mango
normalized = I
No match.
writeCertainIFCaegories learnf.aiml size= 0
I have no answer for that.
normalized = like
No match.
writeCertainIFCaegories learnf.aiml size= 0
I have no answer for that.
normalized = Mango
No match.
writeCertainIFCaegories learnf.aiml size= 0
I have no answer for that.
my AIML file
star.aiml
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml>
<category>
<pattern>I LIKE *</pattern>
<template>
I too like <star/>.
</template>
</category>
<category>
<pattern>A * IS A *</pattern>
<template>
How <star index = "1"/> can not be a <star index = "2"/>?
</template>
</category>
</aiml>
.csv file
star.aiml.csv
0,I LIKE *,*,*,I too like <star/>.,star.aiml
0,A * IS A *,*,*,How <star index = "1"/> can not be a <star index = "2"/>?,star.aiml
when i run the Main class like below it works but when i run custom class it doesn't.
java -cp lib/Ab.jar Main bot=super action=chat trace=false
Can anybody please let me know what is wrong with custom class
Finally I got the answer.
import java.util.Scanner;
import org.alicebot.ab.AB;
import org.alicebot.ab.Bot;
import org.alicebot.ab.Chat;
import org.alicebot.ab.PCAIMLProcessorExtension;
import org.alicebot.ab.utils.IOUtils;
public class Test_001 {
public static void main(String args[]){
String botname="super";
String path="F:/Jars/NLP";
org.alicebot.ab.AIMLProcessor.extension = new PCAIMLProcessorExtension();
Bot bot = new Bot(botname, path,"chat");
Chat chatSession = new Chat(bot);
AB.ab(bot);
Scanner sc=new Scanner(System.in);
String request = "Hello";
do{
request = IOUtils.readInputTextLine();
String response = chatSession.multisentenceRespond(request);
System.out.println(response);
}while(!request.equals("exit"));
}
}
I have string looks like this
123_NAME
MONTHLY
MONTHLY 53_January_2013
MONTHLY 54_February_2013
MONTHLY 55_March_2013
MONTHLY 56_April_2013
QUARTERLY
QUARTERLY 51_First_Quarter_2013
QUARTERLY 54_Second_Quarter_2013
QUARTERLY 57_Third_Quarter_2013
QUARTERLY 60_Fourth_Quarter_2013
Above is the List of files I am pulling from Directory and printing as a list.The files are located in local machine in the same directory structure as above. For Example Folder Monthly wil contain files with names jan,feb,mar etc and folder quarterly contains files with name 1quarte,2nd quarter etc.
I need to append the list of files which I am printing like this
Monthly
Jan 2013
Feb 2013
Continue....
Quarterly
first Quarter 2013
second quarter 2013
Continue...
Below is part of my code will give some Idea
Iterator<String> iterator=listFilesForFolder(folder, startWithDirectory, filesArray).iterator();
while(iterator.hasNext()){
String listofFiles=iterator.next();
StringBuilder str=new StringBuilder(listofFiles);
String test=str.substring(str.indexOf("/")+1);
System.out.println(test);
In your while loop, you could try something like this if you don't mind hard-interpretation.
String[] split = listOfFiles.split("_")
if(split.length > 1) {
if(split[0].contains("MONTHLY")) { //unique case
System.out.println(split[1].substring(0, 3) + " " + split[2]);
}
else {
for(int i = 1; i < split.length(); i++) {
System.out.print(split[i] + " ");
}
System.out.println("");
}
}
else {
System.out.println("\n" + listOfFiles + "\n");
}
I guess you want output in the following way (in the same line):
Folder > file1, file2, ...
instead of (in new lines):
Folder
File1
File2
If that's the case, did you know you have System.out.print() that does not print a new line at the end?
Try tweaking it, to insert the required separators (like commas and angular bracket).
Also since you ARE using StringBuilder, it has an append() method that you can use. However, I see no reason for using StringBuilder for str instead of using it for test.
I'm a Java noob so please bear with me.
I'm having an issue with a java project I have to complete. We have to sort a list of 10,000 customer transactions, pick the top three customers that spent the most, then give five random customers gift cards, five of them starting at $20 and ending at $100, increasing in $20 increments. So far I have the following:
public static void main(String[] args) throws IOException {
BufferedReader inputStream = new BufferedReader (new FileReader("Transactions.txt"));
BufferedWriter outputStream = new BufferedWriter (new FileWriter("output.txt"));
Scanner trans = null;
try {
trans = new Scanner(new BufferedReader(new FileReader("Transactions.txt")));
trans.useDelimiter("s*");
while (trans.hasNext()) {
System.out.println(trans.next());
}
}
finally {
if (trans !=null) {
trans.close();
I'm confused as to how I would put this information into an OrderedList so it'll sort them in ascending order according to the amount they spent.
EDIT: Here are some lines from the transaction.txt file:
Order # Date First name Middle Initial Last name Address City State Zip Email Transaction Amount
1 8/26/2012 Kristina H Chung 947 Martin Ave. Muncie CA 46489 khchung#business.com $593
2 11/16/2012 Paige H Chen 15 MainWay Rd. Dallas HI 47281 phchen#business.com $516
3 11/10/2012 Sherri E Melton 808 Washington Way Brazil CA 47880 semelton#business.com $80
4 9/20/2012 Gretchen I Hill 56 Washington Dr. Atlanta FL 47215 gihill#business.com $989
5 3/11/2012 Karen U Puckett 652 Maplewood Ct. Brazil FL 46627 kupuckett#business.com $826
My apologies, but I have no idea how to make this look neat.