This is some code that I found to help with reading in a 2D Array, but the problem I am having is this will only work when reading a list of number structured like:
73
56
30
75
80
ect..
What I want is to be able to read multiple lines that are structured like this:
1,0,1,1,0,1,0,1,0,1
1,0,0,1,0,0,0,1,0,1
1,1,0,1,0,1,0,1,1,1
I just want to essentially import each line as an array, while structuring them like an array in the text file.
Everything I have read says to use scan.usedelimiter(","); but everywhere I try to use it the program throws straight to the catch that replies "Error converting number". If anyone can help I would greatly appreciate it. I also saw some information about using split for the buffered reader, but I don't know which would be better to use/why/how.
String filename = "res/test.txt"; // Finds the file you want to test.
try{
FileReader ConnectionToFile = new FileReader(filename);
BufferedReader read = new BufferedReader(ConnectionToFile);
Scanner scan = new Scanner(read);
int[][] Spaces = new int[10][10];
int counter = 0;
try{
while(scan.hasNext() && counter < 10)
{
for(int i = 0; i < 10; i++)
{
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = scan.nextInt();
}
}
}
for(int i = 0; i < 10; i++)
{
//Prints out Arrays to the Console, (not needed in final)
System.out.println("Array" + (i + 1) + " is: " + Spaces[i][0] + ", " + Spaces[i][1] + ", " + Spaces[i][2] + ", " + Spaces[i][3] + ", " + Spaces[i][4] + ", " + Spaces[i][5] + ", " + Spaces[i][6]+ ", " + Spaces[i][7]+ ", " + Spaces[i][8]+ ", " + Spaces[i][9]);
}
}
catch(InputMismatchException e)
{
System.out.println("Error converting number");
}
scan.close();
read.close();
}
catch (IOException e)
{
System.out.println("IO-Error open/close of file" + filename);
}
}
I provide my code here.
public static int[][] readArray(String path) throws IOException {
//1,0,1,1,0,1,0,1,0,1
int[][] result = new int[3][10];
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
Scanner scanner = null;
line = reader.readLine();
if(line == null) {
return result;
}
String pattern = createPattern(line);
int lineNumber = 0;
MatchResult temp = null;
while(line != null) {
scanner = new Scanner(line);
scanner.findInLine(pattern);
temp = scanner.match();
int count = temp.groupCount();
for(int i=1;i<=count;i++) {
result[lineNumber][i-1] = Integer.parseInt(temp.group(i));
}
lineNumber++;
scanner.close();
line = reader.readLine();
}
return result;
}
public static String createPattern(String line) {
char[] chars = line.toCharArray();
StringBuilder pattern = new StringBuilder();;
for(char c : chars) {
if(',' == c) {
pattern.append(',');
} else {
pattern.append("(\\d+)");
}
}
return pattern.toString();
}
The following piece of code snippet might be helpful. The basic idea is to read each line and parse out CSV. Please be advised that CSV parsing is generally hard and mostly requires specialized library (such as CSVReader). However, the issue in hand is relatively straightforward.
try {
String line = "";
int rowNumber = 0;
while(scan.hasNextLine()) {
line = scan.nextLine();
String[] elements = line.split(',');
int elementCount = 0;
for(String element : elements) {
int elementValue = Integer.parseInt(element);
spaces[rowNumber][elementCount] = elementValue;
elementCount++;
}
rowNumber++;
}
} // you know what goes afterwards
Since it is a file which is read line by line, read each line using a delimiter ",".
So Here you just create a new scanner object passing each line using delimter ","
Code looks like this, in first for loop
for(int i = 0; i < 10; i++)
{
Scanner newScan=new Scanner(scan.nextLine()).useDelimiter(",");
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = newScan.nextInt();
}
}
Use the useDelimiter method in Scanner to set the delimiter to "," instead of the default space character.
As per the sample input given, if the next row in a 2D array begins in a new line, instead of using a ",", multiple delimiters have to be specified.
Example:
scan.useDelimiter(",|\\r\\n");
This sets the delimiter to both "," and carriage return + new line characters.
Why use a scanner for a file? You already have a BufferedReader:
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
Now you can read the file line by line. The tricky bit is you want an array of int
int[][] spaces = new int[10][10];
String line = null;
int row = 0;
while ((line = reader.readLine()) != null)
{
String[] array = line.split(",");
for (int i = 0; i < array.length; i++)
{
spaces[row][i] = Integer.parseInt(array[i]);
}
row++;
}
The other approach is using a Scanner for the individual lines:
while ((line = reader.readLine()) != null)
{
Scanner s = new Scanner(line).useDelimiter(',');
int col = 0;
while (s.hasNextInt())
{
spaces[row][col] = s.nextInt();
col++;
}
row++;
}
The other thing worth noting is that you're using an int[10][10]; this requires you to know the length of the file in advance. A List<int[]> would remove this requirement.
Related
I want to read data from a CSV file in Java and then put this data into a list. The data in the CSV is put into rows which looks like:
Data, 32, 4.3
Month, May2, May 5
The code I have currently only prints the [32].
ArrayList<String> myList = new ArrayList<String>();
Scanner scanner = new Scanner(new File("\\C:\\Users\\Book1.csv\\"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
myList.add(scanner.next());
for (int i = 0; i <= myList.size(); i++) {
System.out.println(myList.toString());
}
scanner.close();
}
Maybe this code can help you, maybe this code is different from yours, you use arrayList while I use regular array.
Example of the data:
Farhan,3.84,4,72
Rajab,2.98,4,72
Agil,2.72,4,72
Alpin,3.11,4,73
Mono,3,6,118 K
imel,3.97,7,132
Rano,2.12,6,110
Kukuh,4,1,22
Placing data on each row in a csv file separated by commas into the array of each index
int tmp = 0;
String read;
Mahasiswa[] mhs = new Mahasiswa[100];
BufferedWriter outs;
BufferedReader ins;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
try {
ins = new BufferedReader(new FileReader("src/file.csv"));
tmp = 0;
while ((read = ins.readLine()) != null) {
String[] siswa = read.split(",");
mhs[tmp] = new Mahasiswa();
mhs[tmp].nama = siswa[0];
mhs[tmp].ipk = Float.parseFloat(siswa[1]);
mhs[tmp].sem = Integer.parseInt(siswa[2]);
mhs[tmp].sks = Integer.parseInt(siswa[3]);
tmp++;
i++;
}
ins.close();
} catch (IOException e) {
System.out.println("Terdapat Masalah: " + e);
}
Print the array data
tmp = 0;
while (tmp < i) {
System.out.println(mhs[tmp].nama + "\t\t" +
mhs[tmp].ipk + "\t\t" +
mhs[tmp].sem + "\t\t" +
mhs[tmp].sks);
tmp++;
}
ArrayList<String> myList = new ArrayList<String>();
try (Scanner scanner = new Scanner(new File("C:\\Users\\Book1.csv"))) {
//here at your code there are backslashes at front and end of the path that was the
//main reason you are not able to read csv file
scanner.useDelimiter(",");
while (scanner.hasNext()) {
myList.add(scanner.next());
}
for (int i = 0; i < myList.size(); i++) { //remember index is always equal to "length - 1"
System.out.println(myList);
}
} catch (Exception e) {
e.printStackTrace();
}
you also did not handle the FileNotFoundException
Hope this helps:)
I'm working on a project and I'm trying to count
1) The number of words.
2) The number of lines in a text file.
My problem is that I can't figure out how to detect when the file goes to the next line so I can increment lines correctly. Basically if next is not a space increment words and if next is a new line, increment lines. How would I do this? Thanks!
public static void readFile(Scanner f) {
int words = 0;
int lines = 0;
while (f.hasNext()) {
if (f.next().equals("\n")) {
lines++;
} else if (!(f.next().equals(" "))) {
words++;
}
}
System.out.println("Total number of words: " + words);
System.out.println("Total number of lines: " + lines);
}
Try this:
public static void readFile(Scanner f) {
int words = 0;
int lines = 0;
while (f.hasNextLine()) {
String line = f.nextLine();
lines++;
for (String token : line.split("\\s+")) {
if (!token.isEmpty()) {
words++;
}
}
}
System.out.println("Total number of words: " + words);
System.out.println("Total number of lines: " + lines);
}
Do you have to use InputStream? (Yes) It is better to use a BufferedReader with an InputStreamReader passed in so you can read the file line by line and increment while doing so.
numLines = 0;
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = br.readLine()) != null)
{
numLines++;
// process the line.
}
}
Then to count the words just split the string using a regular expression that finds whitespaces. myStringArray = MyString.Split(MyRegexPattern); will then return a String[] of all the words. Then all you do is numWords += myStringArray.length();
You can use an InputStreamReader to create a bufferedreader which can read a file line by line:
int amountOfLines = 0;
try {BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))} catch (Exception e) {e.printStackTrace();}
String line;
while ((line = br.readLine()) != null{
numLines++;
// process the line.
}
You can then use the split(String) method to separate every part
Try following:
public static void readFile(Scanner f) {
int words = 0;
int lines = 0;
while (f.hasNextLine()) {
String line = f.nextLine();
String[] arr = line.split("\\s");
words += arr.length;
lines++;
}
System.out.println("Total number of words: " + words);
System.out.println("Total number of lines: " + lines);
}
So, I'm working on a procedure that has an entry of a txt file called orders that specifies the number of words to bold and wich words must be bolded. I've managed to to it for one word but when i try with two words the output gets doubled. For example:
Input:
2
Ophelia
him
Output:
ACT I
ACT I
SCENE I. Elsinore. A platform before the castle.
SCENE I. Elsinore. A platform before the castle.
FRANCISCO at his post. Enter to him BERNARDO
FRANCISCO at his post. Enter to *him* BERNARDO
Here's my code, can anyone help me? PS: Ignore the boolean I guess.
static void bold(char bold, BufferedReader orders, BufferedReader in, BufferedWriter out) throws IOException
{
String linha = in.readLine();
boolean encontrou = false;
String[] palavras = new String[Integer.parseInt(orders.readLine())];
for (int i = 0; i < palavras.length; i++)
{
palavras[i] = orders.readLine();
}
while (linha != null)
{
StringBuilder str = new StringBuilder(linha);
for (int i = 0; i < palavras.length && !encontrou; i++)
{
if (linha.toLowerCase().indexOf(palavras[i]) != -1)
{
str.insert((linha.toLowerCase().indexOf(palavras[i])), bold);
str.insert((linha.toLowerCase().indexOf(palavras[i])) + palavras[i].length() + 1, bold);
out.write(str.toString());
out.newLine();
}
else
{
out.write(linha);
out.newLine();
}
}
linha = in.readLine();
}
}
This merits a regular expression replace of WORD-BOUNDARY + ALTERNATIVES + WORD-BOUNDARY.
String linha = in.readLine(); // Read number of words to be bolded.
String[] palavras = new String[Integer.parseInt(orders.readLine())];
for(int i = 0; i < palavras.length; i++){
palavras[i]=orders.readLine();
}
// We make a regular expression Pattern.
// Like "\\b(him|her|it)\\b" where \\b is a word-boundary.
// This prevents mangling "shimmer".
StringBuilder regex = new StringBuilder("\\b(");
for (int i = 0; i < palavras.length; i++) {
if (i != 0) {
regex.append('|');
}
regex.append(Pattern.quote(palavras[i]));
}
regex.append(")\\b");
Pattern pattern = Pattern.compile(regex.toString(), Pattern.CASE_INSENSITIVE);
boolean encontrou = false;
linha = in.readLine(); // Read first line.
while(linha != null){
Matcher m = pattern.matcher(linha);
String linha2 = m.replaceAll(pattern, "*$1*");
if (linha2 != linha) {
encontrou = true; // Found a replacement.
}
out.write(linha2);
out.newLine();
linha = in.readLine(); // Read next line.
}
A replaceAll (instead of replaceFirst) then replaces all occurrences.
It's writing out twice because you output your StringBuilder (out.write(str.toString())) for the line (linha) every time you iterate through it, which will be at least the number of words in the lookup list.
Move the out.write() statements outside the loop and you should be fine.
Note this will only find one match in each line for each word. If you need to find more than one, the code is a little more complicated. You need to introduce a while loop instead of your if test for matching, or you could consider using replaceAll() using a regular expression based on your word palavras[i]. Ensuring you respected the capitalisation of the original is not simple there, but possible.
Fixed version
static void bold(char bold, BufferedReader orders, BufferedReader in, BufferedWriter out)
throws IOException
{
String linha = in.readLine();
boolean encontrou = false;
String[] palavras = new String[Integer.parseInt(orders.readLine())];
for (int i = 0; i < palavras.length; i++)
{
palavras[i] = orders.readLine();
}
while (linha != null)
{
StringBuilder str = new StringBuilder(linha);
for (int i = 0; i < palavras.length && !encontrou; i++)
{
if (linha.toLowerCase().indexOf(palavras[i]) != -1)
{
str.insert((linha.toLowerCase().indexOf(palavras[i])), bold);
str.insert(
(linha.toLowerCase().indexOf(palavras[i])) + palavras[i].length() + 1,
bold);
}
}
out.write(str.toString());
out.newLine();
linha = in.readLine();
}
}
With replaceAll
static void bold(char bold, BufferedReader orders, BufferedReader in, BufferedWriter out)
throws IOException
{
String linha = in.readLine();
boolean encontrou = false;
String[] palavras = new String[Integer.parseInt(orders.readLine())];
for (int i = 0; i < palavras.length; i++)
{
palavras[i] = orders.readLine();
}
while (linha != null)
{
for (int i = 0; i < palavras.length && !encontrou; i++)
{
String regEx = "\\b("+palavras[i]+")\\b";
linha = linha.replaceAll(regEx, bold + "$1"+bold);
}
out.write(linha);
our.newLine();
linha = in.readLine();
}
}
P.S. I've left the found boolean (encontrou) in, although it is not doing anything at the moment.
i have the file which has data stored as " Integer-> \t(tab)-> String ->couple of space-> ".
Am I doing Wrong?
What I am doing is.
Trie t = new Trie();
BufferedReader bReader = new BufferedReader(new FileReader(
"H:\\100kfound.txt"));
String line;
String[] s = null;
while ((line = bReader.readLine()) != null) {
s = line.split("\t");
}
int i;
for (i = 0; i < s.length; i++) {
System.out.println(s[i]);
if (!(s[i].matches("\\d+"))) {
t.addWord(s[i]);
System.out.println(s[i]);
}
}
What I can see by debugging it is going properly till while loop but in for loop it just stores two strings and prints the same.
You might want to and a ^[0-9]+$ for the expressions so you just get complete integers. Without the ^ and $ you could be matching other characters like tt55gh would match.
if (!(s[i].matches("^[0-9]+$"))) {
}
Per the comment above you need to move the for loop inside the while loop.
while ((line = bReader.readLine()) != null) {
s = line.split("\t");
for (int i = 0; i < s.length; i++) {
System.out.println("Value "+i+": "+s[i]);
if (!(s[i].matches("^[0-9]+$"))) {
t.addWord(s[i]);
System.out.println("Integer "+i+": "+s[i]);
}
}
}
I have file named input1.txt with contents as below:
a b c d
b d
c d
d e
I want to read it and put them in 2-dimensional array of Strings. I have written code for it. But it is showing NULL POINTER EXCEPTION. Where may be the error? Below is my code:
I am getting the exception in line graphNodes[i][j] = s;
BufferedReader br = null;
BufferedReader cr = null;
int lines = 0;
try {
br = new BufferedReader(new FileReader(filename));
try {
while (br.readLine() != null) {
lines++;
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
List<String> nodes = new ArrayList<String>();
String[][] graphNodes = new String[lines][];
String[] line = new String[lines];
int i = 0;
int j = 0, x = 0;
try {
cr = new BufferedReader(new FileReader(filename));
while (cr.readLine() != null) {
line[x] = cr.readLine();
System.out.println("Line is: " + line[x]);
String[] letters = line[x].split(" ");
for (String s : letters) {
System.out.println("Letter is " + s);
graphNodes[i][j] = s;
j++;
}
i++;
x++;
}
} catch (IOException e) {
e.printStackTrace();
}
the graphNodes is missing column length
String[][] graphNodes = new String[lines][];
in your problem, once you get letters, you can initialize column of 2d array
String[] letters = line[x].split(" ");
graphNodes[i] = new String[letters.length];
You need to instantiate graphNodes[i] before accessing its j index.
I believe you're having issues with the following bit of code:
try {
cr = new BufferedReader(new FileReader(filename));
while (cr.readLine() != null) {
line[x] = cr.readLine();
System.out.println("Line is: " + line[x]);
String[] letters = line[x].split(" ");
for (String s : letters) {
System.out.println("Letter is " + s);
graphNodes[i][j] = s;
j++;
}
i++;
x++;
}
}
This while statement says "while cr.readLine() != null" and at that very moment it read the first line of the file, compared it with null, and it wasn't null so it enters the loop. You then told it to set line[x] equal to cr.readLine() which it then reads the next line of the file, and sets it equal to line[x]. Thus skipping the first line of code doing nothing more with it than using it to check the while loop condition.
I think what you want in your while loop is something like this
try {
cr = new BufferedReader(new FileReader(filename));
for(String lineValue = cr.readLine(); lineValue != null; x++, lineValue = cr.readLine()) {
line[x] = lineValue;
System.out.println("Line is: " + line[x]);
String[] letters = line[x].split(" ");
for (String s : letters) {
System.out.println("Letter is " + s);
graphNodes[i][j] = s;
j++;
}
i++;
}
}
But as someone mentioned previously, You need to declare the size of your 2 dimensional array. For the sake of this loop I just made it String[lines][100] but you'll want to adjust that to meet your needs (however long you anticipate your longest line of letters to be.
Well for one, you are not specifying a value for the second dimension: String[][] graphnodes = new String[lines][].
This means you are basically trying to set s to a value that cannot exist.
you might try defining String[] letters first then doing something like String[][] graphnodes = new String[lines][letters.getLength()];
also,
while (cr.readLine() != null) should be while (cr.hasNextLine())
your code would also look a lot cleaner if you did something like:
for (int i = 0, j = 0, x = 0; cr.hasNextLine(); i++, x++) {
line[x] = cr.readLine();
System.out.println("Line is: " + line[x]);
String[] letters = line[x].split(" ");
for (String s : letters) {
System.out.println("Letter is " + s);
graphNodes[i][j] = s;
j++;
}
}
First of All you don't need to read the files twice. Once to get the number of lines and the other to get the actual data.
You need to read the lines and put them directly in a List. Then you can do whatever you need with that list.