How to make an array from a text file - java

let me start off by saying that I am a fairly new Java programmer, and what I am trying to attempt is a bit over my head. Thus, I came here to try to learn it.
Okay, so here's the issue: I am trying to build a program that makes a 2d array from values in a text document. The text document has three columns and many rows (100+)...basically a [3][i] array.
Here's what I can do: I understand how to read the text file using bufferedReader. Here is a sample program I have that prints the text exactly how it looks in the text file (I apologize ahead for bad formatting; it's my first time on these forums):
import java.io.BufferedReader;
import java.io.FileReader;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("RA.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String[] nums = line.split(",");
for (String str : nums) {
System.out.println(str);
}
}
br.close();
}
}
This is what is printed:
00 03 57.504
02 04 03.796
00 06 03.386
03 17 43.059
00 52 49.199
05 52 49.555
etc, etc.
Please help me in making an array with values. Thank you!

define a list outside your while loop like
List list = new LinkedList();
Inside your while loop, add the splitted array to the list, like
list.add(line.split(","));
After the while loop convert your list to an array, resulting in a 2D array:
Foo[] array = list.toArray(new Foo[list.size()]);

Related

Compact splitting and new line manipulation in java with ArrayLists and HashMaps

I am still in the process of developing this code and I am looking ideas to do this in a efficient and compact ways as I intend to embed this in a separate java code. I am open to ideas for other methods too although I wold prefer HashMap or ArrayList methods
I have a file that I am working with that looks like this:
053 100% BRAN A0 B1 C01 E0
054 100% NATURAL A0 B1 C01 E0 F0 G0
the end product of this code has to look like
053 016% BRAN A0
053 100% BRAN B1
053 100% BRAN C01
053 100% BRAN E0
054 100% NATURAL A0
054 100% NATURAL B1
054 100% NATURAL C01
054 100% NATURAL E0
054 100% NATURAL F0
054 100% NATURAL G0
Please note that the file is very large. All columns are tab separated and the last column as space separated elements.
EDIT: I am sorry I should have framed my question better.I was thinking of collections because after doing this I need to be able to access all the lines with different keys (the repeating values of the first column).
If the pattern is fixed, then this can be done using RegEx. The get(); will take each line as input and returns the list of all combinations for that input string
public static void main(String[] args) {
String input="053 100% BRAN A0 B1 C01 E0";
System.out.println(get(input));
}
public static List<String> get(String input){
List<String> list = new ArrayList<String>();
String regEx="((?:\\d*)\\s(?:\\d*)%\\s(?:[A-Z]*))([\\s]*)([\\sA-Z0-9]*)";
Matcher matcher = Pattern.compile(regEx).matcher(input);
String firstHalf="";
String codes="";
if(matcher.matches()) {
firstHalf=matcher.group(1)+matcher.group(2);
codes=matcher.group(3);
}
for (String code : codes.split("\\s")) {
list.add(firstHalf+code);
}
return list;
}
It's unclear why you need a collection at all. Just manipulate the strings:
for (String line : input) {
String prefix = line.substring(0, 20); // Or however you decide on the line prefix.
String suffix = line.substring(20);
for (String part : suffix.split(" ")) {
System.out.printf("%s%s%n", prefix, part);
}
}
You can do it more efficiently than this, by using a PrintWriter to avoid explicitly constructing the substrings/split array.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class Test {
public static void main (String[] args){
List<String[]> myList = new ArrayList<>();
//read each line of your file and split it by \s+
try (Stream<String> stream = Files.lines(Paths.get("C:\\temp\\xyz.txt"))) {
stream.forEach( line->{
String[] splited = line.split("\\s+");
//iterate from 4th element of your splited array to last
//and add the first three elements and the ith element to your list
for(int i = 3; i<splited.length; i++){
myList.add(new String [] {splited[0] ,splited[1], splited[2], splited[i]});
}
});
} catch (IOException ex) {
ex.printStackTrace();
}
//print or do other stuff with your list
myList.forEach(e->{System.out.println(Arrays.toString(e));});
}
}

Finding two specific numbers in a list using string tokenizer

