From data to ArrayList - java

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);

Related

Java Taking Multiple Line Input

How do I go about taking input that is multiple lines, such as
4 2 9
1 4 2
9 8 5
and placing it into an array of that is big enough to hold each line with no empty positions, or an arraylist. I've tried many ways to do this and cannot find a solution.
For example, if the user copied and pasted the above snippet as input, I want an array or arraylist to hold
["4 2 9", "1 4 2", "9 8 5"]
Try calling nextLine
Scanner s = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
while (s.hasNextLine()) {
list.add(s.nextLine());
}
System.out.println(list);
Note that the scanner will keep prompting for input. To stop this, you need to enter an end of line character. See this answer for how to do this.
Example input/output:
4 2 9
1 4 2
9 8 5
^D
[4 2 9, 1 4 2, 9 8 5]
try this:
List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
list.add(str);
}
You can use Scanner to read the input from console.
Try something like this:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
List<String> list = new ArrayList<String>();
while(scan.hasNextLine()) {
String str = scan.nextLine();
System.out.println(str);
list.add(str);
}
System.out.println(java.util.Arrays.toString(list.toArray()));
scan.close();
}

How to read an input file in java

Input file:
1/2/3/5/6
I want to store numbers 1 2 3 4 5 6
My code:
Scanner in= new Scanner(new FileReader("v.txt"));
in.split();
Is not there so how can I store these values?
1. There is a coolest trick about Scanner that you can read the whole file into a string.
String text = new Scanner(new FileReader("v.txt")).useDelimiter("\\A").next();
Source for Scanner Tricks
2. you can split the string by using / delimiters
3. you can go through the String one by one an convert each String to Integer number.
a. Integer.valueOf() which return Integer
b. Integer.parseInt() which return int
In Java 8
Code:
String text = new Scanner(new FileReader("1.txt")).useDelimiter("\\A").next();
String[] sp = text.split("/");
List<Integer> listIntegers = Stream.of(sp)
.map( s -> Integer.valueOf(s))
.collect(Collectors.toList());
listIntegers.forEach(i -> System.out.print(" " + i));
Output:
1 2 3 4 5 6
Needed Imports:
import java.util.stream.Collectors;
import java.util.stream.Stream;
First read the full line of text.
String line="";
while(in.hasNextLine(){
line=in.nextLine();
}
Then split the line by /
String[] arr=line.split("/");
If you want to get these as int values, you can use Integer.parseInt() to get int from String.
if you use Java 7:
List<String> lines = Files.readAllLines(Paths.get("path to file"), StandardCharsets.UTF_8);
try followind code:
Scanner in= new Scanner(new FileReader("v.txt"));
String tok[];
while(in.hasNextLine(){
tok=in.nextLine().spilt("/");
}
Input :
1/2/3/5/6
Output :
1
2
3
5
6
For more on such operations visit this link.

Turning a string into multiple arrays?

I'm a student who is learning java (just started this year. I just graduated so I can't ask my high school teacher for help, either), and I need some help on how to turn a string into multiple arrays(?).
However, after this I get stuck (because I can't find a way to break down the string for my purposes).
The file is read like this
Input: The first line will be the number of cases. For each case the
first line will be Susan’s work schedule, and the second line will be
Jurgen’s work schedule. The work schedules will be the date of the
month (1-30) which they work. The third line will be the size of the
initial TV.
The file in question:
3
2 5 10
2 4 10
60
2 4 10
2 5 10
60
1 2 3 4 7 8 10 12 14 16 18 20 24 26 28 30
1 2 3 6 9 10 17 19 20 21 22 23 25 27 28 29
20
I'm not sure how to go about this. I've tried .split(), but that only seems to work on the first row in the string. Any help/tips you might have would be greatly appreciated!
you may read your input by lines and then apply regex on them to separate numbers from string like:
String numbers = "1 2 3 4 7 8 10 12 14 16 18 20 24 26 28 30";
String[] singleNumbers = numbers.split(" ");
then you will have these numbers separated by space in singleNumbers array
Depending on how you are reading the file, you are probably using something like the following:
BufferedReader in = new BufferedReader(new FileReader("foo.in"));
Then, to read the file line by line:
String theLine = in.readLine();
Now you have the string corresponding to the line (in this case the first line, but you can call readLine() over and over to read them all), but note you do not read the 'whole' file at once to get all the Strings, as I think you are suggesting, rather the reader takes a line at a time.
Therefore, if you want all the lines held in an array, all you need to do is declare the array, and then read each line into it. Something like:
// Declare an array to put the lines into
int numberOfLines = 10;
String[] arrayOfStrings = new String[numberOfLines];
// Read the first line
String aLine = in.readLine();
int i = 0;
// If the line that has been read is null, it's reached the end of the file
// so stop reading
while(aLine != null){
arrayOfStrings[i] = aLine;
i++;
aLine = in.readLine();
}
// arrayOfStrings elements are now each line as a single String!
Of course, you may not know how many lines are in the file to be read in the first case, so declaring the size of the array is difficult. You could then look into a dynamically-scaling data structure such as ArrayList, but that is a separate matter.
Hey I got a great solution for you.
Just make a class to store each student's data like
import java.util.List;
public class Student {
private int noOfCases;
private List<String> workSchedule;
private List<String> initialTV;
//getter setters
}
Then this...
public static void main(String[] args) {
//3 students for reading 9 lines
//Susan, Jurgen and You ;)
Student[] students = new Student[3];
int linesRead = 0;
String aLine = null;
// read each line through aLine
for (Student student : students) {
//use buffered/scanner classes for reading input(each line) in aLine
while (aLine != null) {
++linesRead;
if (linesRead == 1) {
student.setNoOfCases(Integer.valueOf(aLine));
++linesRead;
} else if (linesRead == 2) {
student.setWorkSchedule(Arrays.asList(aLine.split(" ")));
++linesRead;
} else if (linesRead == 3) {
student.setInitialTV(Arrays.asList(aLine.split(" ")));
} else {
linesRead = 0;
}
}
}
}
}
If you need to read more lines/more student's records, just resize the Student Array!!
Given you already have your BufferedReader, you could try something like this to give you a multi dimensional array of your rows and columns:
BufferedReader reader = ...;
List<String[]> lines = new ArrayList<String[]>();
String input;
while((input = reader.readLine()) != null){
if (!input.trim().isEmpty()){
lines.add(input.split(" "));
}
}
String[][] data = lines.toArray(new String[lines.size()][]);

Taking input an arbitrary number of times

I am looking to solve a coding problem, which requires me to take the input an arbitary number of times with one integer at one line. I am using an ArrayList to store those values.
The input will contain several test cases (not more than 10). Each
testcase is a single line with a number n, 0 <= n <= 1 000 000 000.
It is the number written on your coin.
For example
Input:
12
2
3
6
16
17
My attempt to take input in Java:
List<Integer> list = new ArrayList<Integer>();
Scanner inp = new Scanner(System.in);
while(inp.hasNext()){
list.add(inp.nextInt());
}
However, when I try to print the elements of the list to check if I have taken the inputs correctly, I don't get any output. the corresponding correct code in C goes like this:
unsigned long n;
while(scanf("%lu",&n)>0)
{
printf("%lu\n",functionName(n));
}
Please help me fix this thing with Java.
(PS: I am not able to submit solutions in Java because of this )
You can do this one thing! At the end of the input you can specify some character or string terminator.
code:
List<Integer> list = new ArrayList<Integer>();
Scanner inp = new Scanner(System.in);
while(inp.hasNextInt())
{
list.add(inp.nextInt());
}
System.out.println("list contains");
for(Integer i : list)
{
System.out.println(i);
}
sample input:
10
20
30
40
53
exit
output:
list contains
10
20
30
40
53
Can you do something like this:
List<Integer> list = new ArrayList<Integer>();
Scanner inp = new Scanner(System.in);
while(inp.hasNextInt()){
list.add(inp.nextInt());
}
If there is some another value like character, loop finishes.

Adding lines of varying length to a 2d arraylist

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?

Categories