I want to split string by new lines in Java.I am using following regex -
str.split("\\r|\\n|\\r\\n");
But still it is not splitting string by new lines.
Input -
0
0
0
0
Output = String [] array = {"0000"} instead I want = String [] array = {"0","0","0","0"}.
I have read various solutions on stack overflow but nothing works for me.
Code is -
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
public class Input {
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line;
String text = "";
try {
while((line=br.readLine())!=null){
text = text + line;
}
} catch (IOException e) {
e.printStackTrace();
}
String [] textarray = text.trim().split("[\\r\\n]+");
for(int j=0;j<textarray.length;j++)
System.out.println(textarray[j]);
// System.out.print("");
// for(int i=((textarray.length)-1);i>=0;i--){
// long k = Long.valueOf(textarray[i]).longValue();
// System.out.println(k);
//// double sqrt = Math.sqrt(k);
//// double value = Double.parseDouble(new DecimalFormat("##.####").format(sqrt));
//// System.out.println(value);
////
//// }
}
When you call br.readLine(), the newline characters are stripped from the end of the string. So if you type 0 + ENTER four times, you are trying to split the string "0000".
You would be better to read items in from stdin and store them in an expandable data structure, such as a List<String>. No need to split things if you've already read them separately.
Updated Answer:
If you are reading the inputstreamfrom the keyboard, the \n may not be put into the data correctly. In that case, you may want to choose a new sentinel value.
Original Answer:
I believe you need to create a sentinel value. So if \n is your sentinel value, you could do something like this:
Load the inputstream into a string variable
Go character by character through the string variable checking to see if \n is in the input (you could use a for loop and the substing(i, i+2)
If it is found, then you could add it to an array
Related
I use Android Studio.I have a text file with some of numbers and I want to calculate them with others numbers. When I am try to convert them from string with method Integer.parseInt on program start I get error and program close.Error is :
at java.lang.Integer.parseInt(Integer.java:521)
at java.lang.Integer.parseInt(Integer.java:556)
I am just beginner and sorry for bad english , I hope you understand my problem.
This is part of my code.
public void read (){
try {
FileInputStream fileInput = openFileInput("example.txt");
InputStreamReader reader = new InputStreamReader(fileInput);
BufferedReader buffer = new BufferedReader(reader);
StringBuffer strBuffer = new StringBuffer();
String lines;
while ((lines = buffer.readLine()) != null) {
strBuffer.append(lines + "\n");
}
int numbers = Integer.parseInt(strBuffer.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here:
int numbers = Integer.parseInt(strBuffer.toString());
You should read the javadoc for the library methods you are using. parseInt() parses one number from a string that contains one number.
So you need
to learn how to use arrays of int (because you want to read and process multiple numbers), not just a single one
to then use parseInt() on the individual number strings in that file
Also note that you can use the Scanner to directly work on an InputStream, there is no need to first turn the complete file content into one large string in memory!
Integer.parseInt(String) throws a NumberFormatException when its argument can't be converted to a number.
Break your problem into smaller, more manageable blocks. Your code currently gets the entire content of example.txt and tries to parse the whole thing to an Integer.
One possibility for reading all integer values is to do this with a java.util.Scanner object instead and use its nextInt() method.
Consider the following example, given a file example.txt with integers separated by spaces.
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class App {
public static void main(String...args) throws Exception {
File file = new File("/home/william/example.txt");
try (InputStream is = Files.newInputStream(file.toPath())) {
Scanner scanner = new Scanner(is);
List<Integer> ints = new ArrayList<>();
while (scanner.hasNextInt()) {
int i = scanner.nextInt();
System.out.printf("Read %d%n", i);
ints.add(i);
}
}
}
}
Why does Java String.split() generate different results when working with string defined in code versus string read from a file when numbers are involved? Specifically I have a file called "test.txt" that contains chars and numbers separated by spaces:
G H 5 4
The split method does not split on spaces as expected. But if a string variable is created within code with same chars and numbers separated by spaces then the result of split() is four individual strings, one for char and number. The code below demonstrates this difference:
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
public class SplitNumber {
//Read first line of text file
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileReader fr = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fr);
String firstLine;
if ((firstLine = bufferedReader.readLine()) != null) {
String[] firstLineNumbers = firstLine.split("\\s+");
System.out.println("First line array length: " + firstLineNumbers.length);
for (int i=0; i<firstLineNumbers.length; i++) {
System.out.println(firstLineNumbers[i]);
}
}
bufferedReader.close();
String numberString = "G H 5 4";
String[] numbers = numberString.split("\\s+");
System.out.println("Numbers array length: " + numbers.length);
for (int i=0; i<numbers.length; i++) {
System.out.println(numbers[i]);
}
} catch(Exception exception) {
System.out.println("IOException occured");
exception.printStackTrace();
}
}
}
The result is:
First line array length: 3
G
H
5 4
Numbers array length: 4
G
H
5
4
Why do the numbers from the file not get parsed the same as the same string defined within code?
Based on feedback I changed the regex to split("[\\s\\h]+") which resolved the issue; the numbers for the file were properly split which clearly indicated that I had a different whitespace-like character in the text file that I was using. I then replaced the contents of the file (using notepad) and reverted back to split("\\s+") and found that it worked correctly this time. So at some point I must have introduced different white-space like characters in the file (maybe a copy/paste issue). In the end the take away is I should use split("[\\s\\h]+") when reading from a file where I want to split on spaces as it will cover more scenarios that may not be immediately obvious.
Thanks to all for helping me find the root cause of my issue.
My bad for the title, I am usually not good at making those.
I have a programme that will generate all permutations of an inputted word and that is supposed to check to see if those are words (checks dictionary), and output the ones that are. Really I just need the last the part and I can not figure out how to parse through a file.
I took out what was there (now displaying the "String words =") because it really made thing worse (was an if statement). Right now, all it will do is output all permutations.
Edit: I should add that the try/catch was added in when I tried turning the file in a list (as opposed to the string format which it is currently in). So right now it does nothing.
One more thing: is it possible (well how, really) to get the permutations to display permutations with lesser characters than entered ? Sorry for the bad wording, like if I enter five characters, show all five character permutations, and four, and three, and two, and one.
import java.util.List;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import static java.lang.System.out;
public class Permutations
{
public static void main(String[] args) throws Exception
{
out.println("Enter anything to get permutations: ");
Scanner scan = new Scanner(System.in);
String io = scan.nextLine();
String str = io;
StringBuffer strBuf = new StringBuffer(str);
mutate(strBuf,str.length());
}
private static void mutate(StringBuffer str, int index)
{
try
{
String words = FileUtils.readFileToString(new File("wordsEn.txt"));
if(index <= 0)
{
out.println(str);
}
else
{
mutate(str, index - 1);
int currLoc = str.length()-index;
for (int i = currLoc + 1; i < str.length(); i++)
{
change(str, currLoc, i);
mutate(str, index - 1);
change(str, i, currLoc);
}
}
}
catch(IOException e)
{
out.println("Your search found no results");
}
}
private static void change(StringBuffer str, int loc1, int loc2)
{
char t1 = str.charAt(loc1);
str.setCharAt(loc1, str.charAt(loc2));
str.setCharAt(loc2, t1);
}
}
If each word in your file is actually on a different line, maybe you can try this:
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null)
{
... // check and print here
}
Or if you want to try something else, the Apache Commons IO library has something called LineIterator.
An Iterator over the lines in a Reader.
LineIterator holds a reference to an open Reader. When you have finished with the iterator you should close the reader to free internal resources. This can be done by closing the reader directly, or by calling the close() or closeQuietly(LineIterator) method on the iterator.
The recommended usage pattern is:
LineIterator it = FileUtils.lineIterator(file, "UTF-8");
try {
while (it.hasNext()) {
String line = it.nextLine();
// do something with line
}
} finally {
it.close();
}
I want to read this string (from console not file) for example:
one two three
four five six
seven eight nine
So I want to read it per line and put every line in an array.
How can I read it? Because if I use scanner, I can only read one line or one word (nextline or next).
what I mean is to read for example : one two trhee \n four five six \n seven eight nine...
You should do by yourself!
There is a similer example:
public class ReadString {
public static void main (String[] args) {
// prompt the user to enter their name
System.out.print("Enter your name: ");
// open up standard input
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String userName = null;
// read the username from the command-line; need to use try/catch with the
// readLine() method
try {
userName = br.readLine();
} catch (IOException ioe) {
System.out.println("IO error trying to read your name!");
System.exit(1);
}
System.out.println("Thanks for the name, " + userName);
}
} // end of ReadString class
To answer the question as clarified in the comment on the first answer:
You must call Scanner's nextLine() method once for each line you wish to read. This can be accomplished with a loop. The problem you will inevitably encounter is "How do I know big my result array should be?" The answer is that you cannot know if you do not specify it in the input itself. You can modify your programs input specification to require the number of lines to read like so:
3
One Two Three
Four Five
Six Seven Eight
And then you can read the input with this:
Scanner s = new Scanner(System.in);
int numberOfLinesToRead = new Integer(s.nextLine());
String[] result = new String[numberOfLinesToRead];
String line = "";
for(int i = 0; i < numberOfLinesToRead; i++) { // this loop will be run 3 times, as specified in the first line of input
result[i] = s.nextLine(); // each line of the input will be placed into the array.
}
Alternatively you can use a more advanced data structure called an ArrayList. An ArrayList does not have a set length when you create it; you can simply add information to it as needed, making it perfect for reading input when you don't know how much input there is to read. For example, if we used your original example input of:
one two trhee
four five six
seven eight nine
You can read the input with the following code:
Scanner s = new Scanner(System.in);
ArrayList<String> result = new ArrayList<String>();
String line = "";
while((line = s.nextLine()) != null) {
result.add(line);
}
So, rather than creating an array of a fixed length, we can simply .add() each line to the ArrayList as we encounter it in the input. I recommend you read more about ArrayLists before attempting to use them.
tl;dr: You call next() or nextLine() for each line you want to read using a loop.
More information on loops: Java Loops
Look at this code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class SearchInputText {
public static void main(String[] args) {
SearchInputText sit = new SearchInputText();
try {
System.out.println("test");
sit.searchFromRecord("input.txt");
System.out.println("test2");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void searchFromRecord(String recordName) throws IOException {
File file = new File(recordName);
Scanner scanner = new Scanner(file);
StringBuilder textFromFile = new StringBuilder();
while (scanner.hasNext()) {
textFromFile.append(scanner.next());
}
scanner.close();
// read input from console, compare the strings and print the result
String word = "";
Scanner scanner2 = new Scanner(System.in);
while (((word = scanner2.nextLine()) != null)
&& !word.equalsIgnoreCase("quit")) {
if (textFromFile.toString().contains(word)) {
System.out.println("The word is on the text file");
} else {
System.out.println("The word " + word
+ " is not on the text file");
}
}
scanner2.close();
}
}
this is my first question here so I hope I'm doing this right. I have a programming project that needs to read each line of a tab delimited text file and extract a string, double values, and int values. I'm trying to place these into separate arrays so that I can use them as parameters. This is what I have so far(aside from my methods):
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class LoanDriver {
public static void main(String[] args)
{
String[] stringData = new String[9];
Scanner strings = null;
try
{
FileReader read = new FileReader("amounts.txt");//Read text file.
strings = new Scanner(read);
String skip = strings.nextLine();//Skip the first line by storing it in an uncalled variable
strings.useDelimiter("\t *");//Tab delimited
}
catch (FileNotFoundException error)
{}
while (strings.hasNext())
{
String readLine = strings.next();
stringData = readLine.split("\t");
}
}}
If I try to get the [0] value, it skips all the way to the bottom of the file and returns that value, so it works to some extent, but not from the top like it should. Also, I can't incorporate arrays into it because I always get an error that String[] and String is a type mismatch.
Instead of using delimiter, try reading the file line by line using Scanner.nextLine and split each new line you read using String.split ("\t" as argument).
try {
FileReader read = new FileReader("amounts.txt");//Read text file.
strings = new Scanner(read);
String skip = strings.nextLine();//Skip the first line by storing it in an uncalled variable
}
catch (FileNotFoundException error) { }
String line;
while ((line = strings.nextLine()) != null) {
String[] parts = line.split("\t");
//...
}
You are getting the last value in the file when you grab stringData[0] because you overwrite stringData each time you go through the while loop. So the last value is the only one present in the array at the end. Try this instead:
List<String> values = new ArrayList<String>();
while (strings.hasNext()) {
values.add(strings.next());
}
stringData = values.toArray(new String[values.size()]);