Below contents are available in a text file. I want to extract data (Name, age, Working experience, position). How can I do? I tried to extract using java stringtokenizer and split function. But cannot extract data.
Name Age Working Experience Position
John 23 10 Team Leader
Christian Elverdam 27 7 Director
Niels Bye Nielsen 59 16 Composer
Rajkumar Hirani 40 23 Director
Vidhu Vinod Chopra 58 21 Screenplay
Expected ouput:
John |23|10|Team Leader|
Christian Elverdam|27|7 |Director |
Niels Bye Nielsen |59|16|Composer |
Rajkumar Hirani |40|23|Director |
Vidhu Vinod Chopra|58|21|Screenplay |
Don't use StringTokenizer:
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
You can use split() if you split on 2 or more spaces: split(" {2,}")
Demo
String input = "Name Age Working Experience Position \n" +
"John 23 10 Team Leader \n" +
"Christian Elverdam 27 7 Director \n" +
"Niels Bye Nielsen 59 16 Composer\n" +
"Rajkumar Hirani 40 23 Director \n" +
"Vidhu Vinod Chopra 58 21 Screenplay\n";
List<String[]> rows = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new StringReader(input))) {
in.readLine(); // skip header line
for (String line; (line = in.readLine()) != null; ) {
rows.add(line.split(" {2,}"));
}
}
for (String[] row : rows)
System.out.println(Arrays.toString(row));
Output
[John, 23, 10, Team Leader]
[Christian Elverdam, 27, 7, Director]
[Niels Bye Nielsen, 59, 16, Composer]
[Rajkumar Hirani, 40, 23, Director]
[Vidhu Vinod Chopra, 58, 21, Screenplay]
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I am trying to read from a text file that has 20 lines and supposed to store them into an array and assign them a variable, firstname lastname and grade. Because I have to output them as last name, firstname and grade, I decided to use tokens but somehow I get this error: java.lang.ArrayIndexOutOfBoundsException: 1
public static void main(String[] args) throws IOException {
int numberOfLines = 20;
studentClass[] studentObject = new studentClass[numberOfLines];
readStudentData(studentObject);
}
public static void readStudentData(studentClass[] studentObject)throws {
//create FileReader and BufferedReader to read and store data
FileReader fr = new FileReader("/Volumes/PERS/Data.txt");
BufferedReader br = new BufferedReader (fr);
String line = null;
int i = 0;
//create array to store data for firstname, lastname, and score
while ((line = br.readLine()) != null){
String[] stuArray = line.split(" ");
String stuFName = stuArray[0];
String stuLName = stuArray[1];
int score = Integer.parseInt(stuArray[2]);
studentObject[i] = new studentClass (stuFName, stuLName, score);
i++;
}
br.close();
for(i = 0; i<studentObject.length; i++){
System.out.print(studentObject[i].getStudentFName());
}
}
The error that I get is specifically this line:
String stuLName = stuArray[1];
Here is the text file:
Duckey Donald 85
Goof Goofy 89
Brave Balto 93
Snow Smitn 93
Alice Wonderful 89
Samina Akthar 85
Simba Green 95
Donald Egger 90
Brown Deer 86
Johny Jackson 95
Greg Gupta 75
Samuel Happy 80
Danny Arora 80
Sleepy June 70
Amy Cheng 83
Shelly Malik 95
Chelsea Tomek 95
Angela Clodfelter 95
Allison Nields 95
Lance Norman 88
I think at the last line of your file you have white spaces. make sure last line hast no white space like space or tab.
First, next time you should include the import and output also in your code
for us to easy to fix it, and one more thing, the Class name should be
StudentClass, not studentClass, it have to me different with methods.
Second, I can't test your code without your studentClass ... So I only can guess it:
Consider 1: The text file have one more line (with white space) >> Impossible because String test = " "; test.split(" ")[0] == null;
Consider 2: Your text file has error, to test it, I suggest you to add
System.out.println(line + ".") after while ((line = br.readLine()) != null){
to test it, believe me, you will receive the last line because it's bloged;
I am trying to take a text file which has a list of peoples first and last names with age and rearrange it so the console output would go from 46 Richman, Mary A. to Mary A. Richman 46. However, in my attempt to do so I have ran into issues (shown below) and I don't understand exactly why they're occurring (it was much worse earlier).
I'd really appreciate the assistance!
Text File:
75 Fresco, Al
67 Dwyer, Barb
55 Turner, Paige
108 Peace, Warren
46 Richman, Mary A.
37 Ware, Crystal
83 Carr, Dusty
15 Sledd, Bob
64 Sutton, Oliver
70 Mellow, Marsha
29 Case, Justin
35 Time, Justin
8 Shorts, Jim
20 Morris, Hugh
25 Vader, Ella
76 Bird, Earl E.
My Code:
import java.io.*;
import java.util.*;
public class Ex2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner(new File("people.txt"));
while (input.hasNext()) { // Input == people.txt
String line = input.next().replace(",", "");
String firstName = input.next();
String lastName = input.next();
int age = input.nextInt();
System.out.println(firstName + lastName + age);
}
}
}
Bad Console Output: (How is it throwing an Unknown Source Error?)
Fresco,Al67
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Ex2.main(Ex2.java:11)
Target Console Output:
Al Fresco 75
Barb Dwyer 67
Paige Turner 55
Warren Peace 108
Mary A. Richman 46
Crystal Ware 37
Dusty Carr 83
Bob Sledd 15
Oliver Sutton 64
Marsha Mellow 70
Justin Case 29
Justin Time 35
Jim Shorts 8
Hugh Morris 20
Ella Vader 25
Earl E. Bird 76
This will make sure the first name includes the middle initial
while (input.hasNext())
{
String[] line = input.nextLine().replace(",", "").split("\\s+");
String age = line[0];
String lastName = line[1];
String firstName = "";
//take the rest of the input and add it to the last name
for(int i = 2; 2 < line.length && i < line.length; i++)
firstName += line[i] + " ";
System.out.println(firstName + lastName + " " + age);
}
You can avoid the issue and simplify the logic by actually reading with input.nextLine() as shown in the below code with comments:
while (input.hasNextLine()) {
String line = input.nextLine();//read next line
line = line.replace(",", "");//replace ,
line = line.replace(".", "");//replace .
String[] data = line.split(" ");//split with space and collect to array
//now, write the output derived from the split array
System.out.println(data[2] + " " + data[1] + " " + data[0]);
}
For one of my assignments, I have to calculate the heat index and use printf to format the output to display neatly, like this:
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
________________________________________________________________________________________
Temperature (F): 1.1 2.2 3.3 4.4 5.5 6.6 7.7 8.8 9.9 10 11 12
Humidity (%): 1 2 3 4 5 6 7 8 9 10.3 11.2 12.1
HI (F): 1.1 2.2 3.3 4.4 5 7 6 8 9 10 11 12
The problem is, I don't know how to format an array of Strings because the array of Strings contains numbers. In my program, do I have to convert my array that I declared as a String to like a double or a float and then format it with printf? Also, I don't know how I can use an array for a calculation. In my assignment, I have to use two arrays to calculate the heat index. Trying to solve this problem, I tried performing the calculations individually by indexes. The problem is, the program will just show the whole entire array. The program is reading two files and storing the text in an array, one array for each file. Any help will be greatly appreciated. The first file contains this:
70.3 70.8 73.8 77.0 80.7 83.4 84.5 84.4 83.4 80.2 76.3 72.0
and the second contains this:
69 67 66 64 66 69 67 67 70 69 69 70
and my code is this:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author timothylee
*/
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
public class HeatIndex {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
public static void main(String[] args) throws IOException{
// TODO code application logic here
// create months
System.out.println("Jan" + " Feb" + " Mar" + " April" + " May" + " June" +
" July" + " Aug" + " Sep" + " Oct" + " Nov" + " Dec");
// create line
System.out.println("_________________________________________________"
+ "__________________________________");
// // read KeyWestTemp.txt
// create token1
String token1 = "";
// create Scanner inFile1
Scanner inFile1 = new Scanner(new File
("/Users/timothylee/KeyWestTemp.txt")).
useDelimiter(",\\s*");
// create temps1
List<String> temps1 = new LinkedList<String>();
// while loop
while(inFile1.hasNext()){
// find next
token1 = inFile1.next();
// initialize temps1
temps1.add(token1);
}
// close inFile1
inFile1.close();
// create array
String[] tempsArray1 = temps1.toArray(new String[0]);
// for-each loop
for(String s : tempsArray1){
// display Temp (F)
System.out.print("Temp (F) ");
// display s
System.out.printf(tempsArray1[0]);
// create new line
System.out.println();
}
// create token2
String token2 = "";
// create Scanner inFile2
Scanner inFile2 = new Scanner(new File
("/Users/timothylee/KeyWestHumid.txt")).
useDelimiter(",\\s*");
// create temps2
List<String> temps2 = new LinkedList<String>();
// while loop
while(inFile2.hasNext()){
// find next
token2 = inFile2.next();
// initialize temps2
temps2.add(token2);
}
// close inFile2
inFile2.close();
// create array
String[] tempsArray2 = temps2.toArray(new String[0]);
// for-each loop
for(String ss : tempsArray2){
// create Humidity (%)
System.out.print("Humidity (%) ");
// display ss
System.out.printf(tempsArray2[0]);
}
// calculate heat index
}
}
and my output is this:
run:
Jan Feb Mar April May June July Aug Sep Oct Nov Dec
___________________________________________________________________________________
Temp (F) 70.3 70.8 73.8 77.0 80.7 83.4 84.5 84.4 83.4 80.2 76.3 72.0
Humidity (%) 69 67 66 64 66 69 67 67 70 69 69 70BUILD SUCCESSFUL (total time: 0 seconds)
Take a look at Formatter. You need to use the format() method, for example something like this would give you the spacing you need in your first line.
formatter.format("%15s%5s%5s%5s",months[0],months[1],months[2],months[3]); //and so on for all twelve months
As for numbers you need to use
formatter.format("%5.1f",myFloat);
The first digit denotes how many characters you use for your natural part and the second digit how many characters for your decimal part. Seeing that all your numbers have only 1 decimal digit and you need spacing between numbers, use the %5.1f format.
I have file with data format as
userid, friend id, books id, cd id
1, 11 12 14 12, 223 256 333 234 222, 22
2, 78 22, 22 66 11 29, 76 455
3, 123 22 11 234 198 122 881, 34 12 98 64, 22
where I need to use only user id and cd id, But I am unable to separate these fields.
My Java code as below.
BufferedReader in = new BufferedReader(new FileReader("CSV_test.txt"));
BufferedWriter ou =new BufferedWriter(new FileWriter("users.csv"));
String str;
str = in.readLine();
while ((str = in.readLine()) != null) {
String[] ar = str.split(",");
String[] ar1 = ar[1].split("");
ou.write(ar[0]);
ou.write(",");
ou.write(ar1[1]);
ou.newLine(); }
in.close();
ou.close();
}
Is there any issue with this?
Surely you want
String[] ar = str.split(",");
String user = ar[0].trim();
String cd = ar[3].trim();
Note that I'm trimming to remove leading/trailing spaces.
You could split using ", " (note the trailing space) and that would remove the need to further trim(). It does make some assumptions however as to how your fields are separated (commas ? commas-and-spaces?) and perhaps it's worth investigating a CSV library.
No need to reinvent the wheel. While CSV parsing is fairly simple, there are things that might be a little bit complicated (such as escaping the separator in field values). Existing libraries can do this for you, such as OpenCSV or CsvJdbc
Hii Guys !!!
I have a string with values like 69 17 17 16 2 1 1 26 26 56 56 69 20 19 20 etc .Now As per my need i have to put these values into new String with each values in new line as after each value space is there ..
Any help will be highly appreciated..
Thanx in advance...
String newStr = origStr.replaceAll(" ", " \n");
You should split the String using a specific separator into a List.
Then print out the List using the format required.
This helps when tomorow the String contains digits, decimals, text, etc or they want the text in another format.
String source = "69 17 17 16 2 1 1 26 26 56 56 69 20 19 20";
String[] splitted = source.split(" ");
StringBuilder sb = new StringBuilder();
for (String split : splitted){
sb.append(split).append(System.getProperty("line.separator"));
}
System.out.println(sb.toString());