BufferedReader inputStream = null;
String fileLine;
int employeeCount = 1;
String[] years = new String[2];
//Employee[] employees = new Employee[employeeCount + 1];
List<Employee> employees = new ArrayList<>();
File myFile = new File("src/project1/data.txt");
//System.out.println("Attempting to read from file in: "+ myFile.getCanonicalPath());
try {
FileInputStream fstream = new FileInputStream(myFile);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] data = strLine.split(" ");
//while ( int i < employees.length ) {
for (int i=1; i < employees.size(); i++ ) {
if (data[1].equals("Executive")) {
employees.add( new Executive(data[0],data[1],data[2], Integer.parseInt(data[3]), Integer.parseInt(data[4])) );
} else if (data[1].equals("Salesman")) {
employees.add( new Salesman(data[0],data[1],data[2], Integer.parseInt(data[3]), Integer.parseInt(data[4])) );
} else {
employees.add( new Employee(data[0],data[1],data[2], Integer.parseInt(data[3])) );
}
//System.out.println(employees[i].toString());
System.out.println(i +" " + employeeCount);
employeeCount++;
}
}
for (int y=1; y < employees.size(); y++ ) {
System.out.println(employees.get(y).getName());
}
//System.out.println(employees.toString());
} catch (IOException io) {
System.out.println("File IO exception" + io.getMessage());
}
EmployeeCount is incrementing as expected, but i is always 1 - what am I missing here? textfile is read in line by line using a while loop - for loop checks if second piece of data matches a string and creates object base on match. Am I making sense here?
The for loop is not incrementing because the condition is false after the first iteration at:
for (int i=1; i < employees.length; i++ ) {
that is, employees.length is 2 since employeeCount was one at this line (I must assume that since the code is incomplete):
Employee[] employees = new Employee[employeeCount + 1];
This line creates an array with two positions since employeeCount + 1 was 2. The size is not automatically adjusted as employeeCount is incremented...
I suggest using a List instead of an array, since the List is expanded as needed:
List<Employee> employees = new ArrayList<>();
...
employees.add(new Employee(...));
Related
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.
I have the following code which counts and displays the number of times each word occurs in the whole text document.
try {
List<String> list = new ArrayList<String>();
int totalWords = 0;
int uniqueWords = 0;
File fr = new File("filename.txt");
Scanner sc = new Scanner(fr);
while (sc.hasNext()) {
String words = sc.next();
String[] space = words.split(" ");
for (int i = 0; i < space.length; i++) {
list.add(space[i]);
}
totalWords++;
}
System.out.println("Words with their frequency..");
Set<String> uniqueSet = new HashSet<String>(list);
for (String word : uniqueSet) {
System.out.println(word + ": " + Collections.frequency(list,word));
}
} catch (Exception e) {
System.out.println("File not found");
}
Is it possible to modify this code to make it so it only counts each occurrence once per line rather than in the entire document?
One can read the contents per line and then apply logic per line to count the words:
File fr = new File("filename.txt");
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
// Read the line in the file
String line = null;
while ((line = br.readLine()) != null) {
//Code to count the occurrences of the words
}
Yes. The Set data structure is very similar to the ArrayList, but with the key difference of having no duplicates.
So, just use a set instead.
In your while loop:
while (sc.hasNext()) {
String words = sc.next();
String[] space = words.split(" ");
//convert space arraylist -> set
Set<String> set = new HashSet<String>(Arrays.asList(space));
for (int i = 0; i < set.length; i++) {
list.add(set[i]);
}
totalWords++;
}
Rest of the code should remain the same.
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)
I am writing a program that should create a file and then generate a unique id , read the file and if any duplicates are present in it generate a new id and repeat the check.
As of now I am able to create the id and write into the file. But my issue is I' m not able to check if any duplicates are present in the file.
Here is the code which I tried:
public class Main {
public static void main(String a[]) throws IOException {
File file = new File("text.txt");
file.createNewFile();
FileWriter filewriter = new FileWriter(file.getAbsoluteFile(), true);
filewriter.write("\r\n");
BufferedWriter bw = new BufferedWriter(filewriter);
String alphanumeric = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Random random = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
// randomInteger = random.nextInt();
sb.append(alphanumeric.charAt(random.nextInt(alphanumeric.length())));
}
System.out.println("\n Random Alphanumeric in Java: " + sb.toString());
// reading data from file
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String string;
while((string = br.readLine()) != null) {
if(string.equals(sb.toString())) {
for (int i = 0; i < 10; i++) {
// randomInteger = random.nextInt();
sb.append(alphanumeric.charAt(random.nextInt(alphanumeric.length())));
}
bw.write((sb.toString()));
System.out.println("new value :" + sb.toString());
}
else{
System.out.println("existing value :" +sb.toString());
}
}
System.out.println(sb.toString());
} catch (FileNotFoundException fnfe) {
System.out.println("File not found!!");
}
}
}
There are several things wrong here
1:
if(string.equals(sb.toString())) {
for (int i = 0; i < 10; i++) {
// randomInteger = random.nextInt();
sb.append(alphanumeric.charAt(random.nextInt(alphanumeric.length())));
}
bw.write((sb.toString()));
System.out.println("new value :" + sb.toString());
}
This adds to the existing id as sb is never reset to empty.
2:
What you are doing now is:
generate id
for each line L do
if L equals id
append to ID
write id
else
some output
end for
What you should be doing:
while not inserted
generate id
for each line L do
if L equals id
found = true
break // exit for each
end for
if found
continue //restart while loop
insert into file // we only get here if it was not found
inserted = true
end while
For better performance first read all the IDs into a list and use it to check for existing ids instead of reading the file every time.
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.