How to read an input file in java - 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.

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

From data to ArrayList

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

User enters numbers separated by spaces, tabs, or new lines

I am in an beginner java programming class and am stuck on something I know should be simple, but it's killing me. The user is prompted to enter any number of x,y values and can be entered separated by a space, a tab, or a new line. So it can be entered like this:
1.0 1.0 2.0 2.0 3.0 3.0 etc...
or
1.0 (tab) 1.0 (tab) 2.0 (tab) 2.0 (tab) etc...
or
1.0 1.0
2.0 2.0
3.0 3.0
etc...
Well that's fine and great but I don't know how to separate these numbers. I'm thinking of having an x var and a y var and would like to separate them into this, but how do I do this? My first thought was maybe an array but we haven't even covered those yet. I feel like this is ridiculously easy and I'm just missing it
If you take the input as a String you could do something like
String[] input = inputString.split(" ");
Then convert each element to your desired type.
You're going to want to use a regular expression for this - find all white space in the string, then split on that.
String[] vals = t1.split("[\\s]+");
\s is the whitespace character regex search pattern.
You can split a string up by space using the following:
String[] parts = userinput.split(" ");
You can split a string up by tab using the following:
String[] parts = userinput.split("\t");
You can split a string up by line return using the following:
String[] parts = userinput.split("\n");
note: you may beed to add a '/r' to the above \n
So, find your delimiter, split your string by that using one of the above (or more if needed)
then you should have all your data in a String array
I can offer you to use scanner. You can set your delimeters that can be entered.
Scanner s = new Scanner("This is a , test word \n ");
s.useDelimiter(",|\\n");
while(s.hasNext()){
System.out.println(s.next());
}
Here you go. [ \t] is a regular expression meaning either a space or a tab.
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
while (line != null && !line.isEmpty())
{
String[] arr = line.split("[ \t]");
for (int i = 0; i < arr.length; i += 2)
{
doSomething(Double.parseDouble(arr[i]), Double.parseDouble(arr[i+1]));
}
line = br.readLine();
}
}
static void doSomething(double x, double y)
{
System.out.println("x is "+x+", y is "+y);
}
You may want to also include some error checking.
you can use BufferedReader + Scanner to read data that are separated by spaces or newlines:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner input = new Scanner(br);
& read the numbers one by one using Scanner , which will wait until it meets a number then read it no matter what is separating them a space or a new line
int numbersCount = 5; //numbersCount is the count of the numbers you are wanting to read from the input , so if you are waiting 5 numbers then it will be 5.
int[] numbers = new int[numbersCount];
for (int i=0;i<numbersCount;i++)
{
numbers[i] = input.nextInt();
}
so the array numbers will contain all the numbers you want isA
hope this helps

Java - How to read integers separated by a space into an array

I am having trouble with my project because I can't get the beginning correct, which is to read a line of integers separated by a space from the user and place the values into an array.
System.out.println("Enter the elements separated by spaces: ");
String input = sc.next();
StringTokenizer strToken = new StringTokenizer(input);
int count = strToken.countTokens();
//Reads in the numbers to the array
System.out.println("Count: " + count);
int[] arr = new int[count];
for(int x = 0;x < count;x++){
arr[x] = Integer.parseInt((String)strToken.nextElement());
}
This is what I have, and it only seems to read the first element in the array because when count is initialized, it is set to 1 for some reason.
Can anyone help me? Would it be better to do this a different way?
There is only a tiny change necessary to make your code work. The error is in this line:
String input = sc.next();
As pointed out in my comment under the question, it only reads the next token of input. See the documentation.
If you replace it with
String input = sc.nextLine();
it will do what you want it to do, because nextLine() consumes the whole line of input.
String integers = "54 65 74";
List<Integer> list = new ArrayList<Integer>();
for (String s : integers.split("\\s"))
{
list.add(Integer.parseInt(s));
}
list.toArray();
This would be a easier way to do the same -
System.out.println("Enter the elements seperated by spaces: ");
String input = sc.nextLine();
String[] split = input.split("\\s+");
int[] desiredOP = new int[split.length];
int i=0;
for (String string : split) {
desiredOP[i++] = Integer.parseInt(string);
}
There are alternate ways to achieve the same. but when i tried your code, it seems to work properly.
StringTokenizer strToken = new StringTokenizer("a b c");
int count = strToken.countTokens();
System.out.println(count);
It prints count as 3. default demiliter is " "
I dont know how are you getting your input field. May be it is not returning the complete input in string format.
I think you are using java.util.Scanner for reading your input
java doc from scanner.
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace. The resulting tokens may then be
converted into values of different types using the various next
methods.
Hence the input is returning just one Integer and leaving the rest unattended
Read this. Scanner#next(), You should use Scanner#nextLine() instead
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
.
.
.
StringTokenizer st = new StringTokenizer(br.readLine());
int K = Integer.parseInt(st.nextToken());
int N= Integer.parseInt(st.nextToken());

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