The program compiles fine, but when I run it, I get an error, more specifically this:
java.lang.ArrayIndexOutOfBoundsException: 1
It is getting the error on:
String name = array[1];
I am not sure why.
This is the code with the problem:
infile = new Scanner(new FileReader("EmployeeData.TXT"));
while(infile.hasNext()){
String line = infile.nextLine();
String array[] = line.split(":");
String name = array[1];
String id = array[2];
double salary = Double.parseDouble(array[3]);
Employee e;
if (array[0].equals("s")){
e = new SalariedWorker(id, name, salary);}
else {
boolean overtime = Boolean.parseBoolean(array[4]);
if(overtime){
int maxhu = Integer.parseInt(array[5]);
e = new HourlyWorker(id, name, salary, maxhu);
}
else{
e = new HourlyWorker(id, name , salary);
}
}
company.add(e);
}
For reference, this is the rest of the program:
It reads this text file called "EmployeeData.TXT":
S Washington,George 000001 125000
H MacDonald,Ronald 386218 7.80 true 40
H Walton,Samuel 268517 8.21 false
H Thomas,David 131313 9.45 true 38
H Sanders,HarlandDavid 277651 8.72 false
S Baron,James 368535 310236
You're splitting on ":", and your text file:
S Washington,George 000001 125000
H MacDonald,Ronald 386218 7.80 true 40
H Walton,Samuel 268517 8.21 false
H Thomas,David 131313 9.45 true 38
H Sanders,HarlandDavid 277651 8.72 false
S Baron,James 368535 310236
does not have any such character. So each array will have size 1.
It makes no sense to split on a non-existing character, which makes me very curious why you would choose to use ":". Myself, I'd split on white space, "\\s+"
As an aside, this problem is very amenable to debugging either with a debugger or with some printlns:
while(infile.hasNext()){
String line = infile.nextLine();
System.out.println("Unsplit String: " + line);
String array[] = line.split(":");
System.out.println("Split String: " + java.util.Arrays.toString(array));
Either way, in the future when you have similar problems, find out just what your variables are holding at the time and place of the error, and that often will lead you to the origin of the problem and thereby to its solution.
It is breaking on these lines:
String line = infile.nextLine();
String array[] = line.split(":");
String name = array[1];
String id = array[2];
You are trying to assign the value of array[1] to name... But the array doesn't contain enough elements.
So say you have line = "hey" and you call split on line, your array will only be of length 1, since there is no ":" character to split on.
Related
So I'm creating a scanner to read off of a simple text file:
import java.io.*;
import java.util.Scanner;
public class Weather {
public static void main(String[] args) throws FileNotFoundException {
int a;
File weatherData = new File("C:\\Users\\taddi\\eclipse-workspace\\COS_160_ASSIGNMENT_10\\src\\PortlandWeather1941to2018.txt");
Scanner scnr = new Scanner(weatherData);
scnr.useDelimiter("//");
int totalCount = scnr.nextInt();// this reads the number at the beginning and uses it so I know how many times to run the loop
String throwAway1 = scnr.nextLine();//these statement are used to throw a way the rest of line 1, and all of line 2 and 3
String throwAway2 = scnr.nextLine();
String throwAway3 = scnr.nextLine();
int[] month = new int[totalCount];
int[] day = new int[totalCount];
int[] year = new int[totalCount];
int[] tmax = new int[totalCount];
int[] tmin = new int[totalCount];
for(a = 0; a < totalCount; a ++) {
month[a] = scnr.nextInt();
System.out.println(month[a]);
day[a] = scnr.nextInt();
System.out.println(day[a]);
year[a] = scnr.nextInt();
tmax[a] = scnr.nextInt();
tmin[a] = scnr.nextInt();
}
}
}
The first part of the text file is an integer I'm trying to read. For some reason, it only reads that integer when I comment out the scnr.useDelimiter("//"); line, otherwise I get an InputMismatchException
I'd love to just get rid of all the unnecessary words and slashes in the text file but that wouldn't satisfy the assignment. What's going wrong with the delimiter? How do I read the integer?
Your delimiter is a string, and it will not work in your use case the way you want.
I assume your sample data is like this (ignoring the header lines) ...
01/01/1941 38 25
01/02/1941 32 20
... so you are looking to get each number - the date elements and the tmax/tmin values - so a single delimiter character of '/' would only break up the date.
For example:
final String data =
"01/01/1941 38 25 \n"+
"01/02/1941 32 20 \n";
Scanner scnr = new Scanner(data);
scnr.useDelimiter("/");
while(scnr.hasNext()) {
System.out.println(scnr.next());
}
scnr.close();
outputs the following ...
01
01
1941 38 25
01
02
1941 32 20
showing that it splits on the date d/m/y slashes, but the year and tmax and tmin are bundled together.
Adjusting the scanner to use a Pattern delimiter allows us to split on the slashes and the spaces.
final String data =
"01/01/1941 38 25 \n"+
"01/02/1941 32 20 \n";
Scanner scnr = new Scanner(data);
scnr.useDelimiter(Pattern.compile("[/ ]+"));
while(scnr.hasNext()) {
System.out.println(scnr.next());
}
scnr.close();
}
giving the output I think you want:
01
01
1941
38
25
01
02
1941
32
20
However, note that in my example data I have trailing whitespace on each line and they are thus also returned as empty String tokens. If I was scanning for nextInt() I would get an java.util.InputMismatchException error. Depending on the exact formatting of your input you may need to cater for that.
I'm trying to get the values from a string builder , where I've converted the string builder to string to get values but not helping in fetching particular values.
My String builder output is,
SN: 00486 Mode: 1
Temp. 15.4 C
Fat............... 0.0%
SNF............... 0.4%
well further replaced with characters like,
String i = stringBuilder.toString();
i = i.replaceAll("[^\\d.]", "");
here my output is ,
004861.15.4...............0.0...............0.4
I expect my output to get only those values(digits) of Temp ,Fat and SNF ,how can i overcome those dots with my decimal points if I use any loops? please help me out anyone.
Expected Output,
15 (two digits) from Temp , 0.0 from Fat , and 0.4 from SNF.
try this though it`s an ugly piece of code
StringBuilder sb=new StringBuilder("SN: 00486 Mode: 1\n" +
"Temp. 15.4 C\n" +
"Fat............... 0.0%\n" +
"SNF............... 0.4%");
String str=sb.toString();
str=str.replace("%","").replace("\n"," ");
String[] splt=str.split(" ");
String fullStr="";
for (String st: splt ) {
try {
Double num=Double.parseDouble(st);
fullStr+=num.toString()+"\n";
}catch (Exception ex){
}
}
System.out.println(fullStr);
here all the number is separated. and you can separate your desired too.
if you need clarification please ask.
Well I've replaced the code by slight change as
i = i.replaceAll("[^\d]", "");
where i got the results as
00486117000240241040719
which i did altered it later by converting to int [] and got the positions of my values,thanks for your reply everyone.
it is better to read out the searched values with a pattern
Pattern snpat = Pattern.compile( "(?<info>[^\\d\\:\\.\\x20\r\n]+)(:?[\\.]+)(:?\\x20)?(?<value>[\\d\\.]+)[^\r\n][\r\n]?", Pattern.MULTILINE );
Matcher m = snpat.matcher( str );
String rslt = "";
while( m.find() ) {
String value = m.group( "value" );
if( m.group( "info" ).equals( "Temp" ) && value.indexOf( '.' ) >= 0 ) // ignore decimal places
value = value.substring( 0, value.indexOf( '.' ) );
rslt = String.join( rslt.isEmpty() ? "" : ", ", rslt, value + " from " + m.group( "info" ) );
}
System.out.println( rslt + '.' );
gives:
15 from Temp, 0.0 from Fat, 0.4 from SNF.
if You like a blank before the comma change the delimiter to " , "
I am trying to write a program that loads a movie data base file, and then splits up that information into the movie title, year, and all of the associated actors. I split up all of the info, but I am having issues converting the year, which is in a string, to an int. The format of the year string is (****) with the * being a year, such as 1999. When I try to use parse I get a number format exception. I have tried replacing the parentheses, but it just gave me more errors! Any ideas?
public class MovieDatabase {
ArrayList<Movie> allMovie = new ArrayList<Movie>();
//Loading the text file and breaking it apart into sections
public void loadDataFromFile( String aFileName) throws FileNotFoundException{
Scanner theScanner = new Scanner(aFileName);
theScanner = new Scanner(new FileInputStream("cast-mpaa.txt"));
while(theScanner.hasNextLine()){
String line = theScanner.nextLine();
String[] splitting = line.split("/" );
String movieTitleAndYear = splitting[0];
int movieYearIndex = movieTitleAndYear.indexOf("(");
String movieYear = movieTitleAndYear.substring(movieYearIndex);
System.out.println(movieYear);
//this is where I have issues
int theYear = Integer.parseInt(movieYear);
String movieTitle = movieTitleAndYear.substring(0, movieYearIndex);
ArrayList<Actor> allActors = new ArrayList<Actor>();
for ( int i = 1; i < splitting.length; i++){
String[] names = splitting[i].split(",");
String firstName = names[0];
Actor theActor = new Actor(firstName);
ArrayList<Actor> allActor = new ArrayList<Actor>();
allActor.add(theActor);
}
Movie theMovie = new Movie(movieTitle, theYear, allActors);
allMovie.add(theMovie);
}
theScanner.close();
}
output:
(1967)
Here is the errors I am getting:
Exception in thread "main" java.lang.NumberFormatException: For input string: "(1967)"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:481)
at java.lang.Integer.parseInt(Integer.java:527)
at MovieDatabase.loadDataFromFile(MovieDatabase.java:27)
You have brackets around the numbers. You could either correct your file or you could remove brackets using:
String str = "(1967)";
System.out.println(str.substring(1, str.length()-1));
Output:
1967
In your code, you used:
int movieYearIndex = movieTitleAndYear.indexOf("(");
String movieYear = movieTitleAndYear.substring(movieYearIndex);
So if my movieTitleAndYear string is "hi (1947)", indexOf will give me index of "(" as 3 and substring will start reading string from index 3 which includes "(". One way you could avoid opening bracket is to change your substring line to:
String movieYear = movieTitleAndYear.substring(movieYearIndex + 1);//but still you have closing bracket.
If you are sure it's always going to be of four digit, then you could do something like:
String movieYear = movieTitleAndYear.substring(movieYearIndex + 1, movieYearIndex + 5);
You need to add indexof for ")".
Code snippet:
int movieYearOpenBracesIndex = movieTitleAndYear.indexOf("(");
int movieYearCloseBracesIndex = movieTitleAndYear.indexOf(")");
String movieYear = movieTitleAndYear.substring(movieYearOpenBracesIndex + 1, movieYearCloseBracesIndex);
System.out.println(movieYear);
This will give the exact year. e.g. 1967
Your substring call currently gets a year enclosed by brackets, e.g., (1967). You can avoid this by calling the substring variant that accepts an endIndex, and just get the year's four digits:
String movieYear =
movieTitleAndYear.substring(movieYearIndex + 1, // to get rid of "("
movieYearIndex + 5 // to get rid of ")"
);
I have list of text files I need to read a specific string from, which is always preceded by the string "SWEUserName=". I have been able to print the entire line from the log, but not just the string I need. I do want to print the line number, just not the whole line
So far this is what I've got:
public static String [] openFile() throws FileNotFoundException, IOException{
String searchTech = "SWEUserName=";
int s;
String foundTech = "";
File logs = new File("C:\\Users\\wfedric\\Desktop\\GD\\Java\\Learning\\app\\src\\main\\java\\com\\fedrictechnologies\\learning\\FSDS2.txt");
Scanner scnr = new Scanner(logs);
int lineNumber = 1;
while(scnr.hasNextLine()){
String line = scnr.nextLine();
lineNumber++;
if(line.contains(searchTech)){
s = 10;
foundTech = lineNumber +" :"+ searchTech + s;
System.out.println(foundTech);
System.out.println(line);
}else;
}
return null;
}
I know I am missing something, but I can't for the life of me figure how to count the next 10 characters. I realize at it stands in my code, I am simply printing the Line number followed by my searchTech variable, and the number 10.
I need s to hold on to the 10 characters following searchTech. Perhaps an array is the best way? Just not sure :(
With the above code, I have the following output, which I should expect:
141 :SWEUserName=10
[09/04/14 EDT:8:15:48 AM- INFO- MASC1050141409832948329] - [ HomePageURL ] - ThinClient Home Page URL - https://wls.rio.directv.com/wpservsm_enu/start.swe?SWECmd=ExecuteLogin&SWENeedContext=false&SWEUserName=masc105014&SWEPassword=%5BNDSEnc-D%5Dji%2Fic25k%2FTB%2Fy7mqG2kcb2ndd1S3hgWC8Rfa4e1DvtwKWMGQmTzngA%3D%3D&
143 :SWEUserName=10
[09/04/14 EDT:8:15:48 AM- INFO- ] - [ webServiceRequest ] - Web service Call - RetryCounter: 0, URL: https://wls.rio.directv.com/wpservsm_enu/start.swe?SWECmd=ExecuteLogin&SWENeedContext=false&SWEUserName=masc105014&SWEPassword=%5BNDSEnc-D%5Dji%2Fic25k%2FTB%2Fy7mqG2kcb2ndd1S3hgWC8Rfa4e1DvtwKWMGQmTzngA%3D%3D&, Type: GET
1st and 3rd lines are the General format I want, 2nd and 4th lines are where I get stuck returning the specific values after searchTech.
SOLUTION (During this process, I played with the indexOf method to include the date, and left it there)
public class techMatching {
static int s;
static int d;
static String sTech;
static String dTech;
public static String [] openReadFile() throws FileNotFoundException, IOException{
String searchTech = "SWEUserName=";
String foundTech;
File logs = new File("C:\\FSDS2.txt");
Scanner scnr = new Scanner(logs);
int lineNumber = 1;
while(scnr.hasNextLine()){
String line = scnr.nextLine();
lineNumber++;
if(line.contains(searchTech)){
s = line.indexOf(searchTech);
sTech = line.substring(s+12,s+22);
d = line.indexOf("[");
dTech = line.substring(1, 22);
foundTech = lineNumber +": "+ "(" + dTech + ")" + "|"+ sTech.toUpperCase();
System.out.println(foundTech);
}else;
}
return null;
}
Which returned the expected output:
141: (09/04/14 EDT:8:15:48 )|MASC105014
143: (09/04/14 EDT:8:15:48 )|MASC105014
And so on.
"" ""
I suggest you look at the methods available in the String class. Using indexOf(searchTech), you know where in the line the "SWEUserName=" is. Using substring, you can get a String consisting of part of the line.
So I have a string which is from a text file, essentially the text file is just 5 lines which read:
x=1
y=15
z=128
topx=100
leftx=150
label= this is a test
I am able to get the split to work once which separates via the '=' sign, but when I try to split the string again by \n nothing works, I have tried using "\r?\n", line.Separator etc. but the string value always stays the same, basically the 5 lines without the characters before the = sign. How would I pull out the individual lines to assign variables to?
Here is the code I have, basically the println is to try and see if I can get the first value '1' to list separate from the rest of the lines.
public static void main(String[] a) {
15 draw d = new draw();
16 Read r = new Read();
17 String m = r.doRead("variables.txt");
18
19 String[] ss = new String[5];
20 ss = m.split("\n");
21
22 String[] kv= new String[5];
23 for (int i=0; i<ss.length; i++) {
24 kv = ss[i].split("=");
25 String eol = System.getProperty("line.seperator");
26 String test = kv[1];
27 String[] split = new String[5];
28 split = test.split("\n");
29
30
31
32
33 String first = split[0];
34 //String second = split[1];
35 //String third = split[2];
36 //String fourth = split[3];
37 //String fifth = split[4];
38 System.out.println(first);
39 }
When every line looks like
x=1 y=15 z=128 topx=100 leftx=150 label= this is a test
you should first split at a whitespace to get 5 parts (x=1, y=15, ...) and then at = to get the "key" and "value" part of each part.
check this out:
String s = "x=1\ny=15\nz=128\ntopx=100\nleftx=150\nlabel= this is a test";
String[] ss = s.split("\n");
System.err.println( Arrays.asList(ss[0].split("=")) );