I'm trying to find two specific numbers (25,55) in a input list by converting them to tokens. e.g. below - string list = (52 98 55 86 42 25 87 566 56 843).
Just for context, the numbers are prices for books bought in a week for a library.
If they are both in a line only then I want to know (print "both"). If only one of them is in the line or something like 5562 or 3259 (part of another number), i want a return of "no". I guess that's why I'm converting them to tokens.
This code below is not working unless i remove the else statement and even when i do remove it, it prints out "both" no matter what I numbers i put in, even if there's no 25 or 55. Sorry if this seems like a dumb question, pretty new to coding.
package part;
import java.io.File;
import java.io.IOException;
import java.util.StringTokenizer;
public class Part {
public static void main(String[] args) throws Exception {
String list = "52 98 55 86 42 25 87 566 56 843";
StringTokenizer tokenizer = new StringTokenizer(list);
String rp = tokenizer.nextToken();
if (rp.equals("25") && rp.equals ("55")){
System.out.println("both");
} else {
System.out.println("no");
}
}
StringTokenizer works like ResultSet when fetching queries in DB side. Considering it, you should do something like this:
public static void main(String[] args) throws Exception {
String list = "52 98 55 86 42 25 87 566 56 843";
List<String> tokenList = new ArrayList<>();
StringTokenizer tokenizer = new StringTokenizer(list);
while(tokenizer.hasMoreTokens()){
tokenList.add(tokenizer.nextToken());
}
if(tokenList.contains("25") && tokenList.contains("55")){
System.out.println("both");
} else {
System.out.println("no");
}
}
StringTokenizer class is deprecated now. It is recommended to use split() method of String class or regex (Regular Expression).
Try using below code if you want to check that the contains both of them.
String list = "52 98 55 86 42 25 87 566 56 843";
String[] strarr = list.split("\\s+");
boolean first;
boolean second;
for(String str:strarr){
if(str.equals("25")) first=true;
if(str.equals("55")) second=true;
if(first && second) break;
}
if(first && second) System.out.println("both");
else System.out.println("no");

Why do I keep receiving an inputmismatchexception on my array?

I have been running through this array of objects trying to figure out what I am doing wrong and I can't see the error. This program runs through the first iteration bringing in Austria and all its subsequent information but will not move onto the second part of the array. I thought it might be that it's somehow taking each variable from the countries class and making it its own spot in the array but that can't be it because I have increased the array size to 64 and it still stops at the end of Austria. I have been able to get it to go a bit further by placing print statements after each item is added and it seems to be adding an unaccounted for blank line in it for some reason and I'm not sure why. any help that could be given would be greatly appreciated.
This is my test code with the data list:
import java.util.Scanner;
import java.io.*;
public class Test {
public static void main (String [] args) throws IOException {
final String INPUT_FILE = "CountriesInfo2.txt";
FileReader inputDataFile = new FileReader (INPUT_FILE);
Scanner read = new Scanner (inputDataFile);
Countries[] c = new Countries[8];
for (int i = 0; i < c.length; i++) {
c[i] = new Countries();
c[i].countryName = read.nextLine();
c[i].latitude = read.nextLine();
c[i].longitude = read.nextLine();
c[i].countryArea = read.nextInt();
c[i].countryPopulation = read.nextInt();
c[i].countryGDP = read.nextDouble();
c[i].countryYear = read.nextInt();
sop ("" + c[i].countryName + "\n" + c[i].latitude+"\n"+c[i].longitude+"\n"+c[i].countryArea+"\n"+
c[i].countryPopulation+"\n"+c[i].countryGDP+"\n"+c[i].countryYear);
}// end for
} // End Main
public static void sop (String s) {
System.out.println(s);
} // End sop
} // end class
Austria
47 20 N
13 20 E
83871 8754513 417.2 2016
Belgium
50 50 N
04 00 E
30528 11491346 509.5 2016
Czech Republic
49 45 N
15 30 E
7886
10674723
350.7
2016
France
46 00 N
02 00 E
643801
67106161
2734.0
2016
This list is supposed to be one line for each bit of information with lat-long having 2 sets of double digits and a letter each.
nextLine() automatically moves the scanner down after returning the current line. Rather I would advise you do as following
read each line using String data = scanner.nextLine();
split the data using space separator String[] pieces =
data.split("\\s+");
set the pieces to Country attributes by converting them in to
their appropriate type.
eg. c[i].countryName = pieces[0];
`c[i].latitude = piece[1];`

Storing content of txt file in an array

I have a .txt file which looks like 43 78 63 73 99 ....i.e.,
all its values are separated by spaces.
I want each of them to be added into an array,such that
a[0]=43
a[1]='78
a[2]=63 and so on.
How can I do this in Java..Please explain
Read the file into a string. Then spilt the string on the space into a string array.
Use a filereader to read in the values
E.g.
Scanner sc = new Scanner(new File("yourFile.txt"));
Then you read all the integers from the file and put them into an integer array.
Java Scanner class documentation
Java File class
Well I would do it by storing the text file into a string. (as long as it's not too big) Then I would just use .split(" ") to store it into an array.
Like this:
String contents = "12 32 53 23 36 43";
//pretend this reads from file
String[] a = contents.split(" ");
Now the array 'a' should have all the values stored in it. If you want the array to be an int, you could use an int array, and use Integer.toString() to convert data types.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class readTextToIntArray {
public static void main(String... args) throws IOException {
BufferedReader reader=new BufferedReader(new FileReader("/Users/GoForce5500/Documents/num.txt"));
String content;
List<String> contentList=new ArrayList<String>();
while((content=reader.readLine())!=null){
for(String column:content.split(" ")) {
contentList.add(column);
}
}
int[] result=new int[contentList.size()];
for(int x=0;x<contentList.size();x++){
result[x]=Integer.parseInt(contentList.get(x));
}
}
}
You may use this.

How to read the first element of a text file and if it matches it, to read the rest of the line?

I'm trying to check if the text file contains "Circle" or "Square" and if so to read the rest of the line. I have tried using scan.next()=="Circle" but that doesn't seem to work.
EDIT: The numbers refer to x and y coordinates which will be implemented into an instance of a class. In this case, Square and Circle.
Text File:
Circle 50 60 40 50 50
Square 250 260 45 -50 -50
If you are reading from a text file try using a BufferedReader and then using readLine and then using .equals() instead of ==
An example:
BufferedReader reader = new BufferedReader(new FileReader(myTextFile));
String lineOne = reader.readLine();
if(lineOne.equals("circle"))
{
//do something
}
In Java, the “==” operator is used to compare 2 objects. It checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.
So you should make use of equals. But in your case, if a line starts with circle or square you have to read the line from the given file.
Can you use the following condition and check if it works with scanner itself?
String line = sc.next();
if (line.startsWith("Circle") || line.startsWith("Square")){
//Your logic
}
Try this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class FileReader {
public FileReader() {
Scanner scanner;
List<String> list;
try {
list = new ArrayList<>();
scanner = new Scanner(new File("file.txt"));
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
if (!s.startsWith("Circle") && !s.startsWith("Square")) {
break;
}
System.out.println(s);
list.add(s);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new FileReader();
}
The file is called file.txt:
Circle 50 60 40 50 50
Square 250 260 45 -50 -50
False 50 60 40 50 50
If you compare Strings, always use equals not ==. Check this out

Categories

Resources