Read Strings separated by newline using BufferedReader into a String array - java

I've read number of such questions but they are all about reading inputs from a txt file. I want to read input from user and not from the file.
I've input like following:
6 //number of total Strings to store in array
babu
anand
rani
aarti
nandu
rani
I've tried the following code to take such input in a String array:
int n = in.nextInt(); // n= 6 here
String[] s = new String[n]; //String array of size 6 here
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try{
s = br.readLine().split("\\s");
}
catch(Exception e){
System.out.println(e);
}
Is the regex provided to the split() is correct or not? What I'm missing here? If this is not correct approach than what should I do for this problem?

Regex are using backslashes (\) while you used slashes //s, correct one is \\s.
But this split is not needed, you just need the readLine, and you will get what you need (assuming you don't want to split words in the line).
You should use a loop to read all the data (and get rid of Scanner, that you appear to have in the in variable):
String[] s = null
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in)) {
int n = Integer.parseInt(br.readLine());
for (int line = 0; line < n; line++) {
s[line] = br.readLine();
}
} catch(Exception e){
System.out.println(e);
}

Move the third line before the first one.
Then use this in your new second line:
int n = Integer.parseInt(br.readLine());
And, of course, you need a loop to put your input strings into an array.
This should help.

Related

Why am I getting a NullPointerException when I try to read input using BufferedReader?

I am trying to take a multiple integer input in a single line and store all those integers into an ArrayList. This is my code:
String[] input = new String[5];
ArrayList<Integer> A=new ArrayList<>(5);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try{
while(br.readLine()!=null)
input = br.readLine().split(" ");
}
catch(Exception e){
System.out.print(e);
}
System.out.println(Arrays.toString(input));
The input is like this :
2 2 1 3 1
But when I excecute the code I get a NullPointerException in this line input = br.readLine().split(" ");. How can I fix this?
EDIT: Tried using Scanner to take the input like this:
String str="";
Scanner s=new Scanner(System.in);
String[] input = new String[5];
ArrayList<Integer> A=new ArrayList<>(5);
while(s.hasNext())
str=s.nextLine();
input=str.split(" ");
System.out.println(Arrays.toString(input)); //[]
Now my array is completely empty!!
You have two calls to br.readLine(). While the first call will abort the loop if line is null, the second call can still read the next line which can be null (indicating end of file). Additional problem is also that the line returned by the first br.readLine() is lost.
The correct way is:
String line;
while ((line = br.readLine()) != null) {
String[] input = line.split(" ");
}
There should be exactly 1 spaces between the input numbers. Also you should not start input with space or have 2 spaces joined together when you are running this code.

Read only one line of Integers from a file

I am trying to read a file which contains integers. The file has 40 lines, each having 80 integers. However when I run the following code, I get 40 lines and 3200 integers in each line (it reads the entire file for each line). How can I fix this.
while(input.hasNextLine()){
++rows;
Scanner colReader = new Scanner(input.nextLine());
while(colReader.hasNextInt()){
++columns;
colReader.nextInt();
}
colReader.close();
}
You can also simplify your code somewhat. You can keep on reading integers one by one.
Scanner input = new Scanner(new File("f:/numbs.txt"));
while (input.hasNextInt()) {
int v = input.nextInt();
System.out.println(v);
}
Because you are duplicated the loop, if you want to read a file, you can do the next
BufferedReader bufferReader = new BufferedReader(new FileReader(new File("")));
int line;
StringBuilder stringBuilder = new StringBuilder();
while ( (line =bufferReader.read()) != 0 ) {
// Do something
}

Read file and store values into two arrays, one for each line

