I am looking to open a text file which is formatted as follows and to put it into an 2d arraylist where each object (and not each line) has its own index.
5
1 a w e r s 5 2 d 6
f s d e a 3 6 7 1 32
2 f s 6 d
4 s h y 99 3 s d
7 s x d q s
I have tried many solutions, most of those involving a while(scanner.hasNext()) or while(scanner.hasNextLine()) loops, assigning all the objects in a row to their own indice in a 1d arraylist, and then adding that arraylist to a 2d arraylist. But no matter what I do I do not get the result I want.
What I am in essence trying to do is something such as the scanner .hasNext() method which only grabs the next object within a line, and will not jump to the next line. An example of one of my tries is as follows:
while (scanner.hasNextLine()) {
ArrayList<Object> array = new ArrayList<Object>();
while(scanner.hasNext()0 {
String line = scanner.next();
array.add(line);
}
System.out.println(array);
2dArray.add(array);
}
scanner.nextLine();
}
You need to allocate a new array each time through the outer loop, rather than clearing the existing array. Also, it might be easiest to set up a new Scanner for each line:
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Scanner lineScanner = new Scanner(line);
ArrayList<String> array = new ArrayList<String>();
while (lineScanner.hasNext()) {
array.add(lineScanner.next());
}
my2Darray.add(array);
}
Use a BufferedReader to read the file one line at atime.
BufferedReader br = new BufferedReader(...);
while ((strLine = br.readLine()) != null) {
String[] strArray = strLine.split("\\s");
// do stuff with array
}
Then split the String on spaces, which gives you a String[], and is easily converted into a List. Something like this: How do I split a string with any whitespace chars as delimiters?
Related
I was practicing problems in JAVA for the last few days and I got a problem like this:
I/p: I Am A Good Boy
O/p:
I A A G B
m o o
o y
d
This is my code.
System.out.print("Enter sentence: ");
String s = sc.nextLine();
s+=" ";
String s1="";
for(int i=0;i<s.length();i++)
{
char c = s.charAt(i);
if(c!=32)
{s1+=c;}
else
{
for(int j=0;j<s1.length();j++)
{System.out.println(s1.charAt(j));}
s1="";
}
}
The problem is I am not able to make this design.My output is coming as each character in each line.
First, you need to divide your string with space as a delimiter and store them in an array of strings, you can do this by writing your own code to divide a string into multiple strings, Or you can use an inbuilt function called split()
After you've 'split' your string into array of strings, just iterate through the array of strings as many times as your longest string appears, because that is the last line you want to print ( as understood from the output shared) i.e., d from the string Good, so iterate through the array of strings till you print the last most character in the largest/ longest string, and exit from there.
You need to handle any edge cases while iterating through the array of strings, like the strings that does not have any extra characters left to print, but needs to print spaces for the next string having characters to be in the order of the output.
Following is the piece of code that you may refer, but remember to try the above explained logic before reading further,
import java.io.*;
import java.util.*;
public class MyClass {
public static void main(String args[]) throws IOException{
//BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
String[] s = sc.nextLine().split(" ");
// Split is a String function that uses regular function to split a string,
// apparently you can strings like a space given above, the regular expression
// for space is \\s or \\s+ for multiple spaces
int max = 0;
for(int i=0;i<s.length;i++) max = Math.max(max,s[i].length()); // Finds the string having maximum length
int count = 0;
while(count<max){ // iterate till the longest string exhausts
for(int i=0;i<s.length;i++){
if(count<s[i].length()) System.out.print(s[i].charAt(count)+" "); // exists print the character
else System.out.print(" "); // Two spaces otherwise
}
System.out.println();count++;
}
}
}
Edit: I am sharing the output below for the string This is a test Input
T i a t I
h s e n
i s p
s t u
t
I need to get multiple lines of input which will be integers from the console for my class problem. So far I have been using scanner but I have no solution. The input consists of n amount of lines. The input starts with an integer followed by a line of series of integers, this is repeated many times. When the user enters 0 that is when the input stops.
For example
Input:
3
3 2 1
4
4 2 1 3
0
So how can I read this series of lines and possible store each line as a element of an array using a scanner object? So far I have tried:
Scanner scan = new Scanner(System.in);
//while(scan.nextInt() != 0)
int counter = 0;
String[] input = new String[10];
while(scan.nextInt() != 0)
{
input[counter] = scan.nextLine();
counter++;
}
System.out.println(Arrays.toString(input));
You need 2 loops: An outer loop that reads the quantity, and an inner loop that reads that many ints. At the end of both loops you need to readLine().
Scanner scan = new Scanner(System.in);
for (int counter = scan.nextInt(); counter > 0; counter = scan.nextInt()) {
scan.readLine(); // clears the newline from the input buffer after reading "counter"
int[] input = IntStream.generate(scan::nextInt).limit(counter).toArray();
scan.readLine(); // clears the newline from the input buffer after reading the ints
System.out.println(Arrays.toString(input)); // do what you want with the array
}
Here for elegance (IMHO) the inner loop is implemented with a stream.
You could use scan.nextLine() to get each line and then parse out the integers from the line by splitting it on the space character.
As mWhitley said just use String#split to split the input line on the space character
This will keep integers of each line into a List and print it
Scanner scan = new Scanner(System.in);
ArrayList integers = new ArrayList();
while (!scan.nextLine().equals("0")) {
for (String n : scan.nextLine().split(" ")) {
integers.add(Integer.valueOf(n));
}
}
System.out.println((Arrays.toString(integers.toArray())));
I am importing a file that has the following:
1 2 3 4 5
4 5 6 7 8
10 11 12 13 14 15 16 17
11 13 15 17 19 21 23
4 5 5 6 76 7 7 8 8 8 8 8
23 3 4 3 5 3 53 5 46 46 4 6 5 3 4
I am trying to write a program that will take the first line and add it to ArrayList<Integer>s1 and the second line into ArrayList<Integer>s2. After that, I am calling another method that will use those two (UID.union(s1,s2)). However, I am unable to figure out how to add those numbers into the ArrayList. I wrote the following, but it doesn't work:
ArrayList<Integer> set1 = new ArrayList<Integer>();
TreeSet<Integer> s1 = new TreeSet<Integer>();
Scanner input = new Scanner(new File ("mathsetdata.dat"));
String str []= input.next().split(" ");
Set<String> s11 = new TreeSet<String>(Arrays.asList(str));
for (String k: s11)
{
set1.add(Integer.parseInt(k));
}
Also, I am using a loop that will use the first line as s1, the second as s2, and then call the other class and run it. Then, it will use the third line as s1 and the fourth as s2 and run it again.
Maybe you should use Scanner.nextLine()method. You use next() method will return a single character.
We know that nextInt(), nextLong(), nextFloat() ,next() methods are known as token-reading methods, because they read tokens separated by delimiters.
Although next() and nextLine() both read a string,but nextLine is not token-reading method. The next() method reads a string delimited by delimiters, and nextLine() reads a line ending with a line separator.
Further speak, if the nextLine() mehod is invoked after token-reading methods,then this method reads characters that start from this delimiter and end with the line separator. The line separator is read, but it is not part of the string returned by nextLine().
Suppose a text file named test.txt contains a line
34 567
After the following code is executed,
Scanner input = new Scanner(new File("test.txt"));
int intValue = input.nextInt();
String line = input.nextLine();
intValue contains 34 and line contains the characters ' ', 5, 6, and 7.
So in your code,you can replace with the following code:
Scanner input = new Scanner(new File ("mathsetdata.dat"));
String str []= input.nextLine().split(" ");
List<Integer> list = new ArrayList<Integer>(){};
Scanner input = new Scanner(new File ("mathsetdata.dat"));
while(input.hasNextLine()){
String[] strs= input.nextLine().split(" ");//every single line
for(String s :strs){
list.add(Integer.parseInt(s));
}
is it what you want maybe?
You are not reading file in right way also you are adding redundant code. I have added method to convert a line into List of Integers.
private static List<Integer> convertToList(String line) {
List<Integer> list = new ArrayList<Integer>();
for (String value : line.split(" ")) {
list.add(Integer.parseInt(value));
}
return list;
}
public static void main(String[] args) throws JsonSyntaxException, JsonIOException, FileNotFoundException {
Scanner input = new Scanner(new File("/tmp/mathsetdata.dat"));
while (input.hasNextLine()) {
String line = input.nextLine();
if (line.trim().length() > 0)
System.out.println(convertToList(line));
}
}
I think this is what you are seeking for:
public static List<String> readTextFileToCollection(String fileName) throws IOException{
List<String> allLines = Files.lines(Paths.get(fileName)).collect(Collectors.toList());
ArrayList<String> finalList = allLines.stream()
.map(e->{ return new ArrayList<String>(Arrays.asList(e.split(" ")));})
.reduce(new ArrayList<String>(), (s1,s2) -> UID.union(s1,s2));
return finalList;
}
In order to work this solution; your UID.union(s1,s2) should return the merged arraylist. That means, you should be able to write something like below without compilation errors:
ArrayList<String> mergedList = UID.union(s1,s2);
I'm trying to create a 2D array from a .txt file, where the .txt file looks something like this:
xxxx
xxxx
xxxx
xxxx
or something like this:
xxx
xxx
xxx
So I need to handle multiple sizes of a 2D array (Note: Each 2D array will not always be equal x and y dimensions). Is there anyway to initialize the array, or get the number of characters/letters/numbers per line and number of columns? I do not want to use a general statement, something like:
String[][] myArray = new Array[100][100];
And then would filling the array using filewriter and scanner classes look like this?
File f = new File(filename);
Scanner input = new Scanner(f);
for(int i = 0; i < myArray[0][].length; i++){
for(int j = 0; j < myArray[][0].length, j++){
myArray[i][j] = input.nextLine();
}
}
You have several choices as I see it:
Iterate through the file twice, the first time getting the array parameters, or
Iterate through it once, but fill up a List<List<SomeType>> possibly instantiating your Lists as ArrayLists. The latter will give you much greater flexibility in the short and long run.
(per MadProgrammer) The third option is to re-structure the file to provide the meta data required to make decisions about the size of the array.
For example, using your code,
File f = new File(filename);
Scanner input = new Scanner(f);
List<List<String>> nestedLists = new ArrayList<>();
while (input.hasNextLine()) {
String line = input.nextLine();
List<String> innerList = new ArrayList<>();
Scanner innerScanner = new Scanner(line);
while (innerScanner.hasNext()) {
innerList.add(innerScanner.next());
}
nestedLists.add(innerList);
innerScanner.close();
}
input.close();
Java Matrix can have each line (which is an array) by your size desicion.
You can use: ArrayUtils.add(char[] array, char element) //static method
But before that, you need to check what it the file lines length
Either this, you can also use ArrayList> as a collection which is holding your data
I have a .txt file that lists integers in groups like so:
20,15,10,1,2
7,8,9,22,23
11,12,13,9,14
and I want to read in one of those groups randomly and store the integers of that group into an array. How would I go about doing this? Every group has one line of five integers seperated by commas. The only way I could think of doing this is by incrementing a variable in a while loop that would give me the number of lines and then somehow read from one of those lines that is chosen randomly, but I'm not sure how it would read from only one of those lines randomly. Here's the code that I could come up with to sort of explain what I'm thinking:
int line = 0;
Scanner filescan = new Scanner (new File("Coords.txt"));
while (filescan.hasNextLine())
{
line++;
}
Random r = new Random(line);
Now what do I do to make it scan line r and place all of the integers read on line r into a 1-d array?
There is an old answer in StackOverflow about choosing a line randomly. By using the choose() method you can randomly get any line. I take no credit of the answer. If you like my answer upvote the original answer.
String[] numberLine = choose(new File("Coords.txt")).split(",");
int[] numbers = new int[5];
for(int i = 0; i < 5; i++)
numbers[i] = Integer.parseInt(numberLine[i]);
I'm assuming you know how to parse the line and get the integers out (Integer.parseInt, perhaps with a regular expression). If you're sing a scanner, you can specify that in your constructor.
Keep the contents of each line, and use that:
int line = 0;
Scanner filescan = new Scanner (new File("Coords.txt"));
List<String> content = new ArrayList<String>(); // new
while (filescan.hasNextLine())
{
content.add(filescan.next()); // new
line++;
}
Random r = new Random(line);
String numbers = content.get(r.nextInt(content.size()); // new
// Get numbers out of "numbers"
Read lines one by one from the file, store them in a list and generate a random number from the list's size and use it to get the random line.
public static void main(String[] args) throws Exception {
List<String> aList = new ArrayList<String>();
Scanner filescan = new Scanner(new File("Coords.txt"));
while (filescan.hasNextLine()) {
String nxtLn = filescan.nextLine();
//there can be empty lines in your file, ignore them
if (!nxtLn.isEmpty()) {
//add lines to the list
aList.add(nxtLn);
}
}
System.out.println();
Random r = new Random();
int randomIndex=r.nextInt(aList.size());
//get the random line
String line=aList.get(randomIndex);
//make 1 d array
//...
}