I'm trying to read from a text file, but I get this error I can't figure it out how to fix it .
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
and my code
try {
String scan;
FileReader file = new FileReader("C:\\Users\\W7\\workspace\\Lab 8\\students.txt");
BufferedReader br = new BufferedReader(file);
while((scan = br.readLine()) != null) {
String values = scan;
String[] val = values.split("\t");
String[] vals;
vals = val[0].split(":");
int size = val.length;
System.out.println(vals[1]);
switch (size) {
case 3 :
vals = val[0].split(":");
int id = Integer.parseInt(vals[1]);
vals = vals[1].split(":");
String name = val[1];
vals = val[2].split(":");
int grade = Integer.parseInt(vals[1]);
Student st = new Student(id, name, grade);
} catch (IOException e) {
System.out.println(e.getStackTrace());
}
My text file
ID:5 Name:john Grade:6
ID:6 Name:paul Grade:10
Length of vals is not known before accessing its first or second element:
String[] vals;
vals = val[0].split(":");
System.out.println(vals[1]);
Even before accessing the element at index 0, you need to make sure that vals is not an empty array by checking its length. This can happen, for example, when you encounter an empty line in the input which doesn't even have a tab.
The error is where you use vals[1] before checking the length of vals.
vals = val.contains(":") ? val[0].split(":") : null;
int size = (vals == null) ? 0 : vals.length; // which is the array I think you want
System.out.println(vals[1]);
switch (size) {
...
}
String values = scan;
String[] val = values.split("\t");
String[] vals;
vals = val[0].split(":");
int size = val.length;
System.out.println(vals[1]);
You sure the codes above can handle a blank line? You are assuming every single line has at least 1 ":"
Related
So I have a string that looks something like this:
text java.awt.Color[r=128,g=128,b=128]text 1234
How could I pop out the color and get the rgb values?
You can get the rgb values from that string with this:
String str = "text java.awt.Color[r=128,g=128,b=128]text 1234";
String[] temp = str.split("[,]?[r,g,b][=]|[]]");
String[] colorValues = new String[3];
int index = 0;
for (String string : temp) {
try {
Integer.parseInt(string);
colorValues[index] = string;
index++;
} catch (Exception e) {
}
}
System.out.println(Arrays.toString(colorValues)); //to verify the output
The above example extract the values in an array of Strings, if you want in an array of ints:
String str = "text java.awt.Color[r=128,g=128,b=128]text 1234";
String[] temp = str.split("[,]?[r,g,b][=]|[]]");
int[] colorValues = new int[3];
int index = 0;
for (String string : temp) {
try {
colorValues[index] = Integer.parseInt(string);
index++;
} catch (Exception e) {
}
}
System.out.println(Arrays.toString(colorValues)); //to verify the output
As said before, you will need to parse the text. This will allow you to return the RGB values from inside the string. I would try something like this.
private static int[] getColourVals(String s){
int[] vals = new int[3];
String[] annotatedVals = s.split("\\[|\\]")[1].split(","); // Split the string on either [ or ] and then split the middle element by ,
for(int i = 0; i < annotatedVals.length; i++){
vals[i] = Integer.parseInt(annotatedVals[i].split("=")[1]); // Split by the = and only get the value
}
return vals;
}
So, I'm reading from a txt file. The file is something like this, separate with a tab "/t"
ID name test date object
1 John pass 9/13 RC_CUST_1
2 John fail 10/13 RC_CUST_1
3 John pass
I'm reading the txt file like this:
String line="";
ArrayList<String> data = new ArrayList<String>();
FileReader fIn;
BufferedReader buff;
fIn = new FileReader("...");
buff = new BufferedReader( fIn );
while( ( line = buff.readLine() ) != null )
{
if(!line.isEmpty())
data.add(line);
}
In late of my code I do that:
ArrayList<String> name1 = new ArrayList<String>();
ArrayList<String> RC1 = new ArrayList<String>();
ArrayList<String> date1 = new ArrayList<String>();
ArrayList<String> pass1 = new ArrayList<String>();
String [] substr2;
for(int k=0;k<data.size();k++)
{
substr2=data.get(k).split("\t");
RC1.add(substr2[4]);
name1.add(substr2[1]);
date1.add(substr2[3]);
pass1.add(substr2[2]);
}
And I have an error because you can see, my ID number 3 has not any date or object. How can I fix that, and how can I know what ID has not a date or an object
I would like for example to print: ID number x has not date or ID number x has not any object if I have a error of this type
After the split on \t you get an array as result. you can check the length of the array before accessing the fields in it.
for(int k=0;k<data.size();k++) {
String [] substr2 = data.get(k).split("\t");
int length = substr2.length
if (length >= 5) {
RC1.add(substr2[4]);
} else {
System.out.println("no object found");
}
....
}
I have a data like :
in an arraylist of Strings I am collecting names .
example:
souring.add(some word);
later I have something in souring = {a,b,c,d,d,e,e,e,f}
I want to assign each element a key like:
0=a
1=b
2=c
3=d
3=d
4=e
4=e
4=e
5=f
and then I store all ordering keys in an array . like:
array= [0,1,2,3,3,4,4,4,5]
heres my code on which I am working :
public void parseFile(String path){
String myData="";
try {
BufferedReader br = new BufferedReader(new FileReader(path)); {
int remainingLines = 0;
String stringYouAreLookingFor = "";
for(String line1; (line1 = br.readLine()) != null; ) {
myData = myData + line1;
if (line1.contains("relation ") && line1.endsWith(";")) {
remainingLines = 4;//<Number of Lines you want to read after keyword>;
stringYouAreLookingFor += line1;
String everyThingInsideParentheses = stringYouAreLookingFor.replaceFirst(".*\\((.*?)\\).*", "$1");
String[] splitItems = everyThingInsideParentheses.split("\\s*,\\s*");
String[] sourceNode = new String[10];
String[] destNode = new String[15];
int i=0;
int size = splitItems.length;
int no_of_sd=size;
tv.setText(tv.getText()+"size " + size + "\n"+"\n"+"\n");
sourceNode[0]=splitItems[i];
// here I want to check and assign keys and track order...
souring.add(names);
if(size==2){
destNode[0]=splitItems[i+1];
tv.setText(tv.getText()+"dest node = " + destNode[0] +"\n"+"\n"+"\n");
destination.add(destNode[0]);
}
else{
tv.setText(tv.getText()+"dest node = No destination found"+"\n"+"\n"+"\n");
}
} else if (remainingLines > 0) {
remainingLines--;
stringYouAreLookingFor += line1;
}
}
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
How can I do this?
can any one help me in this..?
I would advise you to use ArrayList instead of String[]
So, if you want to add an element you just write
ArrayList<String> list = new ArrayList<String>;
list.add("whatever you want");
Then, if you want to avoid repetitions just use the following concept:
if(!list.contains(someString)){
list.add(someString);
}
And if you want to reach some element you just type:
list.get(index);
Or you can easily find an index of an element
int index=list.indexOf(someString);
Hope it helps!
Why don't you give it a try, its take time to understand what you actually want.
HashMap<Integer,String> storeValueWithKey=new HashMap<>();
// let x=4 be same key and y="x" be new value you want to insert
if(storeValueWithKey.containsKey(x))
storeValueWithKey.get(x)+=","+y;
else
storeValueWithKey.put(z,y); //Here z is new key
//Than for searching ,let key=4 be value and searchValue="a"
ArrayList<String> searchIn=new ArrayList<>(Arrays.asList(storeValueWithKey.get("key").split(",")));
if(searchIn.contains("searchValue"))
If problem still persist than comment
I have an array that is from .split command and want to put it into an array called String[][] datatabvars, I do not know how to turn datatabvars into a two dimensional array and put the data into it.
public String[] getList() {
String file_name = "path";
String[] links = null;
String[][] datatabvars = null; // this var
int numberOfDatatabs = 0;
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int i;
for(i=0; i < aryLines.length; i++) { //aryLines.length
if (aryLines[i].substring(0, 7).equals("datatab")) {
aryLines[i] = aryLines[i].replace("datatab["+Integer.toString(numberOfDatatabs)+"] = new Array(", "");
aryLines[i] = aryLines[i].replace(");", "");
datatabvars = aryLines[i].split(","); // this split array
numberOfDatatabs++;
}
}
System.out.println(datatabvars[0]);
}catch (IOException e) {
System.out.println( e.getMessage() );
}
return links;
}
Update the two lines(I added comment) as below: (I am assuming that rest of your code is working)
String[][] datatabvars = null; // this var
int numberOfDatatabs = 0;
try {
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
datatabvars = new String[aryLines.length][]; // INITIALIZED
int i;
for(i=0; i < aryLines.length; i++) { //aryLines.length
if (aryLines[i].substring(0, 7).equals("datatab")) {
aryLines[i] = aryLines[i].
replace("datatab["+Integer.toString(numberOfDatatabs)+"] =
new Array(", "");
aryLines[i] = aryLines[i].replace(");", "");
datatabvars[i] = aryLines[i].split(","); // this split array: ASSIGNED
numberOfDatatabs++;
}
}
System.out.println(datatabvars[0]);
In general, arrays are to avoided like the plague - use collections if possible:. In this case, split() returns a String[], so use that, but use List<String[]> to store multiple String[]:
List<String[]> datatabvars = new ArrayList<String[]>();
...
String[] array = input.split(",");
datatabvars.add(array);
You find life is much easier using collections than arrays.
In the input file, there are 2 columns: 1) stem, 2) affixes. In my coding, i recognise each of the columns as tokens i.e. tokens[1] and tokens[2]. However, for tokens[2] the contents are: ng ny nge
stem affixes
---- -------
nyak ng ny nge
my problem here, how can I declare the contents under tokens[2]? Below are my the snippet of the coding:
try {
FileInputStream fstream2 = new FileInputStream(file2);
DataInputStream in2 = new DataInputStream(fstream2);
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String str2 = "";
String affixes = " ";
while ((str2 = br2.readLine()) != null) {
System.out.println("Original:" + str2);
tokens = str2.split("\\s");
if (tokens.length < 4) {
continue;
}
String stem = tokens[1];
System.out.println("stem is: " + stem);
// here is my point
affixes = tokens[3].split(" ");
for (int x=0; x < tokens.length; x++)
System.out.println("affix is: " + affixes);
}
in2.close();
} catch (Exception e) {
System.err.println(e);
} //end of try2
You are using tokens as an array (tokens[1]) and assigning the value of a String.split(" ") to it. So it makes things clear that the type of tokens is a String[] array.
Next,
you are trying to set the value for affixes after splitting tokens[3], we know that tokens[3] is of type String so calling the split function on that string will yield another String[] array.
so the following is wrong because you are creating a String whereas you need String[]
String affixes = " ";
so the correct type should go like this:
String[] affixes = null;
then you can go ahead and assign it an array.
affixes = tokens[3].split(" ");
Are you looking for something like this?
public static void main(String[] args) {
String line = "nyak ng ny nge";
MyObject object = new MyObject(line);
System.out.println("Stem: " + object.stem);
System.out.println("Affixes: ");
for (String affix : object.affixes) {
System.out.println(" " + affix);
}
}
static class MyObject {
public final String stem;
public final String[] affixes;
public MyObject(String line) {
String[] stemSplit = line.split(" +", 2);
stem = stemSplit[0];
affixes = stemSplit[1].split(" +");
}
}
Output:
Stem: nyak
Affixes:
ng
ny
nge