I'm trying to read a text file with this format:
Array x
1,3,5,4
Array y
12,13,15,11
and put it in two array, but I only want the integer.
What delimiter should I use to ignore the String and the empty line?
Here's my code in putting the int to arrays. By the way, I'm using scanner to read the file:
Scanner sc = null;
try
{
sc = new Scanner(new FileInputStream("C:\\x.txt"));
sc.useDelimiter(""); // What will I put inside a quote to get only the int values?
}
catch(Exception e)
{
System.out.println("file not found!");
}
int[] xArray = new int[4];
int[] yArray = new int[4];
while (sc.hasNextInt( )){
for(int i=0; i<4; i++){
xArray[i] = sc.nextInt( );
}
for(int i=0; i<4; i++){
yArray[i] = sc.nextInt( );
}
}
What I want to get is
int[] xArray = {1,3,5,4}
int[] yArray = {12,13,15,11}
I hope you understand :)
Thanks.
I suggest you to use bufferedreader instead of scanner. You can use below code :
BufferedReader br=new BufferedReader(new FileReader("your file name"));
br.readLine(); //it will omit first line Array x
String x=br.readLine(); //it return second line as a string
String[] x_value=x.split(","); //You can parse string array into int.
This is for Array x. You can do the same for array y. and after that parse into int.
Related
I'm trying to read a text file and put each comma separated value in an array and put all of them inside a 2d array.But the code I have right now puts the whole line in the array
Scanner sc = new Scanner(new BufferedReader(new FileReader(path)));
int rows = 3;
int columns = 1;
String[][] myArray = new String[rows][columns];
while (sc.hasNextLine()) {
for (int i = 0; i < myArray.length; i++) {
String[] line = sc.nextLine().trim().split(" " + ",");
for (int j = 0; j < line.length; j++) {
myArray[i][j] = line[j];
}
}
}
System.out.println(Arrays.deepToString(myArray));
This is the text file:
A6,A7
F2,F3
F6,G6
Output
[[A6,A7], [F2,F3], [F6,G6]]
Expected Output
[[A6],[A7],[F2],[F3],[F6],[G6]]
The problem is that you are assigning the entire 2D array instead of just each item.
Here are several alternatives.
Use Files.lines to stream the file.
splitting on a comma creates the 1D array of two elements for each line
flatMap that to stream each item.
that map that to an array of one item.
then just store them in a 2D array.
String[][] array = null;
try {
array = Files.lines(Path.of("f:/MyInfo.txt"))
.flatMap(line->Arrays.stream(line.split(","))
.map(item->new String[]{item}))
.toArray(String[][]::new);
} catch (IOException ioe) {
ioe.printStackTrace();
}
if (array != null) {
System.out.println(Arrays.deepToString(array));
}
prints
[[A6], [A7], [F2], [F3], [F6], [G6]]
Here is an approach similar to yours.
List<String[]> list = new ArrayList<>();
try {
Scanner scanner = new Scanner(new File("f:/MyInfo.txt"));
while (scanner.hasNextLine()) {
String[] arr = scanner.nextLine().split(",");
for (String item : arr) {
list.add(new String[]{item});
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
There is no deepToString for Lists so you either iterate it or convert to a 2D array.
String[][] ar = list.toArray(String[][]::new);
System.out.println(Arrays.deepToString(ar));
prints
[[A6], [A7], [F2], [F3], [F6], [G6]]
i think you have to double the rows size and for each line just put one element and increment the i++
The declaration of the result array is not correct.
Since you want the end result should look like this, [[A6],[A7],[F2],[F3],[F6],[G6]], it is a 2-dimensional array with one row and six columns.
Considering it, I have changed and simplified your code.
int rows = 3;
String[][] r = new String[1][rows * 2];
FileInputStream fstream = new FileInputStream("/path/to/the/file")
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
while((line = br.readLine()) != null) {
String[] current = line.split(",");
r[0][i++] = current[0];
r[0][i++] = current[1];
}
Goal: To fill an array with doubles from a text file.
Error: Empty array printed.
A small part of my text file which contains close to 500 numbers, I only need the values and not the "Z" at the start:
Z, 10.9123728, 5.3872839283, 11.30903923, 20.128192821, 3.8716134
My code:
Scanner inFile = new Scanner(new File(filename1));
ArrayList<Float> values = new ArrayList<Float>();
while (inFile.hasNext()) {
String line = inFile.nextLine();
String[] nums = line.trim().split(",");
if(inFile.hasNextDouble()) {
float token = Float.parseFloat(nums[1].trim());
values.add(token);
}
}
System.out.println(values);
inFile.close();
You are using two different routes here. Pick one. If you want to use hasNextDouble then you have to set up your Scanner to use a comma as a delimiter. However if given your current code, just abandon the hasNextDouble. NOTE that I did not test this, this is just me typing in the editor, so there could be syntax issues.
Scanner inFile = new Scanner(new File(filename1));
ArrayList<Float> values = new ArrayList<Float>();
while (inFile.hasNext()) {
String line = inFile.nextLine();
String[] nums = line.trim().split(",");
for (String num : nums) {
try {
float float = Float.parseFloat(nums[i].trim());
values.add(token);
} catch (NumberFormatException nfe) {
// the 'z'
continue;
}
}
}
System.out.println(values);
inFile.close();
I'm trying to to read the file contents into a character array using the scanner class and I keep getting a string index out of bounds error from my code and I'm not sure what's wrong
File fileName = null;
if(0<args.length) {
fileName = new File(args[0]);
}
Scanner s = null;
try {
s = new Scanner(fileName);
s.useDelimiter(",");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
char[]array = new char[26];
while(s.hasNext()) {
for(int i=0; i<27; i++) {
array[i] = s.next().charAt(i);
}
}
As far as I can tell, your code is equivalent to the following, which has no out of bounds exceptions
char[]array;
while(s.hasNext()) {
array = s.next().toCharArray();
}
However, after that while loop, your array will only equal the very last scanned value.
If you have individual comma separated characters, you can use the following. You do not need a loop within the existing loop
char[]array = new char[26];
int i = 0;
while(s.hasNext()) {
array[i++] = s.next().charAt(0);
}
In any case, I suggest using StringTokenizer rather than a Scanner
In your for loop, you are trying to access a[26] but you have declared memory for 26 characters. So you can access only a[0] to a[25].
I have to read in a text file called test.txt. the first line of the text file are two integers. these integers tell you the rows and columns of the 2D char array. The rest of the file contains characters. the file looks a bit like: 4 4 FILE WITH SOME INFO except vertically on top of one another not horizontally. I must then read each of the rest of the contents of the file into the 2D char[][] array using nested for loops. I am not supposed to copy from one array to another. This is the code I have so far. I'm having trouble reading each character line by line into my 2D char array. Help been working at this for hours.
public static void main(String[] args)throws IOException
{
File inFile = new File("test.txt");
Scanner scanner = new Scanner(inFile);
String[] size = scanner.nextLine().split("\\s");
char[][] array = new char[Integer.parseInt(size[0])][Integer.parseInt(size[1])];
for(int i=0; i < 4; i++) {
array[i] = scanner.nextLine().toCharArray();
}
for(int k = 0; k < array.length; k++){
for(int s = 0; s < array[k].length; s++){
System.out.print(array[k][s] + " ");
}
System.out.println();
}
scanner.close();
}
}
If I have understood it correctly - file format is something like
4 4
FILE
WITH
SOME
INFO
Modify as below
Scanner scanner = new Scanner(inFile);
String[] size = scanner.nextLine().split("\\s");
char[][] array = new char[Integer.parseInt(size[0])][Integer.parseInt(size[1])];
for(int i=0; i < rows; i++) {
array[i] = scanner.nextLine().toCharArray();
}
Above code is for initialization of you char array. In order to print the same you can do something like
Arrays.deepToString(array);
Copying Tirath´s file format:
4 4
FILE
WITH
SOME
INFO
I would pass it into a 2d array as follows:
public static void main(String[] args){
char[][] receptor = null; //receptor 2d array
char[] lineArray = null; //receptor array for a line
FileReader fr = null;
BufferedReader br = null;
String line = " ";
try{
fr = new FileReader("test.txt");
br = new BufferedReader(fr);
line = br.readLine();//initializes line reading the first line with the index
int i = (int) (line.toCharArray()[0]-48); //we convert line to a char array and get the fist index (i) //48 = '0' at ASCII
int j = (int)(line.toCharArray()[1]-48); // ... get the second index(j)
receptor = new char[i][j]; //we can create our 2d receptor array using both index
for(i=0; i<receptor.length;i++){
line = br.readLine(); //1 line = 1 row
lineArray = line.toCharArray(); //pass line (String) to char array
for(j=0; j<receptor[0].length; j++){ //notice that we loop using the length of i=0
receptor[i][j]=lineArray[j]; //we initialize our 2d array after reading each line
}
}
}catch(IOException e){
System.out.println("I/O error");
}finally{
try {
if(fr !=null){
br.close();
fr.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} //end try-catch-finally
}
I want to read lines of numbers from a file. The code is as follows but the IDE shows NullPointerException runtime exception. Not sure what I am doing wrong.
//reading the contents of the file into an array
public static void readAndStoreNumbers() {
//initialising the new object
arr = new int[15][];
try {
//create file reader
File f = new File("E:\\Eclipse Projects\\triangle.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
//read from file
String nums;
int index = 0;
while ((nums = br.readLine()) != null) {
String[] numbers = nums.split(" ");
//store the numbers into 'arr' after converting into integers
for (int i = 0; i < arr[index].length; i++) {
arr[index][i] = Integer.parseInt(numbers[i]);
}
index++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
Your second dimension of arr is uninitialized, and you are invoking
arr[index].length
You could be running into an NPEX for two reasons.
You don't finish your definition of arr - it's not evident in your code that you declare arr as int arr[][];
Even if you had the above, you wouldn't have set aside space for your second array. What you have now is a jagged array; you can have elements of whatever length in the second dimension you wish in your second array.
The only modification I made to your code to get it to work would be the following line:
arr[index] = new int[numbers.length];
...after pulling elements into numbers, and before entering the loop.
you need to change -
for(int i=0; i<arr[index].length; i++) {
to
arr[index] = new int[numbers.length];
for (int i = 0; i < numbers.length; i++) {
Java doesn't have real multidimensional arrays. What you are using is actually an array of int arrays: new int[n][] actually creates an array with room for n objects of type int[].
Consequently you will have to initialize each of those int arrays separately. That would have been obvious from the fact that you never actually specified the length of the second dimension anywhere in your program.
I think you should use StringBuilder..
//reading the contents of the file into an array
public static void readAndStoreNumbers() {
//initialising the StringBuffer
StringBuilder sb = new StringBuilder();
try {
//create file reader
File f = new File("E:\\Eclipse Projects\\triangle.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
//read from file
String nums;
int index = 0;
while ((nums = br.readLine()) != null) {
String[] numbers = nums.split(" ");
//store the numbers into 'arr' after converting into integers
for (int i = 0; i < arr[index].length; i++) {
sb.append(Integer.parseInt(numbers[i])).append("\n");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}