So, I have the following situation:
private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line= reader.readLine();
String first = ?
String second = ?
So, I know that user will enter something like this: love cats and dogs.
I want that the first word (in this case love) is always in String first and everything else in String second. How can I do it as simple as possible?
String line = "love cats and dogs";
// split into 2 parts
String[] parts = line.split(" ",2);
String first = parts[0];
String second = parts[1];
Simply:
int splitIndex = line.indexOf(" ");
String first = line.substring(0, splitIndex);
String second = line.substring(splitIndex + 1);
Related
I have a problem with something like that. Unfortunately, I can't edit anything.
en_GB United States 2015-07-10 2015-08-30 mountains 5,400.20 USD
This is one line from text file. I'm trying to prepare scanner for it and basing on it create object. Here what i made and what i can edit.
String lang;
String country;
Date[] dates; //contains two dates - arrival and departure
String place;
Double price;
String curr;
public TravelData(String lang, String countryIn, Date[] dateIn, String placeIn, Double priceIn, String currIn)
This is how my constructor looks like. I was trying to use scanner and next() method, but looks like it doesn't work with date. What would be the best way to cut this line of text on smaller parts?
My not working scanner :).
public void ReadOffers(File dataDir) throws FileNotFoundException{
TravelData travel;
for (final File fileEntry : dataDir.listFiles()) {
scan = new Scanner(fileEntry);
while(scan.hasNextLine()){
String l = scan.next();
String c = scan.next();
Date[] d = [Date.parse(scan.next()); Date.parse(scan.next())];
String pl = scan.next();
Double pr = Double.parseDouble(scan.next());
String cu = scan.next();
travel = new TravelData(l, c, d, pl, pr, cu);
travelList.add(travel);
}
}
}
You can use BufferedReader instead to read the line and then split() and put it into an array of strings like this:
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileEntry)));
String line;
while(line = br.readNext() != null)
{
String[] words = line.split(" ");//assuming you want to split based on the whitespace char
//do what you want to do with the words
}//reapeat as long as there is a line to the file
Load it as an entire string
String fileContent = new String(readAllBytes(get("test.txt"));
Separate via regex using split(regex)
String[] separatedLines = fileContent.split("\n");
foreach(String s:separatedLines){
s.split(" ");
[parse as you wish, like you were doing]
[do stuff, put results in a list or in another array]
}
EDIT: I read that those are tabs: split("\t*").
EDIT2: as for the date, check SimpleDataFormat
I am required to split a string which has been read from a external file. I have managed to split the string using this code;
String[] parts = line.split("\\.");
String part1 = parts[0];
String part2 = parts[1];
Now when I attempt to access the data, part1 at index[0] works fine, however trying to get index [1] throw an index out of bounds exception. The data I'm trying to split looks like so
886.0452586206898 27115740907.871643
888.0387931034484 26218442896.246094
890.032327586207 25301777157.154663
892.0258620689656 24365534070.686035
894.0193965517242 23409502709.11487
Am I meant to remove white space before doing the string split?
Since i highly doubt that the index is getting lost. You might want to try this code to find out if the data is completly valid. If the error still occurs you might have the cause of the error at some different place, and want to show your actuall stacktrace.
while ((line = br.readLine()) != null) {
if(line.contains(".")) {
String[] parts = line.split("\\.");
String part1 = parts[0];
String part2 = parts[1];
} else {
System.out.println("Corrupted data as: " + line);
}
}
I guess you are reading the file line by line, then you should split first against a "space" and then again the dot, otherwise you will get corrupted data...
886.0452586206898 27115740907.871643
as you can see, there are 2 elements in each line that can be split by dot
String[] parts = null;
String part1 = null;
String part2 = null;
System.out.println(parts[2]);
while ((line = br.readLine()) != null) {
System.out.println(line);
parts = line.split("\\.");
part1 = parts[0];
part2 = parts[1];
}
It is not working because you are trying to reach a variable that you declarated inside the while. Try to declarate outside it.
Do you want to extract each number from the input, then split on the decimal?
In that case, use Scanner to read in each number first, then split:
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
String num = s.next();
String[] parts = num.split("\\.");
...
}
I want to read line by line from a text file in java, one line consist of 4 fields but one field can contain multiple words, For Ex.:
I have this line: Screen Commercial Problem with product
How can I store this three fields of my line into 3 String variables in java?
var1 -> "Screen"
var2 -> "Commercial"
var3 -> "Problem with product"
This splits the input. Use System.in instead of inputStream if reading from standard input:
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = in.readLine()) != null) {
String[] split = line.split(" ", 3);
String var1 = split[0]; String var2 = split[1]; String var3 = split[2];
// do whatever is needed...
}
Ideally, you'll want to use some specific character to indicate the breaks between fields. For example, Screen|Commercial|Problem with product. Then you could write code that reads the entire line as input and then divides it into substrings. For example:
File yourFile = new File(/*file path goes here*/);
Scanner sc = new Scanner(yourFile);
String input;
String var1;
String var2;
String var3;
int breakIndex;
while (sc.hasNextLine()) {
input = sc.nextLine();
breakIndex = input.indexOf("|");
var1 = input.substring(0, breakIndex);
input = input.substring(breakIndex+1);
breakIndex = input.indexOf("|");
var2 = input.substring(0, breakIndex);
var3 = input.substring(breakIndex+1);
// do whatever it is you plan to do with those variables here
}
Okay So I am creating an application but I'm not sure how to get certain parts of the string. I have read In a file as such:
*tp*|21394398437984|163600
*2*|AAA|1234567894561236|STOP|20140527|Success||Automated|DSPRN1234567
*2*|AAA|1234567894561237|STOP|20140527|Success||Automated|DPSRN1234568
*3*|2
I need to read the lines beginning with 2 so I done:
s = new Scanner(new BufferedReader(new FileReader("example.dat")));
while (s.hasNext()) {
String str1 = s.nextLine ();
if(str1.startsWith("*2*")) {
System.out.print(str1);
}
}
So this will read the whole line I'm fine with that, Now my issue is I need to extract the 2nd line beginning with numbers the 4th with numbers the 5th with success and the 7th(DPSRN).
I was thinking about using a String delimiter with | as the delimiter but I'm not sure where to go after this any help would be great.
You should use String.split("|"), it will give you an array - String[]
Try following:
String test="*2*|AAA|1234567894561236|STOP|20140527|Success||Automated|DSPRN1234567";
String tok[]=test.split("\\|");
for(String s:tok){
System.out.println(s);
}
Output :
*2*
AAA
1234567894561236
STOP
20140527
Success
Automated
DSPRN1234567
What you require will be placed at tok[2], tok[4], tok[5] and tok[8].
Just split the returned line based on your search, which would return an array of String elements where you can retrieve your elements based on their index:
s = new Scanner(new BufferedReader(new FileReader("example.dat")));
String searchLine = "";
while (s.hasNext()) {
searchLine = s.nextLine();
if(searchLine.startsWith("*2*")) {
break;
}
}
String[] strs = searchLine.split("|");
String secondArgument = strs[2];
String forthArgument = strs[4];
String fifthArgument = strs[5];
String seventhArgument = strs[7];
System.out.println(secondArgument);
System.out.println(forthArgument);
System.out.println(fifthArgument);
System.out.println(seventhArgument);
I'm having trouble figuring out how to read the rest of a input line. I need to token the first word then possibly create the rest of the input line as one whole token
public Command getCommand()
{
String inputLine; // will hold the full input line
String word1 = null;
String word2 = null;
System.out.print("> "); // print prompt
inputLine = reader.nextLine();
// Find up to two words on the line.
Scanner tokenizer = new Scanner(inputLine);
if(tokenizer.hasNext()) {
word1 = tokenizer.next(); // get first word
if(tokenizer.hasNext()) {
word2 = tokenizer.next(); // get second word
// note: just ignores the rest of the input line.
}
}
// Now check whether this word is known. If so, create a command
// with it. If not, create a "null" command (for unknown command).
if(commands.isCommand(word1)) {
return new Command(word1, word2);
}
else {
return new Command(null, word2);
}
}
The input:
take spinning wheel
Output:
spinning
Desired Output:
spinning wheel
Use split()
String[] line = scan.nextLine().split(" ");
String firstWord = line[0];
String secondWord = line[1];
It means that you need to split the line at space and that will convert it into the array. Now using yhe index you can get any word you want
OR -
String inputLine =//Your Read line
String desiredOutput=inputLine.substring(inputLine.indexOf(" ")+1)
You can try like this also...
String s = "This is Testing Result";
System.out.println(s.split(" ")[0]);
System.out.println(s.substring(s.split(" ")[0].length()+1, s.length()-1));
Use split(String regex, int limit)
String[] line = scan.nextLine().split(" ", 2);
String firstWord = line[0];
String rest= line[1];
Refer to doc here