How to get int array from string array - java

File myFile = new File(
Environment.getExternalStorageDirectory().getAbsolutePath(),
"Notes/test.txt"
);
BufferedReader br = new BufferedReader(new FileReader(myFile));
String line = br.readLine();
while ((line = br.readLine()) != null) {
b = line.split(",");
xpoints = new int[b[0].length()];
ypoints = new int[b[1].length()];
for (int i = 1; i < b[0].length(); i++) {
xpoints[i] = Integer.parseInt(b[0]);
ypoints[i] = Integer.parseInt(b[1]);
}
/*direction(xpoints, ypoints);*/
}
br.close();
Here, I get X and Y value from b[0] and b[1]. I want to store this values in integer array(like int []x and int []y).How can i get all these values in array as i said earlier?

You should parse your String into int like:
x[i] = Integer.parseInt(str);
for every single String representation of each int element
beware to provide into str though only integer because it will throw NumberFormatException otherwise.

You can iterate over the String array in a loop and then store the values in an int array of the same size.
int[] intArray = new int[b.length];
for(int i = 0; i < b.length; i++){
try{
intArray[i] = Integer.parseInt(b[i]);
catch(NumberFormatException e){
//handle exception
}
}

In your while statement when you do a split do this:
String[] b = line.split(splitsby);
int[] intArray = new int[b.length];
for (int stringIndex = 0; stringIndex < b.length; stringIndex++) {
intArray[stringIndex] = Integer.parseInt(b[stringIndex]);
}
System.out.println("X = " + intArray[0] + " Y = " + intArray[1]);
This is assuming that every value in b can be parsed as an Integer

Since you dont know the exact size of the elements you will get from file, I suggest you to create a ArrayList.
Arralist<Integer> a=new ArrayList<Integer>();
Arralist<Integer> b=new ArrayList<Integer>();
Then
File myFile = new File(Environment
.getExternalStorageDirectory().getAbsolutePath(),
"Notes/test.txt");
BufferedReader br = new BufferedReader(new FileReader(myFile));
String line=br.readLine();
String splitsby = ",";
while ((line = br.readLine()) !=null) {
String[] b=line.split(splitsby);
System.out.println("X = "+b[0]+" Y = "+b[1]);
a.add(Integer.parseInt(b[0]);
b.add(Integer.parseInt(b[1]);
}
br.close();

You can add this method:
private ArrayList<Integer> getIntegerArray(ArrayList<String> stringArray) {
ArrayList<Integer> result = new ArrayList<Integer>();
for(String stringValue : stringArray) {
try {
// convert String to Integer and store it into integer array list
result.add(Integer.parseInt(stringValue));
} catch (NumberFormatException nfe) {
// System.out.println("Could not parse " + nfe);
Log.w("NumberFormat", "Parsing failed! " + stringValue + " can not be an integer");
}
}
return result;
}

You can use Integer.parseInt() method to convert string into integer. you have to go through each string array element to use above method. Following like code can be used in any place as per your requirement.
int[] x = new int[2];
x[0] = Integer.parseInt(b[0]);
x[1] = Integer.parseInt(b[1]);

Integer.parseInt(b[0]);
See the Javadoc for more information.

Related

Split lines with "," and do a trim on every element [duplicate]

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.

How to remove empty elements from arrayList in this code

I experienced a problem with my code where I can not remove empty elements in my arrayList. It ends up returning [1, 2, 3, 0, 8, , 12 , , 34 , 0 ] however those empty elements do not get removed after numerous attempts
public static ArrayList<String> readNumbers() {
Scanner inFile = null;
File file = null;
String filePath = (JOptionPane.showInputDialog("Please enter a file path"));
int size = 0;
ArrayList<String> result = new ArrayList<String>();
try {
file = new File(filePath);
inFile = new Scanner(file);
int skippedCounter = 0;
for(int i = 0; inFile.hasNext(); i++){
if(inFile.hasNextInt())
result.add(inFile.next());
else{
String strOut = "";
String data = inFile.nextLine();
for(int j = 0; j <= data.length() - 1; j++){
if(!Character.isLetter(data.charAt(j))){
strOut += data.charAt(j);
}
else
skippedCounter++;
}
if(!strOut.isEmpty())
result.add(strOut);
}
}
}
catch (FileNotFoundException e) {
System.out.println("File not found");
}
catch(NumberFormatException e){
System.out.println("Not a number");
}
finally {
inFile.close();
}
int count = 0;
result.removeIf(String::isEmpty);
return result;
}
String::isEmpty() only checks if the length of the string is zero. It doesn't return true if your string consists of only spaces or other whitespace.
You can do a String.trim() first and then check for String.isEmpty().
result.removeIf(s -> s.trim().isEmpty());
I believe in Java 8 and up, you can do something like this to remove all empty values from list:
results.removeIf(item -> != StringUtils.isEmpty(item));
You can try:
List<Integer> listWithNulls = Arrays.asList(1,null, 2, 3, null, 4);
List<Integer> listWithoutNulls = listWithNulls.stream().filter(Objects::nonNull).collect(Collectors.toList());

Parsing text file to jagged array

I have the following file
3
2,3,4,5
6,7,8
9,10
and I am trying to convert it to pass it as jagged array of double. By that I mean, I am trying to store this as
double[][] myArray = {{2,3,4},{6,7},{9}}
double[] secondArray = {5,8,10}
I have been able to get the values read from the file but I am stuck on 2 things.
How can I convert the values into double array?
How can I store the last elements into a new array?
I am facing the error because my array contains comma separated values but how can I get the individual values to convert to double? I am still new to Java so I am not aware of all the inbuilt methods.
here is what I have so far
public double[] fileParser(String filename) {
File textFile = new File(filename);
String firstLine = null;
String secondLine = null;
String[] secondLineTokens = null;
FileInputStream fstream = null;
try {
fstream = new FileInputStream(filename);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
try {
firstLine = br.readLine(); // reads the first line
List<String> myList = new ArrayList<String>();
while((secondLine = br.readLine()) != null){
myList.add(secondLine);
//secondLineTokens = secondLine.split(",");
}
String[] linesArray = myList.toArray(new String[myList.size()]);
for(int i = 0; i<linesArray.length; i++){
System.out.println("tokens are: " + linesArray[i]);
}
double[] arrDouble = new double[linesArray.length];
for(int i=0; i<linesArray.length; i++)
{
arrDouble[i] = Double.parseDouble(linesArray[i]); #error here
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It looks like the first line gives you the number of lines in the rest of the file. You can leverage it to make the arrays upfront, like this:
int n = Integer.parseInt(br.readLine());
double a[][] = new double[n][];
double b[] = new double[n];
for (int i = 0 ; i != n ; i++) {
String[] tok = br.readLine().split(",");
a[i] = new double[tok.length-1];
for (int j = 0 ; j != a[i].length ; j++) {
a[i][j] = Double.parseDouble(tok[j]);
}
b[i] = Double.parseDouble(tok[tok.length-1]);
}
Similarly, you can use String.split method to find out how many entries is to be added to the jagged array. This way the code becomes much shorter, because you can pre-allocate all your arrays.
Demo.

Taking an Input from a file

This is the content of my Input file:
0110000000000000000000000000000000000000
I want to take this input to an int[], but BufferReader gives me a char[]. How do I get an int[] from it?
This is my code:
BufferedReader br = new BufferedReader(new FileReader("yes.txt")); // will give a char array not int
int[] input;
input[0] = 0;
input[1] = 1;
input[1] = 1;
// and so on
Solution:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
for (int i = 0; i < s.length; i++) {
int integer = (int) Character.getNumericValue(char_array[i]);
System.out.println(integer);
}
You can use the Character class to convert a char array to an int.

Read int from file separated by comma

I have this code here, that reads numbers from a file and stores them in a String array.
public static void main(String [] args) throws Exception{
BufferedReader br = new BufferedReader(new FileReader("/Users/Tda/desktop/ReadFiles/scores.txt"));
String line = null;
while((line = br.readLine()) != null){
String[] values = line.split(",");
for(String str : values){
System.out.println(str);
}
}
System.out.println("");
br.close();
}
But if I wanted to store the values from the String array in a int array, how should I do?
The file that I'm reading looks something like this.
23,64,73,26
75,34,21,43
After String[] values = line.split(",");...
// new int[] with "values"'s length
int[] intValues = new int[values.length];
// looping over String values
for (int i = 0; i < values.length; i++) {
// trying to parse String value as int
try {
// worked, assigning to respective int[] array position
intValues[i] = Integer.parseInt(values[i]);
}
// didn't work, moving over next String value
// at that position int will have default value 0
catch (NumberFormatException nfe) {
continue;
}
}
... and to test:
System.out.println(Arrays.toString(intValues));
Use parseInt(String) to convert every string to int
http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29
int[] intvalues = new int[values.length];
for (int i = 0; i < values.length; i++) {
intvalues[i] = Integer.parseInt(values[i]);
}
You would need to parse your string into an int:
while((line = br.readLine()) != null){
String[] values = line.split(",");
int[] values2=new int[values.length];
for(int i=0; i<values.length; i++){
try {
values2[i]= Integer.parseInt(values[i]);
//in case it's not an int, you need to try catching a potential exception
}catch (NumberFormatException e) {
continue;
}
}
}

Categories

Resources