Java: Token rearrangement and character removal with text file - java

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]);
}

Related

I want to extract strings from a line

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]

JAVA- Splitting string into tokens but fails with error [duplicate]

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;

parsing csv by "," and " "

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

how to put String values into new Line on getting spaces in java

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());

How to properly use String.format with 2 different incoming array sources?

i wish to know the best way to use String.format in this case...
String names[] = new String[10];
int idNumber[] = new int[10];
String list = "";
for( byte pos = 0; pos < idNumber.length; pos++){
names[pos] = JOptionPane.showInputDialog("Enter the name...");
idNumber[pos] = Integer.parseInt(JOptionPane.showInputDialog("Enther the ID number..."));
list += ("Name: " + names[pos] + "ID: " + idNumber + "\n");
}
JOptionPane.showMessagedialog(null, list);
I wish to use the String.format to change the output of "list"
from:
Name: John Wilson ID: 56
Name: Edward Sinclair ID: 60
Name: Bob Stuart ID: 77
to:
Name: John Wilson ID: 56
Name: Edward Sinclair ID: 60
Name: Bob Stuart ID: 77
how do i properly use the %-10s... %-5s... in this case ? im a little lost here... thanks in advance.
I really don't see what you were having problems with using string.format. Did you actually try it?
list += ("Name: %20s ID: %02d\n").format(names[pos], idNumber[pos]);
As mentioned, it would be more efficient to have:
StringBuilder list = new StringBuilder();
And then replace list += ... with list.append(...)

Categories

Resources