Here is the code I'm using
import java.util.Scanner;
import java.io.*;
import java.util.ArrayList;
public class Message{
Scanner input;
String emailLine = "";
String line;
ArrayList<String> email = new ArrayList<String>();
String emailString;
String sender;
String subject;
String emailMIN;
String[] newString;
StringBuilder emailStringBuilder = new StringBuilder();
public Message(String m)throws IOException{
File inFile = new File ("mail.txt");
input = new Scanner (inFile);
String message;
getEmails();
}
public void getEmails(){
while(input.hasNextLine()){
line = input.nextLine();
System.out.println("Test, line: " + line);
if(line.equals("<END>")){
System.out.println("Test, <END> reached");
System.out.println("Test, email String: " +
emailStringBuilder.toString());
email.add(emailStringBuilder.toString());
}
else{
emailStringBuilder.append("\n" + line);
}
}
}
I'm trying to pass the email ArrayList into a different class so that I can break up the Strings of the ArrayList into separate Arrays. How do I do this? Also once I get it into a different class, how do I access each element of the ArrayList and break each element up into another ArrayList with each element separated by the lines?
Use message.getEmails() to get your emails.
Below is a sample code
public class Message{
Scanner input;
String emailLine = "";
String line;
List<String> emails = new ArrayList<String>();
String emailString;
String sender;
String subject;
String emailMIN;
String[] newString;
StringBuilder emailStringBuilder = new StringBuilder();
public Message(String m)throws IOException{
File inFile = new File ("mail.txt");
input = new Scanner (inFile);
String message;
populateEmails();
}
public void populateEmails(){
while(input.hasNextLine()){
line = input.nextLine();
System.out.println("Test, line: " + line);
if(line.equals("<END>")){
System.out.println("Test, <END> reached");
System.out.println("Test, email String: " +
emailStringBuilder.toString());
emails.add(emailStringBuilder.toString());
}
else{
emailStringBuilder.append("\n" + line);
}
}
}
public List<String> getEmails() {
return emails;
}
}
Well first of all an ArrayList is not a List of arrays. It's simply a List of items, in your case String.
If you want to pass an ArrayList to a different class you could simply do something like this:
public class MyOtherClass {
public void doSomething(ArrayList<String> myList) {
// do something with "myList"
}
And then in your Message class:
MyOtherClass myClass = new MyOtherClass();
myClass.doSomething(email);
Is this helping?
NOTE
From your editing of the question I think you don't fully understand how ArrayList works. It is not a List of Array! It is simply an array implementation of the List interface for better performance in certain tasks. For more information read the javadocs about ArrayList
EDIT
As peeskillet was suggesting, you could also instantiate a Message class object in your new class and get the ArrayList from there, but then email would have to be a public field in your class Message or declare a getter method for email.
EDIT
Since you added more questions:
You can go through all the elements of an ArrayList like this:
For (String nextString : email) {
System.out.println(nextString); // Or do whatever you want with it :)
}
Related
I have a CarModel class that has three fields: name, fuelEconomy, and gasTankSize.
class CarModel {
private String name;
private double fuelEconomy;
private double gasTankSize;
CarModel(String name, double fuelEconomy, double gasTankSize) {
this.name = name;
this.fuelEconomy = fuelEconomy;
this.gasTankSize = gasTankSize;
}
String getName() {
return name;
}
double getFuelEconomy() {
return fuelEconomy;
}
double getGasTankSize() {
return gasTankSize;
}
}
Given the input as a string of text separated by a new line:
MODEL Camry 6.5 58
MODEL Civic 7.5 52
FINISH
How can I create a new object every time the word MODEL is in the input, store the model in an array, use the following words as the data for those fields and end the program when FINISH is in the input?
Inside main method, try doing something like this (Using try with resources):
public static void main(String args[]){
String line;
List<CarModel> cars = new ArrayList<>();
try(Scanner sc = new Scanner(System.in)){
while(sc.hasNextLine()){
line = sc.nextLine();
String[] arr = line.split(" ");
if(arr[0].equalsIgnoreCase("Model")){
cars.add(new CarModel(arr[0], Double.parseDouble(arr[1]), Double.parseDouble(arr[2])));
}else if(arr[0].equalsIgnoreCase("Finish"){
break;
}
}
}catch(ArrayIndexOutOfBoundsException ex){
// do something here!
}catch(Exception ex){
// do something here as well!
}
}
I would use the String.split method. You pass a delimiter, in your case a space character, and then the method chops the string into pieces based on your provided delimeter. Getting the input into your program depends on where the input will be coming from, whether by file or terminal or some other source.
Once you've read a line of input, call String[] values = line.split(" ")
Again, how to read the input depends on where the input is coming from, which you haven't specified.
I dont understand why i am not able to read from the file.I am always getting null with Readline() method of BufferedReader .
TestStudent class should be able to perform the following functions:
Create an ArrayList object of Student objects called studentList, using the student data stored in a text file named students.txt (you should create this file such that it stores the student name and ID of several students initially – one line per student)
Allow the user to add as many new Student objects as the user requests to the ArrayList ensuring that each student has a unique student ID
When the user has finished adding new students to the list, the program will override the students.txt file such that it includes the data relating to the new students as well as the original ones
Ability to display a full list of students as well as just the existing student IDs when necessary
Here's what i have done till now.
import java.util.*;
import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class TestStudent {
public static void main(String[] args) throws IOException {
File f=new File("C:\\Users\\user1\\Desktop\\Students.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(f);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
//File f=new File("Student.txt");
Scanner sc=new Scanner(System.in);
Scanner scan = new Scanner(f);
ArrayList<Student> studentList = new ArrayList<>();
String cont;
do {
System.out.println("Enter Student Name:");
String name=sc.next();
System.out.println("Enter Student ID:");
String id=sc.next();
bw.write(name);
bw.write("\t"+id);
bw.newLine();
System.out.println("Continue Adding?");
cont=sc.next();
}
while(cont.equalsIgnoreCase("y"));
while(bufferedReader.readLine() != null){
String line = bufferedReader.readLine();
String[] record = line.split("\t");
Student myStudent =new Student(record[0],record[1]);
studentList.add(myStudent);
}
for(Student st:studentList)
System.out.println(st.Name+" "+st.Id);
bw.close();
scan.close();
sc.close();
}
}
class Student{
String Name, Id;
with default value red
Student(String string, String string0) {
System.out.println("s");
}
//Following are Mutators methos
public String getName() {
return this.Name;
}
public String getId() {
return this.Id;
}
//Following are accessor Methods
public void setName(String s){
this.Name=s;
}
public void setID(String ID) {
this.Id = ID;
}
public String toString() {
return "Student name is "+getName()+" Student Id is "+getId();
}
public boolean isValidID() {
if(getId().length()!=6)
return false;
else{
for(int i=0;i<getId().length();i++){
if(Id.charAt(i)>'9'||Id.charAt(i)<'0')
return false;
}
return true;
}
}
public boolean IDExists(Student other) {
if(other.getId().equals(this.getId()))
return true;
else
return false;
}
}
The problem is here:
while(bufferedReader.readLine() != null){
String line = bufferedReader.readLine();
...
}
The first call to readLine() reads the line, but does not assign it - its lost. The next call to readLine() reads the next line.
It should be:
String line = null;
while ((line = bufferedReader.readLine()) != null){
....
}
This reads the next line, assign it to line, and then compares to null.
Then, your student constructor is broken:
Student(String string, String string0) {
System.out.println("s");
}
You never assign string and string0 to anything, and Id and Name are not assigned and always null.
Your code furthermore does not compile:
String Name, Id;
with default value red
This is a syntax error.
Read about How to create a Minimal, Complete, and Verifiable example to ensure your code is working and your question focused on one problem at a time. Most of your problems would be gone simply by making sure you test every part of your program separately and make sure it actually compiles.
you forgot to assign studentID and studentName for new Object in constructor
Student(String string, String string0) {
System.out.println("s");
id = string;
name = string0;
}
and because you write and read the same file so you must close fileWriter before reading
do {
// your code
}
while(cont.equalsIgnoreCase("y"));
// close buffer writer before reading
bw.close()
String line;
while((line = bufferedReader.readLine()) != null){
String[] record = line.split("\t");
Student myStudent =new Student(record[0],record[1]);
studentList.add(myStudent);
}
So i got a Java Class of Konto, which got:
private String navn;
private int medlemdsnummer;
private String årstal;
private String måned;
private String dag;
LocalDate localDate;
They are used like this:
ArrayList<Konto> kontoArrayList = new ArrayList<>();
And I save my ArrayList to a .txt document before the program shutdowns:
private static void saveToFile(ArrayList<Konto> kontoArrayList) throws IOException {
String content = new String(Files.readAllBytes(Paths.get("medlemmer.txt")));
PrintStream printStream = new PrintStream("medlemmer.txt");
for (int i = 0; i < kontoArrayList.size(); i++) {
printStream.println(content + kontoArrayList.get(i).getMedlemdsnummer() + ": " + kontoArrayList.get(i).getNavn() + " " +
kontoArrayList.get(i).getLocalDate());
}
}
They end up looking like this in the .txt file:
1: Kasper 1996-11-20
2: Jonas 1996-04-27
3: Jesper 1996-05-14
Okay, so far so good. Now for the question: When the program is turned on, I want to make it able to load the .txt file from the beginning and "transfer" it to an ArrayList of Konto. So that i later can use my method (addNewMember). I saw a lot of example on the internet, but they all use:
ArrayList<String> somename = new ArrayList<String>();
I want to use:
ArrayList<Konto> konto = new ArrayList<Konto>();
Is this possible, if so how do to?
If not what could i do instead?
Thanks in advance, Victor.
You can read all lines from the file as string and split this strings by spaces.
And then create new objects with parsing of options.
Something like this:
List<String> strings = Files.readAllLines(Paths.get("test.txt"));
List<Konto> kontos = new ArrayList<>();
for (String string : strings) {
String[] data = string.split(" ");
kontos.add(new Konto(data[1], new Date(data[2])));
}
Or using Streams:
List<Konto> kontos = Files.lines(Paths.get("test.txt")) // String
.map(line -> line.split(" ")) // String[]
.map(data -> new Konto(data[1], new Date(data[2])) // Konto
.collect(Collectors.toList());
Something like the following, you've got to check it
class TestParse {
public TestParse(String line) {
StringTokenizer tokenizer = new StringTokenizer(line, ",");
if(tokenizer.countTokens() != 3) {
throw new RuntimeException("error");
}
s1 = tokenizer.nextToken();
s2 = tokenizer.nextToken();
s3 = tokenizer.nextToken();
}
private String s1;
private String s2;
private String s3;
}
public class TestRead {
public static void main(String[] args) throws Exception {
List<TestParse> testParses = new ArrayList<TestParse>();
BufferedReader in = new BufferedReader(new FileReader("file.txt"));
String line;
while((line = in.readLine()) != null) {
testParses.add(new TestParse(line));
}
in.close();
}
}
I think one way you can try is read line by line, and define a Konto constructor that accept a string.
Edit: You can follow the below answer from Lucem. But I think I will do it a little different
List<String> strings = Files.readAllLines(Paths.get("fileName.txt"));
List<Konto> kontos = new ArrayList<>();
for (String s: strings) {
kontos.add (new Konto(s))
}
or using Streams:
List<Konto> kontos = Files.lines(Paths.get("fileName.txt"))
.map(line -> new Konto(line));
.collect(Collectors.toList());
And then in Konto class add a constructor that accept a string and manipulate it. Because you didn't add the class Konto here, I didn't know the exact name of your properties, so I let it be "yourPropertyNumber", "yourPropertyString" and "yourPropertyDate"
class Konto {
public Konto (String input) {
// Split based on white space
String[] dataParts = input.split(" ");
// Get rid of the semicolon
String number = dataParts[0].substring(0, dataParts[0].length - 1);
yourPropertyNumber = parseInt(number);
yourPropertyString = dataParts[1];
yourPropertyDate = new Date(dataParts[2]);
}
// Your other code here
}
The reason I want to pass a String to a constructor rather than parse the string where I read the file is that I think it is easier to debug or make change in the way it reads the string.
Hope this help.
I have the following text file (answers.txt):
Problem A: 23|47|32|20
Problem B: 40|50|30|45
Problem C: 5|8|11|14
Problem D: 20|23|25|30
What I need is something that will read the problem that I tell it(Problem A, Problem B), then read the numbers after it, which are separated by the lines, and print it out like this:
Answers for Problem A: a.23 b.47 c.32 d.20
Does anyone know how this can be done? I've been stuck on it for a while.
Read the lines one by one, split the lines at " " first. The you will get an array with three parts "Problem", "A:" and "23|47|32|20". Then split the third part at "|" so you will get a second array with four parts "23,"47","32","20".
Combine all to get the output you want.
If you want info on how to read lines from a file, or spilt strings then there are billions of tutorials online on how to do that so I wont go into detail on how its done. IM sure you can find them.
Check out this code!
It assumes that you have such file format:
Problem A:
23|7|32|20
Problem B:
40|50|30|45
Problem C:
5|8|11|14
Problem D:
20|23|25|30
because you wrote "numbers after it, which are separated by the lines"
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(new File("answers.txt"));
List<String> dataList = new ArrayList<String>();
while(sc.hasNextLine()){
dataList.add(sc.nextLine());
}
System.out.println(dataList);
Map<String,String> map = new HashMap<String,String>();
for(int i=0;i<dataList.size();i=i+2){
map.put(dataList.get(i),dataList.get(i+1));
}
for(Entry<String,String> en:map.entrySet()){
System.out.println(en.getKey()+" : "+en.getValue());
}
String problemC = map.get("Problem C:");
String splitted[] = problemC.split("\\|");
System.out.println("Get me problem C: "+String.format("a:%s, b:%s, c:%s, d:%s",splitted[0],splitted[1],splitted[2],splitted[3]));
}
}
Hope this helps!
public static void main(String args[])
{
BufferedReader br = new BufferedReader(new FileReader(new File("answers.txt")));
String lineRead = null;
String problem = "Problem A";//Get this from user Input
List<String> numberData = new ArrayList<String>();
while((lineRead = br.readLine())!=null)
{
if(lineRead.contains(problem))
{
StringTokenizer st = new StringTokenizer(lineRead,":");
String problemPart = st.nextToken();
String numbersPart = st.nextToken();
st = new StringTokenizer(lineRead,"|");
while(st.hasMoreTokens())
{
String number = st.nextToken();
System.out.println("Number is: " + number);
numberData.add(number);
}
break;
}
}
System.out.println("Answers for " + problem + " : " + numberData );
}
Read the lines one by one, split the lines with :. The you will get an array with two parts "Problem A:" and "23|47|32|20". Then split the second part at "|" so you will get a second array with four parts "23,"47","32","20".
Combining all this you will get the output you want.
Cheers!
Use java.util.Scanner and you can filter the integers in the file.
Scanner s = new Scanner (new File ("answers.txt")).useDelimiter("\\s+");
while (s.hasNext()) {
if (s.hasNextInt()) { // check if next token is integer
System.out.print(s.nextInt());
} else {
s.next(); // else read the next token
}
}
Do you know how to read line by line ? If not , chect it How to read a large text file line by line in java?
To sub your string data there have many ways to do. You can sub as you wish. Here for my code..
String data = yourReader.readLine();
String problem = data.substring("Problem".length(), data.indexOf(":"));
System.err.println("Problem is " + problem);
data = data.substring(data.indexOf(":") + 2, data.length());
String[] temp = data.split("\\|");
for (String result : temp) {
System.out.println(result);
}
Assuming there are always four possible answers as in your Example:
// read complete file in fileAsString
String regex = "^(Problem \\w+): (\\d+)\\|(\\d+)\\|(\\d+)\\|(\\d+)$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(fileAsString);
//and so on, read all the Problems using matcher.find() and matcher.group(int) to get the parts
// put in a Map maybe?
// output the one you want...
I might suggest creating a simple data type for the purpose of organization:
public class ProblemAnswer {
private final String problem;
private final String[] answers;
public ProblemAnswer(String problem, String[] answers) {
this.problem = problem;
this.answers = new String[answers.length];
for (int i = 0; i < answers.length; i++) {
this.answers[i] = answers[i];
}
}
public String getProblem() {
return this.problem;
}
public String[] getAnswers() {
return this.answers;
}
public String getA() {
return this.answers[0];
}
public String getB() {
return this.answers[1];
}
public String getC() {
return this.answers[2];
}
public String getD() {
return this.answers[3];
}
}
Then the reading from the text file would look something like this:
public void read() {
Scanner s = new Scanner("answers.txt");
ArrayList<String> lines = new ArrayList<String>();
while (s.hasNext()) {
lines.add(s.nextLine());//first separate by line
}
ProblemAnswer[] answerKey = new ProblemAnswer[lines.size()];
for (int i = 0; i < lines.size(); i++) {
String[] divide = lines.get(i).split(": "); //0 is the problem name, 1 is the list
//of answers
String[] answers = divide[1].split("|"); //an array of the answers to a given
//question
answerKey[i] = new ProblemAnswer(divide[0], answers); //add a new ProblemAnswer
//object to the key
}
}
Now that leaves you with an answer key with ProblemAnswer objects which is easily checked
with a simple .equals() comparison on the getProblem() method, and whatever index is matched, you have all the answers neatly arranged right within that same object.
I'm trying to read data from a .txt file. The format looks like this:
ABC, John, 123
DEF, Mark, 456
GHI, Mary, 789
I am trying to get rid of the commas and put the data into an array or structure (structure most likely).
This is the code I used to to extract each item:
package prerequisiteChecker;
import java.util.*;
import java.io.*;
public class TestUnit {
public static void main(String[]args){
try {
FileInputStream fstream = new FileInputStream("courses.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
String[] splitOut = strLine.split(", ");
for (String token : splitOut)
System.out.println(token);
}
in.close();
} catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
At one point I had a print line in the "while" loop to see if the items would be split. They were. Now I'm just at a loss on what to do next. I'm trying to place each grouping into one structure. For example: ID - ABC. First Name - John. Room - 123.
I have a few books on Java at home and tried looking around the web. There is so much out there, and none of it seemed to lead me in the right direction.
Thanks.
Michael
create a class that looks something like this:
class structure {
public String data1;
public String data2;
public String data3;
}
This will form your basic data structure that you can use to hold the kind of data you have mentioned in your question. Now, you might want to follow proper object oriented methods like declaring all your fields as private, and writting getters and setters. you can find more on there here ... http://java.dzone.com/articles/getter-setter-use-or-not-use-0
Now, just outside your while loop, create an ArrayList like this: ArrayList<structure> list = new ArrayList<structure>(); This will be used to hold all the different rows of data that you will parse.
Now, in your while loop do something like this:
structure item = new structure();//create a new instance for each row in the text file.
item.data1 = splitOut[0];
item.data2 = splitOut[1];
item.data3 = splitOut[2];
list.add(item);
this will basically take the data that you parse in each row, put in the data structure that you declared by creating a new instance of it for each new row that is parsed. this finally followed by inserting that data item in the ArrayList using the list.add(item) in the code as shown above.
I would create a nice structure to store your information. I'm not sure if how you want to access the data, but here's a nice example. I'll go off of what you previously put. Please note that I only made the variables public because they're final. They cannot change once you make the Course. If you want the course mutable, create getters and setters and change the instance variables to private. After, you can use the list to retrieve any course you'd like.
package prerequisiteChecker;
import java.util.*;
import java.io.*;
public class TestUnit {
public static void main(String[] args) {
try {
FileInputStream fstream = new FileInputStream("courses.txt");
// use DataInputStream to read binary NOT text
// DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
List<Course> courses = new LinkedList<Course>();
while ((strLine = br.readLine()) != null) {
String[] splitOut = strLine.split(", ");
if (splitOut.length == 3) {
courses.add(new Course(splitOut[0], splitOut[1],
splitOut[2]));
} else {
System.out.println("Invalid class: " + strLine);
}
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
public static class Course {
public final String _id;
public final String _name;
public final String _room;
public Course(String id, String name, String room) {
_id = id;
_name = name;
_room = room;
}
}
}
public class File_ReaderWriter {
private static class Structure{
public String data;
}
public static void main(String[] args) throws IOException{
String allDataString;
FileInputStream fileReader = new FileInputStream ("read_data_file.txt");
DataInputStream in = new DataInputStream(fileReader);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(in));
String[] arrayString = {"ID - ", " NAME - ", " ROOM - "};
int recordNumber = 0;
Structure[] structure = new Structure[10];
for (int i = 0; i < 10; i++)
structure[i] = new Structure();
while((allDataString = bufferReader.readLine()) != null){
String[] splitOut = allDataString.split(", ");
structure[recordNumber].data = "";
for (int i = 0; i < arrayString.length; i++){
structure[recordNumber].data += arrayString[i] + splitOut[i];
}
recordNumber++;
}
bufferReader.close();
for (int i = 0; i < recordNumber; i++){
System.out.println(structure[i].data);
}
}
}
I modify your given code. It works. Try it and if any query then ask.