I am trying to print:
String[] provinces =
{
"Ontario",
"Quebec",
"Nova Scotia",
"New Brunswick",
"Manitoba",
"British Columbia",
"Prince Edward Island"
};
using the following command:
for (String spiceTraders: provinces) {
System.out.println(" " + spiceTraders);
}
Now, this prints my output as I want but how do I do it with printf, just the way println command prints it and that is print vertically.
This is the desired output:
Ontario
Quebec
Nova Scotia
New Brunswick
Manitoba
British Columbia
Prince Edward Island
You can use printf using %n to get the linefeed and %s to pass the String
for (String spiceTraders: provinces) {
System.out.printf(" %s%n", spiceTraders);
}
Try this:
System.out.printf("%s", " " + String.join("\n ", provinces) + "\n");
I'm new to parsing (and new to Java), so I just want to be sure I'm conceptualizing this correctly.
I've written a program that allows the user to paste text into a text field, then click the "parse data" button. This button parses the text for two pieces of data: a name and a number.
The text data is generally pasted by the user in this form:
john 48915
beth 10431
frank 10112
anne 34887
taserface 90090
bill 56448
I'm using the regular expression "^\d+\t.*\d+$" to detect the pattern, and after the pattern is confirmed, my parse data code does the following:
Scanner parser = new Scanner(inputText);
parser.useDelimiter("\\n");
while (parser.hasNext()) {
String nextToken = parser.next();
String name = nextToken.trim();
// how do I get the number?
You'll notice the \n delimiter, which parses data at the new line character. This breaks the data up into rows, but does not break each row into two separate data points. I need to grab both the name and the number separately.
I believe I should be using a space delimiter, but I'm not sure if I should be doing this in one or two different steps. The confusion, I believe, stems from my limited understanding of how the Scanner does its work. But after a review of the Java documentation, I'm still not really sure.
Current output:
john 48915
beth 10431
frank 10112
etc.
Expected output:
john
48915
beth
10431
etc.
Should I be doing two different loops of parsing, or can I get the work done in the same pass?
Your problem is that you are usimg \n as delimiter.
This leads to the behavior that the input you are passing to your scanner is only delimited at linebreaks and not as you are expecting also at whitespaces.
One solution would that would work is to simply delete the following line: parser.useDelimiter("\\n");
A solution that would also work is the following:
try (Scanner parser = new Scanner(inputText)) {
while (parser.hasNextLine()) {
String nextLine = parser.nextLine();
String[] strings = nextLine.split("\\s");
// Here you can use any pattern to split the line
String name = strings[0];
String number = strings[1];
System.out.printf("%s%n%s%n", name, number);
}
}
This leads to the following output:
john
48915
beth
10431
frank
10112
anne
34887
taserface
90090
bill
56448
The solution gives you some more controll over the lines and how to parse the name and number.
Here is an example implementation for your case, which offers more control and flexibility to accommodate change of delimiters -
import java.util.Arrays;
public class StringSplitExample {
public static void main(String []args){
String content = "john 48915\n"
+ "beth 10431\n"
+ "frank 10112\n"
+ "anne 34887\n"
+ "taserface 90090\n"
+ "bill 56448";
String[] dataset = content.split("\\n|\\s");
for (String value : dataset) {
System.out.println(value);
}
}
}
And, following is the output for the above code snippet -
john
48915
beth
10431
frank
10112
anne
34887
taserface
90090
bill
56448
You can achieve this functionality with String spilt method, below is same program and output as you desire.
I think without space user can not go next line while filling form.
public class ParseLineText {
public static void main(String[] args) {
String textData = "john 48915 " +
"beth 10431 " +
"frank 10112 " +
"anne 34887 " +
"taserface 90090 " +
"bill 56448 ";
String[] data = textData.split("\\s");
for (String text : data) {
System.out.println(text);
}
}
}
Output:
john
48915
beth
10431
frank
10112
anne
34887
taserface
90090
bill
56448
List<Person> people = new ArrayList<Person>();
for (Person p : list) {
Array person = new array[];
personList.add(person);
person.setName(list.getname);
person.setLastname(list.getLastname);
person.setAddress(list.address);
people.add(person);
In this code my address is having 5 rows and if I have to add bring all these rows in to one
Example, convert this
Name LastName Address
John Smith 123
LakeViewDrive
Wheeling
chicago
illinois
Scott Raible 456
Discovergateway
lakecook road
chicago
illinois
to
John Smith 123 LakeviewDrive Wheeling chicago Illinois
scott Raible 456 Discovergateway lakecook road chicago Illinois
Please let me know how to append address rows to single value with out changing.
I'm currently trying to write a Java assignment that is supposed to, in order;
Read each line of a prewritten text file
Turn each line into a string
Turn each part of each line into its own individual string/int/double
Assign those variables in an object (Which is part of an array of objects) of a class which I have also created as part of this assignment
Print each variable of the object using one of the class' methods
However, I am repeatedly running into a runtime problem where I am getting this error message;
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at Lab2.main(Lab2.java:27)
This leads me to believe I am probably reading the text file wrong. However, no matter what I do I can't seem to get it to read correctly. It's supposed to read a first name, a last name, three separate components of an address (which it concatenates into one string), a city, a state, a zip code (as an integer), a phone number (as a string) and a dollar amount (as a double).
I believe that the problem might arise from the city names, as some of them have a space between them. I thought I had solved this by setting the delimiter of the Scanner that reads each individual string to a tab (which is what every other element is separated by) but this has either not worked (And is thus trying to turn state names into an integer via the Integer.parseInt() static method) or is not the problem. As I said, I am out of ideas and would be greatly appreciative towards anyone who could help me out here!
I will list the code below. First here is the main file;
public class Lab2
{
public static void main(String[] args) throws IOException
{ String FirstName, LastName, Address1, Address2, Address3, AddressFull, City, State, Phone, ZipString, DonString, line = "blank";
int Zip;
double Donation;
Scanner fileScan = new Scanner(new File("Lab2.txt")), lineScan = new Scanner(line);
lineScan.useDelimiter("\t");
PersonStats[] Donators = new PersonStats[25];
for (int i = 0; i < Donators.length; i++)
{ line = fileScan.nextLine();
FirstName = lineScan.next();
LastName = lineScan.next();
Address1 = lineScan.next();
Address2 = lineScan.next();
Address3 = lineScan.next();
AddressFull = Address1 + " " + Address2 + " " + Address3;
City = lineScan.next();
State = lineScan.next();
ZipString = lineScan.next();
Zip = Integer.parseInt(ZipString);
Phone = lineScan.next();
DonString = lineScan.next();
Donation = Double.parseDouble(DonString);
Donators[i] = new PersonStats(FirstName, LastName, AddressFull, City, State, Zip, Phone, Donation);
Donators[i].PrintOut();
}
}
}
Next, the class file I've written up for the assignment;
public class PersonStats
{ private String FirstName, LastName, Address, City, State, Phone;
private int Zip;
private double Donation;
public PersonStats(String first, String last, String area, String town, String feifdom, int postcode, String telegraph, double given)
{ FirstName = first;
LastName = last;
Address = area;
City = town;
State = feifdom;
Zip = postcode;
Phone = telegraph;
Donation = given;
}
public void PrintOut()
{ System.out.println(FirstName + " " + LastName);
System.out.println(Address);
System.out.println(City + ", " + State + " " + Zip + "\n");
System.out.println(Phone + " " + Donation);
}
}
And then finally the text file the program is supposed to be reading from (Might be a little bit difficult to read, just remember each space except for the ones in city names is actually a tab);
Rick James 8276 Carlos Ave Las Vegas NV 87126 5553451567 23.95
John Gibson 9127 Oak Dr Corvallis OR 97330 5552812313 156.78
Ron Wills 1155 Ivy Pl Atlantic Ga 37339 5552123145 189.56
Rita Jones 1259 Chase Ave Las Vegas NV 87126 5554445671 2145.60
Jason Knight 7154 Pine Dr Gresjam OR 97380 5558124545 3157.44
Clara Swanson 1944 Main Pl Springfield OR 97339 5552123144 212.99
Robert Peck 1866 First Ave Las Vegas NV 87126 5553455425 250.00
Dora Garcia 2179 Fir Dr Corvallis OR 97330 5552812919 350.00
Peter Keck 1465 Circle Pl Gold Beach OR 97339 5552123256 2150.00
Stuart Smith 2387 Sweek Ave Las Vegas NV 87126 5553455489 650.99
Tyler Wild 1313 Spooky Ln Corvallis OR 97330 5552813213 587.45
Laretta Peters 2224 Chase Pl Monmouth OR 97361 5552124465 123.45
Kristi Emry 3465 Cerrito Ave Las Vegas NV 87126 5553455567 3212.65
Kelli Gard 1894 Elm Dr Corvallis OR 97330 5552816678 51.00
Jacob Andrews 8159 Rose Ct Mill City OR 97322 5552127879 64.00
Ryan Perkins 7546 Prince Ave Las Vegas NV 87126 5553451989 13.00
Joshua Gilbert 9278 Monroe Dr Corvallis OR 97330 5552832656 95.00
Miles Crain 4578 Chester Dr Corvallis OR 97331 5552345678 1544.00
Butch Cassidy 5498 Sutton Pl Gresham OR 97380 5416565797 1798.56
Perry Winkle 8185 Shaver Ave Las Vegas NV 87126 5553812346 195.66
Loni Day 4598 Holmen Dr Corvallis OR 97330 5555289741 1878.50
Nikita Benson 1787 Grant Pl Portland OR 97321 5553569898 1500.00
Rusty Krouger 8829 Simeon Ave Las Vegas NV 87126 5555677847 2100.00
Wally Wallace 2898 Wilson Blvd Jackson Center OH 23466 5552222222 2222.22
Joe Jones 1212 Water St Millersburg OR 97366 5555555555 55.55
Again, thanks in advance if there's anyone out there who can help me with this, your advice might save a life!... or at least the score of this lab :S
here is a tip: When using Scanner use the hasNextXXX method before invoking next methods to check if elements exists
https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
No Such Element Exception?
Okay, here it is
import java.io.IOException;
import java.io.*;
import java.util.Scanner;
public class Lab2
{
public static void main(String[] args) throws IOException
{ String FirstName, LastName, Address1, Address2, Address3, AddressFull, City, State, Phone, ZipString, DonString, line = "blank";
int Zip;
double Donation;
Scanner fileScan = new Scanner(new File("F:/test.txt")).useDelimiter("\n");
PersonStats[] Donators = new PersonStats[5];
String tempVal="";
int i = 0;
while(fileScan.hasNext())
{
tempVal = fileScan.next(); //Storing person records one at a time in the string line by line
String tempArr[] = tempVal.split("\t"); //Splitting each person record string by tab and storing it in a String array
FirstName = tempArr[0];
LastName = tempArr[1];
Address1 = tempArr[2];
Address2 = tempArr[3];
Address3 = tempArr[4];
AddressFull = Address1 + " " + Address2 + " " + Address3;
City = tempArr[5];
State = tempArr[6];
ZipString = tempArr[7];
Zip = Integer.parseInt(ZipString);
Phone = tempArr[8];
DonString = tempArr[9];
Donation = Double.parseDouble(DonString);
Donators[i] = new PersonStats(FirstName, LastName, AddressFull, City, State, Zip, Phone, Donation);
Donators[i].PrintOut();
i++;
}
}
}
First of all, I would like to point out that your variable names should start with lower case. I did not edit them in the code since they were used in many places. Make an habit to declare String firstName instead of String FirstName
To the code, in your code you had used a "\t" delimter which I replaced with "\n" since in the text file each line holds entire Person details. You could have used "\t" if the donation of the first person and first name of the second person were separated by the same, but they are separated by "\n"
So now Scanner fileScan will read the file line by line which I will store in String tempVal and while(fileScan.hasNext()) assures that the Scanner will keep reading only as long as there are lines to be read.
Now, every line has different information separated by "\t". So I used tempVal.split("\t") to separate them. Also, used a counter int i and removed the for loop. I guess rest of the code is pretty basic and not much different from yours.
**EDIT****
Here is the output
Rick James
8276 Carlos Ave
Las Vegas, NV 87126
5553451567 23.95
John Gibson
9127 Oak Dr
Corvallis, OR 97330
5552812313 156.78
Ron Wills
1155 Ivy Pl
Atlantic, Ga 37339
5552123145 189.56
Rita Jones
1259 Chase Ave
Las Vegas, NV 87126
5554445671 2145.6
Jason Knight
7154 Pine Dr
Gresjam, OR 97380
5558124545 3157.44
And here is the sample text.file that I used.
Rick James 8276 Carlos Ave Las Vegas NV 87126 5553451567 23.95
John Gibson 9127 Oak Dr Corvallis OR 97330 5552812313 156.78
Ron Wills 1155 Ivy Pl Atlantic Ga 37339 5552123145 189.56
Rita Jones 1259 Chase Ave Las Vegas NV 87126 5554445671 2145.60
Jason Knight 7154 Pine Dr Gresjam OR 97380 5558124545 3157.44
Scanner fileScan = new Scanner(new File("Lab2.txt"));
//PersonStats[] Donators = new PersonStats[25];
while(fileScan.hasNext()) {
line = fileScan.nextLine();
String parts[] = line.split("\t");
if(parts.length == 10) {
FirstName = parts[0];
...
}
There are some problems in addion.
First: String ist immutable. So your lineScanner will created with an empty String. If you later change this string, nothing appens for this scanner, because you create a new string with this step.
Second you have to check for an next element. (see my while loop)
To parse your data it is easyer to split the string in parts and use this to fill your Class. But if you want to use the Scanner class, you have to create on instance per line in your file.(in the while loop)
Code that i tried:
import java.io.*;
import java.util.regex.*;
public class All {
public static void main(String[] args) {
String input = "IT&&faculty.*";
try {
FileInputStream fstream = new FileInputStream("uu.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
if (Pattern.matches(input, strLine)) {
Pattern p = Pattern.compile("'(.*?)'");
Matcher m = p.matcher(strLine);
while (m.find()) {
String b = m.group(1);
String c = b.toString() + ".*";
System.out.println(b);
if (Pattern.matches(c, strLine)) {
Pattern pat = Pattern.compile("<(.*?)>");
Matcher mat = pat.matcher(strLine);
while (mat.find()) {
System.out.println(m.group(1));
}
} else {
System.out.println("Not found");
}
}
}
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
}
The contents of my text file are:
\ indicates it is a newline
Input file:
IT&&faculty('Mousum handique'|'Abhijit biswas'|'Arnab paul'|'Bhagaban swain')
Mousum handique(designation|address|phone number|'IT Assistant professor'|<AUS staff quaters>|#5566778899#)
Abhijit biswas(designation|address|phone number|'IT Assistant professor'|<AUW staff quaters>|#5566778891#)
Arnab paul(designation|address|phone number|'IT Assistant professor'|<AUE staff quaters>|#5566778890#)
Bhagaban swain(designation|address|phone number|'IT Assistant professor'|<AUW staff quarters>|#5566778892#)
it gives result -
Mousum handique
Not found
Abhijit Biswas
Not found
Arnab Paul
Not found
Bhagaban swain
Not found
whereas the results i want is:
Mousum handique
AUS staff quaters
Abhijit Biswas
AUW staff quaters
Arnab Paul
AUE staff quaters
Bhagaban swain
AUW staff quaters
That is i want after 1st match when it gets Mousum handique from the file it should again search the file and where it gets line like Mousum handique it should print whatever within <> for that corresponding line. Please refer data of my text file to understand my question. Sorry if my question seems stupid but i m trying it a lot!
You don't need to use string.matches method just use Patttern and Matcher classes to extract the name which was at the start of the line and also the contents between <> on the same line itself.
String s = "IT&&faculty('Mousum handique'|'Abhijit biswas'|'Arnab paul'|'Bhagaban swain')\n" +
" Mousum handique(designation|address|phone number|'IT Assistant professor'|<AUS staff quaters>|#5566778899#)\n" +
" Abhijit biswas(designation|address|phone number|'IT Assistant professor'|<AUW staff quaters>|#5566778891#)\n" +
"Arnab paul(designation|address|phone number|'IT Assistant professor'|<AUE staff quaters>|#5566778890#)\n" +
"Bhagaban swain(designation|address|phone number|'IT Assistant professor'|<AUW staff quarters>|#5566778892#)";
Matcher m = Pattern.compile("(?m)^\\s*([^\\(]+)\\([^\\)]*\\|<([^>]*)>[^\\)]*\\)").matcher(s);
while(m.find())
{
System.out.println(m.group(1));
System.out.println(m.group(2));
}
Output:
Mousum handique
AUS staff quaters
Abhijit biswas
AUW staff quaters
Arnab paul
AUE staff quaters
Bhagaban swain
AUW staff quarters
DEMO
Update:
Use this regex to get also the id number.
String s = "IT&&faculty('Mousum handique'|'Abhijit biswas'|'Arnab
paul'|'Bhagaban swain')\n" +
" Mousum handique(designation|address|phone number|'IT Assistant professor'|<AUS staff quaters>|#5566778899#)\n" +
" Abhijit biswas(designation|address|phone number|'IT Assistant professor'|<AUW staff quaters>|#5566778891#)\n" +
"Arnab paul(designation|address|phone number|'IT Assistant professor'|<AUE staff quaters>|#5566778890#)\n" +
"Bhagaban swain(designation|address|phone number|'IT Assistant professor'|<AUW staff quarters>|#5566778892#)";
Matcher m = Pattern.compile("(?m)^\\s*([^\\(]+)\\([^\\)]*\\|<([^>]*)>[^\\)]*\\|#([^#]*)#[^\\)]*\\)").matcher(s);
while(m.find())
{
System.out.println(m.group(1));
System.out.println(m.group(2));
System.out.println(m.group(3));
}
Output:
Mousum handique
AUS staff quaters
5566778899
Abhijit biswas
AUW staff quaters
5566778891
Arnab paul
AUE staff quaters
5566778890
Bhagaban swain
AUW staff quarters
5566778892
One bug is here:
while (mat.find()) {
System.out.println(m.group(1)); // <-- you should use mat - not m!!!
}
Second bug is here:
if (Pattern.matches(c, strLine)) {
This if is never entered since the String c is the previous match + ".*". Remove this if condition and it'll work.
Fixed code:
...
Pattern p = Pattern.compile("'(.*?)'");
Matcher m = p.matcher(strLine);
while (m.find()) {
String b = m.group(1);
System.out.println(b);
Pattern pat = Pattern.compile("<(.*?)>");
Matcher mat = pat.matcher(strLine);
while (mat.find()) {
System.out.println(mat.group(1));
}
}
...
Running this code with the input:
"Abhijit biswas(designation|address|phone number|'IT Assistant professor'|<AUW staff quaters>|#5566778891#)
outputs:
IT Assistant professor
AUW staff quaters