I have a class Student and two children classes, CasualStudent and PermanentStudent. I am doing this right now.
Employee[] a = new Employee[10];
int count;
a[0] = new PermanentStudent("John", "LUI", "HJFDDFDFJ");
a[1] = new PermanentStudent("Peter", "VAMPLEW", "VAM12345678");
a[2] = new PermanentStudent("Rudi", "SKACEL", "SKA51515151");
a[3] = new CasualStudent("Katie","BLACKBURN","BLA41925612");
a[4] = new CasualStudent("Neal","STEPHENSON","STE97527467");
a[5] = new CasualStudent("Neneh","CHERRY","CHE98765432");
a[6] = new CasualStudent("Chris","BROOKMYRE","BRO97635198");
a[7] = new CasualStudent("Grace","HOPPER","HOP26554432");
a[8] = new CasualStudent("Randall","MUNROE","XKCD1234567");
a[9] = new CasualStudent("Kaylee","FRYE","FRY90224718");
Each of these children classes have a constructor and I have manually coded the data in the code. Now, I want to read this data from a .txt file. I know how to read and I have done this till now:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Program {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new FileReader(
"file.txt"));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
reader.close();
}
}
But how do I read the data into the classes like this? I am new to Java and I am not able to understand how to do this? Please guide me in the right direction. Thanks!
Also, the text file will always contain 10 lines and each line will have the following format.
John LUI HJFDDFDFJ
..................
Code:
61. int i = 0;
62. for (i = 0; i < 10; i++)
63. {
64. String x = a[i].toString();
65. System.out.println(x);
66. }
The simplest way would be as follows:
Employee[] employees = new Employee[10];
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
for (int i = 0; i < 3; i++) {
String line = reader.readLine();
String[] parts = line.split(" ");
employees[i] = new PermanentStudent(parts[0], parts[1], parts[2])
}
for (int i = 3; i < 10; i++) {
String line = reader.readLine();
String[] parts = line.split(" ");
employees[i] = new CasualStudent(parts[0], parts[1], parts[2])
}
}
Related
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.
I need a program that counts the whitespace in a text document, but it keeps giving me an insane number of whitespaces, as I think the while loop just keeps repeating. could anyone read it over and tell me what is up?
import java.io.*;
public class WhiteSpaceCounter {
public static void main(String[] args) throws IOException {
File file = new File("excerpt.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader inreader = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(inreader);
String sentence;
int countWords = 0, whitespaceCount = 0;
while((sentence = reader.readLine()) != null) {
String[] wordlist = sentence.split("\\s+");
countWords += wordlist.length;
whitespaceCount += countWords -1;
}
System.out.println("The total number of whitespaces in the file is: "
+ whitespaceCount);
}
}
You could also use this
while((sentence = reader.readLine()) != null) {
String[] wordlist = sentence.split("\\s+");
whitespaceCount += wordlist.length-1;
}
If you first line has 3 word and your second line has 10 words, then you logic is
countWords (0) += 3 -> 3
countWords(3) += 10 -> 13
So do not use +=
countWords = wordlist.length;
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've been having some difficulties reading in information from a file into separate arrays. An example of the information in the file is:
14 Barack Obama:United States
17 David Cameron:United Kingdom
27 Vladimir Putin:Russian Federation
19 Angela Merkel:Germany
While I can separate the integers into an array, I am having trouble creating an array for the names and an array for the countries. This is my code thus far:
import java.util.*;
import java.io.*;
public class leadRank {
public static void main(String[] args) throws FileNotFoundException {
int size;
Scanner input = new Scanner(new File("names.txt"));
size = input.nextInt();
int[] rank = new int[size];
for (int i = 0; i < rank.length; i++) {
rank[i] = input.nextInt();
input.nextLine();
}
String[] name = new String[size];
for (int i = 0; i <name.length; i++) {
artist[i] =
I think that I would have to read in the line as a string and use indexOf to find the colon in order to start a new array but I'm unsure as to how to execute that.
I just tried to solve your problem in my ways. It was just for a time pass. Hopes this may helps you.
import java.util.*;
import java.io.*;
public class leadRank {
public static void main(String[] args) throws FileNotFoundException {
int size;
File file = new File("names.txt");
FileReader fr = new FileReader(file);
String s;
LineNumberReader lnr = new LineNumberReader(new FileReader(file));
lnr.skip(Long.MAX_VALUE);
size = lnr.getLineNumber()+1;
lnr.close();
int[] rank = new int[size];
String[] name = new String[size];
String[] country = new String[size];
try {
BufferedReader br = new BufferedReader(fr);
int i=0;
while ((s = br.readLine()) != null) {
String temp = s;
if(temp.contains(":")){
String[] splitres = temp.split(":");
String sub = splitres[0];
rank[i] = Integer.parseInt(sub.substring(0,sub.indexOf(" "))); // Adding rank to array rank[]
name[i] = sub.substring(sub.indexOf(" "), sub.length()-1); // Adding name to array name[]
country[i] = splitres[1]; // Adding the conutries to array country[]
}
i++;
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This is a bit more efficient because it goes through the file only once.
public static void main(String[] args) throws FileNotFoundException {
// create an array list because the size of the array is still not know
ArrayList<Integer> ranks = new ArrayList<Integer>();
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> countries = new ArrayList<String>();
// read the input file
Scanner input = new Scanner(new File("names.txt"));
// read each line
while (input.hasNext()) {
String wholeLine = input.nextLine();
// get the index of the first space
int spaceIndex = wholeLine.indexOf(" ");
// parse the rank
int rank;
try {
rank = Integer.parseInt(wholeLine.substring(0, spaceIndex));
} catch (NumberFormatException e) {
rank = -1;
}
// parse the name & country
String[] tokens = wholeLine.substring(spaceIndex + 1).split(":");
String name = tokens[0];
String country = tokens[1];
// add to the arrays
ranks.add(rank);
names.add(name);
countries.add(country);
}
// get your name and country arrays if needed
String[] nameArr = names.toArray(new String[]{});
String[] countryArr = countries.toArray(new String[]{});
// the rank array has to be created manually
int[] rankArr = new int[ranks.size()];
for (int i = 0; i < ranks.size(); i++) {
rankArr[i] = ranks.get(i).intValue();
}
}
I have a requirement where in I need to read contents of a file, each line needs to be read into an array and split the line and store the values into separate variables for further processing.
Sample data from the file
175 31 4 877108051
62 827 2 879373421
138 100 5 879022956
252 9 5 891456797
59 421 5 888206015
Expected output
arr[1][1] = 175
arr[1][2] = 31
arr[1][3] = 2
arr[1][4] = 879373421
arr[2][1] = 62
arr[2][2] = 827
arr[2][3] = 4
arr[2][4] = 877108051
.
.
.
Im able to split properly using StringTokenizer but unable to access individual elements after tokens are formed. Tried with Array.split(), but its not splitting the values into separate array values. Please help me out. Thanks in advance.
My code
static public void main(String[] args) {
File file = new File("small.txt");
String[] lines = new String[100];
FileReader reader = new FileReader(file);
BufferedReader buffReader = new BufferedReader(reader);
int x = 0;
String s;
while((s = buffReader.readLine()) != null){
lines[x] = s;
// Using StringTokenizer
StringTokenizer st = new StringTokenizer(lines[x]);
while (st.hasMoreTokens()){
System.out.println("Next token:"+st.nextToken());
}
// Using Split()
String[] split1 = lines[x].split(" ");
int size = split1.length;
System.out.println("Split size:"+size);
int i = 0;
for (String value : split1) {
System.out.println("Index:"+i+" "+ value); i++;}
}
You can simplify this code a lot.
Try something like this.
1) Read the file line by line, split lines as you go,
add values to some ArrayList containing String[]
2) Close your file
3) Turn the ArrayList into a String[][]
4) Print the result
Also, note that arrays in Java are indexed starting at 0 not at 1.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
public class Test021 {
static public void main(String[] args) throws Exception {
File file = new File("small.txt");
FileReader reader = new FileReader(file);
BufferedReader buffReader = new BufferedReader(reader);
String s = null;
ArrayList<String[]> lst = new ArrayList<String[]>();
String[][] res = null;
while((s = buffReader.readLine()) != null){
String[] arr = s.split("[\\s]+");
lst.add(arr);
}
buffReader.close();
res = new String[lst.size()][lst.get(0).length];
res = lst.toArray(res);
System.out.println();
// System.out.println(res);
// String result = Arrays.deepToString(res);
// System.out.println(result);
System.out.println();
for (int i=0; i<res.length; i++){
for (int j=0; j<res[i].length; j++){
System.out.println("res[" + (i+1) + "][" + (j+1) + "]=" + res[i][j]);
}
}
System.out.println();
}
}
OUTPUT:
res[1][1]=175
res[1][2]=31
res[1][3]=4
res[1][4]=877108051
res[2][1]=62
res[2][2]=827
res[2][3]=2
res[2][4]=879373421
res[3][1]=138
res[3][2]=100
res[3][3]=5
res[3][4]=879022956
res[4][1]=252
res[4][2]=9
res[4][3]=5
res[4][4]=891456797
res[5][1]=59
res[5][2]=421
res[5][3]=5
res[5][4]=888206015
This might not be the cause, but do not split by space. You may have tabs or LF characters, and/or leading and trailing spaces.
That is, do not use lines[x].split(" ");
split using regex.
lines[x].split("[\\s]+"); //one or more spaces.
Try this code
List<String> lines=new ArrayList<>();
Read file and add line to lines array
File file = new File("data.txt");
FileReader reader = new FileReader(file);
BufferedReader buffReader = new BufferedReader(reader);
String line = buffReader.readLine();
while(line!=null){
lines.add(line);
line = buffReader.readLine();
}
Convert lines array to string 2d array
String string[][]=new String[lines.size()][0];
for(int i=0;i<lines.size();i++){
String s[]=lines.get(i).split(" ");
string[i]=s;
}