Android Eclipse: for each line of EditText - java

I want to know how I can get the count of lines of an EditText and then set a line to a string.
Something like that:
String current_line;
for (int i = 0; i < EditText1.LinesLength; ++i) {
current_line = EditText1.Lines(i);
}
I can't make this work..

you can get the edittext lines like this..
Try using String.split(). Code example:
String multiLines = streetEt.getText().toString();
String[] streets;
String delimiter = "\n";
streets = multiLines.split(delimiter);
Now you have an array of streets.
Let's say, for example, your EditText reads "1st St.\nHighway Rd.\nUniversity Ave." (or is those 3 streets separated by line breaks, instead of you actually seeing \n). Following the code example I provided you,
multiLines becomes "1st St.\nHighway Rd.\nUniversity Ave."
`streets = multiLines.split(delimiter);` fills the array streets with the street names, i.e.
streets[0] = "1st St."
streets[1] = "Highway Rd."
streets[2] = "University Ave."

Related

Java: Find word in string and edit words after the word

For example I have a String like this:
String myString = "Money = 10
Arrows = 4"
I want to edit the arrows, so I have to find the word "Arrow" in the String and edit the number "4". Any idea how to do that?
Thanks!
If you want to edit a value easily based on something else in the program, you can make it so the number is a variable instead. Judging by the code as well, you want there to be a new line, currently it's not doing that since you need to use "\n"
So the code should look like:
int arrows = 4;
String myString = "Money = 10" + "\n" + "Arrows = " + arrows;
If you then change the value of the integer arrows before declaring the string it will be different.
I don't use java that much but if you need to find out is something is a letter you can use
System.out.println(Character.isLetter('c'));
System.out.println(Character.isLetter('5'));
And since your data is in a string you can loop trough it like trough an array, as far as I remember.
for(int i =0; i < yourStringName.length; i++)
But I must agree with #jack jay.
So here is a helpful post Java associative-array

Splitting and saving data in Java

I'm trying to read a data file and save the different variables into an array list.
The format of the data file looks a little like this like this
5003639MATH131410591
5003639CHEM434111644
5003639PSYC230110701
Working around the bad formatting of the data file, I added commas to the different sections to make a split work. The new text file created looks something like this
5,003639,MATH,1314,10591
5,003639,CHEM,4341,11644
5,003639,PSYC,2301,10701
After creating said file, I tried to save the information into an array list.
The following is the snippet of trying to do this.
FileReader reader3 = new FileReader("example.txt");
BufferedReader br3 = new BufferedReader(reader3);
while ((strLine = br3.readLine())!=null){
String[] splitOut = strLine.split(", ");
if (splitOut.length == 5)
list.add(new Class(splitOut[0], splitOut[1], splitOut[2], splitOut[3], splitOut[4]));
}
br3.close();
System.out.println(list.get(0));
The following is the structure it is trying to save into
public static class Class{
public final String recordCode;
public final String institutionCode;
public final String subject;
public final String courseNum;
public final String sectionNum;
public Class(String rc, String ic, String sub, String cn, String sn){
recordCode = rc;
institutionCode = ic;
subject = sub;
courseNum = cn;
sectionNum = sn;
}
}
At the end I wanted to print out one of the variables to see that it's working but it gives me an IndexOutOfBoundsException. I wanted to know if I'm maybe saving the info incorrectly, or am I perhaps trying to get it to print out incorrectly?
You have a space in your split delimiter specification, but no spaces in your data.
String[] splitOut = strLine.split(", "); // <-- notice the space?
This will result in a splitOut array of only length 1, not 5 like you expect.
Since you only add to the list when you see a length of 5, checking the list for the 0th element at the end will result in checking for the first element of an empty list, hence your exception.
If you expect your data to have a comma or a space separating the characters then you would alter the split line to be:
String[] splitOut = strLine.split("[, ]");
The split takes a regular expression as an argument.
Rather than artificially adding commas I would look at String.substring in order to cut the line you have read into pieces. For example:
while ((strLine = br3.readLine())!=null) {
if (strLine.length() != 20)
throw new BadLineException("line length is not valid");
list.add(new Class(strLine.substring(0,1), strLine.substring(1,7), strLine.substring(7,11), strLine.substring(11,15), strLine.substring(15,19)));
}
[ Untested: my numbers might be out because I a bit knacked, but you get the idea ]

Java Array Index Out of Bound

I have the following code that reads through a line of students and the program should split at each white space then go to the next part of the text but I get arrayindexoutofBound exception.
The text file has several lines like this:
130002 Bob B2123 35 34 B2132 34 54 B2143 23 34
public static void main(String[] args) throws FileNotFoundException {
File f = new File("C:\\Users\\Softey\\Documents\\scores.txt");
Scanner sc = new Scanner(f);
List<MarkProcessing> people = new ArrayList<MarkProcessing>();
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] details = line.split("\\s+");
String regNumber = details[0];
String name = details[1];
String modOne= details[2];
int courseM = Integer.parseInt(details[3]);
int examM = Integer.parseInt(details[4]);
String modTwo = details[5];
int courseM2 = Integer.parseInt(details[6]);
int examM2 = Integer.parseInt(details[7]);
String modThree = details[8];
int courseM3 = Integer.parseInt(details[9]);
int examM3= Integer.parseInt(details[10]);
MarkProcessing p = new MarkProcessing(regNumber, name, modOne,courseM, examM, modTwo,courseM2,examM2, modThree, courseM3, examM3);
people.add(p);
}
}
}
When it goes to details[1] I get the index error.
Without information regarding the input file, I am going to guess this is because of blank lines in your file. If this is the case, you should try something to ensure that you have enough pieces.. For this, your while loop could be something like this.
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] details = line.split("\\s+");
if(details.length < 11) continue; // skip this iteration
...
}
Keep in mind this is only going to work if you are checking at least 11 items per line. If you need a more advanced method of parsing the input, whereas they may have any number of courses. You are better off thinking of another approach than simply storing values directly from indices.
You should try printing the line before parsing it so that you can see what causes it to blow up.
String line = sc.nextLine();
String[] details = line.split("\\s+");
String regNumber = details[0];
String name = details[1];
String modOne= details[2];
You are splitting on chunks of spaces. In the event you encounter a line with no spaces, then there will only be a single element and therefore details[1] will throw an IndexOutOfBoundsException.
My suggestion is to examine your input carefully. Does it have at trailing line feed? If so, that may be interpreted as a blank line
130002 Bob B2123 35 34 B2132 34 54 B2143 23 34
<blank line>
To split by space, you need to use:
String[] details = line.split(" "); // "\\s+" -> does not split by space.
In your case, it is trying to split the line by the regex pattern '//s+' and since this is not found, it considers the whole line to be one string. In this case, the size of the string array is 1. There is no details[1] and hence you get this error.

