Taking an Input from a file - java

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.

Related

BufferedReader saving sentence, String array, then 2D int array

I have a .txt file that contains text that I would like to save part of it in a String, part of it in a String array, and then the last part in a 2D int array, and am faced with two issues:
How to read and save both of the arrays when their size is not known ahead of time?
2D array is not reading/saving properly
Here is the text file for reference:
This is the sentence to be read.
This
is
a
String
array.
90 47 110 95 95
101 87
54 0 38 12
Here is part of my method that is supposed to read and save the three data types:
BufferedReader br = new BufferedReader(new FileReader(fileName));
sentence = br.readLine();
stringArr = new String[5]; //how to initialize without set number of elements?
for(int i = 0; i<stringArr.length; i++){
stringArr[i] = br.readLine();
}
int2DArr = new int[3][5]; //how to initialize with any amount of rows and columns?
for(int i = 0; i<int2DArr.length; i++){
for(int j = 0; j<int2DArr[i].length; j++){
int2DArr[i][j] = br.read();
//how to read the space after each int ?
}
}
How would I "grab" the size of the arrays by reading the text file, so that when I initialize both arrays, I have the proper sizes? Any help would be greatly appreciated!
Instead of trying to achieve everything in a single pass we can pass through the file twice and obtain a neater code.
It will consume double time of course but it is going to help you understand how you could break bigger problems into smaller ones and deal with them one by one.
Here are the steps:
Determine size of stringArr and intArr in first pass
Fill value in respective array in second pass
If you are wondering how no of columns for int2DArr is determine. Simply we don't do it our self. We use the concept of Jagged Arrays
Read more here How do I create a jagged 2d array in Java?
import java.util.*;
import java.io.*;
class ReadFileIntoArr {
public static void main(String args[]) throws IOException {
String fileName = "test.txt";
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
int strSize = 0;
int intSize = 0;
boolean isDigit = false;
while (line != null && line.trim().length() != 0) {
if (!isDigit && Character.isDigit(line.charAt(0)))
isDigit = true;
if (isDigit)
intSize++;
else
strSize++;
line = br.readLine();
}
br = new BufferedReader(new FileReader(fileName));
String[] stringArr = new String[strSize];
for (int i = 0; i < stringArr.length; i++)
stringArr[i] = br.readLine();
int[][] int2DArr = new int[intSize][];
for (int i = 0; i < int2DArr.length; i++)
int2DArr[i] = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(stringArr));
System.out.println(Arrays.deepToString(int2DArr));
}
}
Note: In single pass this could be accomplished with the help of ArrayList and later transfer everything into respective array.
Update: After understanding the constraints for your problem here is another version
import java.util.*;
import java.io.*;
class ReadFileIntoArr {
public static void main(String args[]) throws IOException {
String fileName = "test.txt";
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
int strSize = 0;
int intSize = 0;
boolean isDigit = false;
while (line != null && line.trim().length() != 0) {
if (!isDigit && isDigit(line.charAt(0)))
isDigit = true;
if (isDigit)
intSize++;
else
strSize++;
line = br.readLine();
}
br = new BufferedReader(new FileReader(fileName));
String[] stringArr = new String[strSize];
for (int i = 0; i < stringArr.length; i++)
stringArr[i] = br.readLine();
int[][] int2DArr = new int[intSize][];
for (int i = 0; i < int2DArr.length; i++)
int2DArr[i] = convertStringArrToIntArr(br.readLine().split(" "));
System.out.println(Arrays.toString(stringArr));
System.out.println(Arrays.deepToString(int2DArr));
}
public static boolean isDigit(char c) {
return c >= '0' && c <= '9';
}
public static int[] convertStringArrToIntArr(String[] strArr) {
int[] intArr = new int[strArr.length];
for (int i = 0; i < strArr.length; i++)
intArr[i] = Integer.parseInt(strArr[i]);
return intArr;
}
}
Path path = Paths.get(fileName);
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
String title = lines.get(0);
List<String> words = new ArrayList<>();
for (int i = 1; i < lines.size(); ++i) {
String word = lines.get(i);
if (!word.isEmpty() && Character.isDigit(word.codePointAt(0)) {
break;
}
words.add(word);
}
String[] wordArray = words.toArray(new String[]);
int i0 = 1 + words.size();
int n = lines.size() - i0;
int[][] numbers = new int[n][];
for (int i = i0; i < lines.size(); ++i) {
String[] values = lines.get(i).trim().split("\\s+");
int m = values.length;
int[] row = new int[m];
for (int j = 0; j < m; ++m) {
row[j] = Integer.parse(values[j]);
}
numbers[i - i0] = row;
}
Path is a generalisation of File, also URLs.
Files is a treasure trove of file functions.
One could do without dynamically sized List; one would need to test first,
but normally one would use a List anyhow.
String.split splits on one or more whitespace.

Reading text file and inputting into double array

Hi for my HW I am suppose to read a text file of '.' and 'x' representing cells in Conway's Game of Life. I'm having trouble with reading the given text input and adding it into my double integer arrays. Specifically the rowcounter and columncounter part I'm sure there is a better way to do it but when I tried for loops it only read one row. I included previous parts of the code just in case. Thanks.
// Initiate file
File inputfile = new File(inputfilename);
try {
input = new Scanner(inputfile);
} catch (Exception ie) {
}
// Get array size
int[] arraysize = new int[2];
while (input.hasNextInt()) {
for (int i = 0; i < 2; i++) {
int token = input.nextInt();
arraysize[i] = token;
}
}
//System.out.println(Arrays.toString(arraysize));
// Create Array
int[][] newarray = new int[arraysize[0]][arraysize[1]];
//System.out.println(Arrays.deepToString(newarray));
// Read initial
int rowcounter = 0;
int columncounter = 0;
while (input.hasNextLine()) {
Scanner inputtoken = new Scanner(input.nextLine());
while (inputtoken.hasNext()) {
String token = inputtoken.next();
//System.out.print(token);
char xchar = token.charAt(0);
if (xchar == 'x') {
newarray[rowcounter][columncounter] = 1;
} else {
newarray[rowcounter][columncounter] = 0;
//System.out.print(rowcounter);
}
columncounter = columncounter + 1;
//System.out.print(columncounter);
}
columncounter = 0;
System.out.println();
rowcounter = rowcounter + 1;
//System.out.print(rowcounter);
}
System.out.println(Arrays.deepToString(newarray));

Replacing a particular number - For Loop

I have the following code:
List<String> l1_0 = new ArrayList<String>(), l2_0 = new ArrayList<String>(),.....;
List<Integer> l1_1 = new ArrayList<Integer>(), l2_1 = new ArrayList<Integer>()......;
int lines1 = 0, lines2 = 0, lines3 = 0 .....;
Scanner s1 = new Scanner(new FileReader("file/path//t1.txt"));
while (s1.hasNext()) {
l1_0.add(s1.next());
l1_1.add(s1.nextInt());
lines1++;
}
s1.close();
func1(l1_0,l1_1,lines);
I have to perform same operation for 40 files.
Can we create a for loop to achieve it?
I am thinking of something along the lines of.
for (int i=1; i<= 40 ; i++)
{
Scanner s[i] = new Scanner(new FileReader("file/path//t[i].txt"));
while (s[i].hasNext()) {
l[i]_0.add(s[i].next());
l[i]_1.add(s[i].nextInt());
lines[i]++;
}
s[i].close();
func1(l[i]_0,l[i]_1,lines[i]);
}
If I understood correctly, you want to loop over your data 40 times. Once for each file.
for (int i=0; i< 40 ; i++)
{
// Initializers for this one file
List<String> strings = new ArrayList<>();
List<Integer> nums = new ArrayList<>();
int lineCount = 0;
String filename = "t" + i;
try (Scanner s = new Scanner(new FileReader("file/path/" + filename + ".txt"))) {
while (s.hasNext()) {
strings.add(s.next());
if (s.hasNextInt()) {
nums.add(s.nextInt());
}
lineCount++;
}
}
func1(strings,nums,lineCount);
}
for (int i=1; i<= 40 ; i++){
Scanner s[i] = new Scanner(new FileReader("file/path//t[i].txt"));
}
In java there is no implicit String pattern resolution. That means you have to create yourself, the String representing new file names like this:
"file/path//t" + i + ".txt"
Or you may use String.format():
String.format("file/path//t%d.txt",i)

How to get int array from string array

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.

Dynamic array of Integer type in processing

How can I create a Dynamic array that holds Integer values (not int) in PROCESSING.
I have stored the String into a text file (String Str= "12,13,14,15"). Now i need to split and convert them to Integer type after loading the text file.
Since code is reading a file, I would use a Scanner instead:
String str = "2,3,4,5,6,7";
List<Integer> intList = new ArrayList<Integer>();
Scanner sc = new Scanner(new File(/*yourFile*/));
//Scanner sc = new Scanner(str);
while(sc.hasNext()) {
sc.useDelimiter(",");
intList.add(sc.nextInt());
}
Integer[] wrapperArray = new Integer[intList.size()];
intList.toArray(wrapperArray);
Scanner: How-to
You can try this code.. It works fine for me
try {
FileReader fr = new FileReader("data.txt");
BufferedReader br = new BufferedReader(fr);
String str = br.readLine();
String strArray[] = str.split(",");
Integer intArray[] = new Integer[strArray.length];
for (int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
System.out.println(intArray[i]);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
I hope this will help you.
String str = "12,13,14,15";
String[] strArray = str.split(",");
int[] intArray = new int[strArray.length];
for (int i = 0; i < strArray.length; i++) {
try {
intArray[i] = Integer.parseInt(strArray[i]);
} catch (NumberFormatException e) {
// Handle the exception properly as noted by Jon
e.printStackTrace();
}
}

Categories

Resources