I got this code here:
try{
FileReader file = new FileReader("/Users/Tda/desktop/ReadFiles/tentares.txt");
BufferedReader br = new BufferedReader(file);
String line = null;
while((line = br.readLine()) != null){
String[] values = line.split(",");
grp1 = new int[values.length];
for(int i=0; i<grp1.length; i++){
try {
grp1[i]= Integer.parseInt(values[i]);
}catch (NumberFormatException e) {
continue;
}
}
System.out.println(Arrays.toString(grp1));
}
System.out.println("");
br.close();
}catch(IOException e){
System.out.println(e);
}
This is what the file im reading contains.
grp1:80,82,91,100,76,65,85,88,97,55,69,88,75,97,81
grp2:72,89,86,85,99,47,79,88,100,76,83,94,84,82,93
Right now im storing the values into one int array.
But if i wanted to store each line of values into two arrays?
Thought about using Arrays.CopyOfRange somehow, and copy the values from the int array
into two new arrays.
This answer won't correspond to your question, but will give a hint to my comment under your question post.
Try this at the beginning of your while loop:
Use String.IndexOf() to find the first occurence of the char : into each line. This will be the beginning index for the second part.
Call String.Substring() from your new beginning index to line.length. This will give you the line without the characters and your first numbers aren't lost.
Before the while
List<int[]> groups = new ArrayList<>();
Before the end of the loop:
groups.add(grp1);
Afterwards:
for (int[] grp : groups) {
...
}
A List is useful for a growing "array".
groups.size() grp1.length
groups.get(3) grp1[3]
groups.set(3, x) grp1[3 = x

Read txt and save into array,java

have some problem reading a file in java and save each element into 2 arrays.
my txt is made like this
2,3
5
4
2
3
1
where the first line is the lenght of two array A=2 and B=3 and then the element of each array. I don't know how to save them into A and B and initialized the array with their lenght.
At the end each array will be A=[5,4] B=[2,3,1]
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("prova.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != " ") {
String[] delims = strLine.split(",");
String m = delims[0];
String n = delims[1];
System.out.println("First word: "+m);
System.out.println("First word: "+n);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
this is what i made..i used System.out.println.... just to print in console it's not necessary...Someone can help me, give me some advice?
thanks in advance
Again, break the big problem into little steps, solve each step.
Read first line.
Parse first line to get sizes of the 2 arrays.
Create the arrays.
Loop first array length times and fill the first array.
Loop second array length times and fill second array.
Close BufferedReader in a finally block (make sure to declare it before the try block).
Show results.
Match this answer with the steps outlined in #Hovercraft's answer
String strLine = br.readLine(); // step 1
if (strLine != null) {
String[] delims = strLine.split(","); // step 2
// step 3
int[] a = new int[Integer.parseInt(delims[0])];
int[] b = new int[Integer.parseInt(delims[1])];
// step 4
for (int i=0; i < a.length; i++)
a[i] = Integer.parseInt(br.readLine());
// step 5
for (int i=0; i < b.length; i++)
b[i] = Integer.parseInt(br.readLine());
br.close(); // step 6
// step 7
System.out.println(Arrays.toString(a));
System.out.println(Arrays.toString(b));
}
Notice, I called br.close(). With in.close() you're closing the inner stream only and that leaves BufferedReader still open. But closing the outer wrapper stream closes all the wrapped inner streams automatically. Note, that clean-up code like this should always go in a finally block.
Also, there's no need to have DataInputStream and InputStreamReader in the chain. Just wrap BufferedReader around a FileReader directly.
If all these classes are having you a bit confused; just remember Stream classes are used for reading at the byte level and Reader classes are used to read at character level. So, you only need Readers here.

converting one line string into individual integers

if i have this line in a file: 2 18 4 3
and i want to read it as individual integers, how could i?
i'm using bufferreader:
BufferedReader(new FileReader("mp1.data.txt"));
i have tried to use:
BufferedReader(new RandomAccessFile("mp1.data.txt"));
so i can use the method
.readCahr();
but i got an error
if i use
int w = in.read();
it will read the ASCII, and i want it as it is(in dec.)
i was thinking to read it as a string first, but then could i separate each number?
also i was thinking to let each number in a line, but the file i have is long with numbers
Consider using a Scanner:
Scanner scan = new Scanner(new File("mp1.data.txt"));
You can then use scan.nextInt() (which returns an int, not a String) so long as scan.hasNextInt().
No need for that ugly splitting and parsing :)
However, note that this approach will continue reading integers past the first line (if that's not what you want, you should probably follow the suggestions outlined in the other answers for reading and handling only a single line).
Furthermore, hasNextInt() will return false as soon as a non-integer is encountered in the file. If you require a way to detect and handle invalid data, you should again consider the other answers.
It's important to approach larger problems in software engineering by breaking them into smaller ones. In this case, you've got three tasks:
Read a line from the file
Break it into individual parts (still strings)
Convert each part into an integer
Java makes each of these simple:
Use BufferedReader.readLine() to read the line as a string first
It looks like the splitting is as simple as splitting by a space with String.split():
String[] bits = line.split(" ");
If that's not good enough, you can use a more complicated regular expression in the split call.
Parse each part using Integer.parseInt().
Another option for the splitting part is to use the Splitter class from Guava. Personally I prefer that, but it's a matter of taste.
You can split() the String and then use the Integer.parseInt() method in order to convert all the elements to Integer objects.
try {
BufferedReader br = new BufferedReader(new FileReader("mp1.data.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String[] split = line.split("\\s");
for (String element : split) {
Integer parsedInteger = Integer.parseInt(element);
System.out.println(parsedInteger);
}
}
}
catch (IOException e) {
System.err.println("Error: " + e);
}
Once you read the line using BufferedReader, you can use String.split(regex) method to split the string by space ("\\s").
for(String s : "2 18 4 3".split("\\s")) {
int i = Integer.parseInt(s);
System.out.println(i);
}
If you use Java 7+, you can use this utility method:
List<String> lines = Files.readAllLines(file, Charset.forName("UTF-8"));
for (String line: lines) {
String[] numbers = line.split("\\s+");
int firstNumber = Integer.parseInt(numbers[0]);
//etc
}
Try this;
try{
// Open the file that is the first
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//split line by whitespace
String[] ints = strLine.split(" ");
int[] integers = new int[ints.length];
// to convert from string to integers - Integer.parseInt ("123")
for ( int i = 0; i < ints.length; i++) {
integers[i] = Integer.parseInt(ints[i]);
}
// now do what you want with your integer
// ...
}
in.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}

Categories

Resources