Splitting a line and filling an array skipping blank values in Java

I have an array of line, which is somewhat like below
Here's example:
A-NUMBER ROUTINF ACO AO L MISCELL
0-0 0 1-20
0-00
0-01 FDS 3-20
0-02 6 7 3-20
0-03 4 3-20
1-0 F=PRE
ANT=3
NAPI=1
1-1 F=PRE
ANT=3
I need to parse the line according to column by skipping the column which has blank values and create a new line like below
ANUM = 0-0, ACO=0, L=1-20;
ANUM = 0-00;
ANUM = 0-01, ROUTINF=FDS, L=3-20;
ANUM = 0-02, ACO=6, AO=7, L=3-20;
ANUM = 0-03, AO=4,L=3-20;
ANUM = 1-0, F=PRE, ANT=3, NAPI=1;
ANUM = 1-1, F=PRE, ANT=3;
I can split the line but my code can't remember which column the value belongs to and when to skip the values.
String[] splitted = null;
for (Integer i = 0; i < lines.size(); i++) {
splitted = lines.get(i).split("\\s+");
for(String str : splitted)
if(!(splitted.length == 1)){
anum = splitted[0];
routinf = splitted[1];
aco = splitted[2];
ao = splitted[3];
l = splitted[4];
}else {
miscell = splitted[0];
}
}
The columns in your file seems to be of fixed length (I don't see any other way to distinguish each column). If that is the case then I would recommend using substring(srat, end) instead of split.
Create a class to hold one single record.
class Record {
String aNumber,
List<String> routingf, aco, ao, l, miscell;
public Record(String aNumber) {
this.aNumber = aNumber;
this.routingf = new ArrayList<>();
// init other lists like above ...
}
public void addRoutingf(String routingf) {
// add only of not null and is not empty trimmed
if(routingf != null && routiingf.trim().length() > 0) {
this.routingf.add(routiingf);
}
}
// implement add-methods for other lists like above ...
}
While parsing each line remember the last created record. If in the actual line A-NUMBER is empty then use the last created record to store the values, otherwise create a new record and remember it as last/actual so you can use it for the upcoming lines if necessary.
Save all record in a list
List<Record> records = new ArrayList<>();
What is the common separator? Just split on that... Your + at the moment will consume any amount of white space. \s{1,4} wil limit it to between 1 and 4 characters. Find the right numbers for your data.
if your input time use one space char (for instance tab) between columns your code is almost OK
String[] splitted = null;
for (Integer i = 0; i < lines.size(); i++) {
splitted = lines.get(i).split("\\s");
if(!(splitted.length == 1)){
anum = splitted[0];
routinf = splitted[1];
aco = splitted[2];
ao = splitted[3];
l = splitted[4];
}else {
miscell = splitted[0];
}
}
//print only not empty fields
pls note removing of unnecessary for loop and change of split character to \s from \s+
Just a thought, but you could also experiment if it helps to keep the whitespaces in the result for defining which column it belongs to.
lines.get(i).split(yourDelimiter, -1);
Its hard to tell if this helps without knowing what exactly your origin files are looking like, but you could give it a try.
e.g. if the values are always at a certain point in the splitted string with whitespaces, you could easily tell which column it belongs to and extract them.

Space delimiter added to following string

So, I'm using Scanner to parse a text file which is space and newline delimited. Each line has an index number which is loaded into an array and a string which is a label corresponding to that member of the array, like so:
0 Sydney
1 Alice Springs
2 Canberra
3 Bathurst
4 Orange
I'm using the following code to read the file:
public void readIndex (String indexFile)
{
int i = 0;
String label = null;
InputStream input = getClass().getResourceAsStream(indexFile);
Scanner parser = new Scanner(input);
parser.useDelimiter(" ");
while (parser.hasNextLine())
{
i = parser.nextInt();
label = parser.nextLine();
this.setLabel(i, label);
}
}
And finally, this code to print the results:
System.out.println("Cities loaded:");
for (int i = 0; i < cities.vertexCount(); i++)
{
System.out.println(cities.getLabel(i));
}
The strings are showing up fine, but there seems to be a leading whitespace for each of the labels. Here's the output:
Cities loaded:
Sydney
Alice Springs
Canberra
Bathurst
Orange
For example, the first string is being stored as " Sydney".
Is this an issue with my delimiter settings, or have I missed something else really obvious? Thanks in advance!
Scanner#nextInt only consumes integer input so the remaining String will contain a leading whitespace. You need to trim this character
label = parser.nextLine().trim();

Categories

Resources