Java, trouble with making a double array of string from file - java

I have a class "car", having five parametres of car (str brand, str model, str colour, int power, int tank), and I have a .txt with five cars, written like that:
Toyota Supra Black 280 80
Ferrari F430 Red 510 95
Nissan GT-R White 600 71
Koenigsegg Agera White 940 80
Mazda RX-8 Red 231 62
I have to read this list from file and make an array of lines array (cars), while each car array is an array of 5 parametres, like:
Cars[car][parametres], and push it into a object of a class (should be a peace of cake, and i think i can handle this)
But i have no clue how to deal with array. Only thing i have now is reading from file:
void 123() {
String[] ImpData = null;
try {
String str;
BufferedReader br = new BufferedReader(new FileReader("imp.txt"));
while ((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
} catch (IOException exc) {
System.out.println("IO error!" + exc);
}
}
Any suggestions?

Create a list of Car object and adding each line into the list as 1 Car object each.
ArrayList<Car> list = new ArrayList<Car>();
while ((str = br.readLine()) != null) { //Not checking your loop
String[] tok = str.split(" "); //str holds all car information
list.add(new Car(tok[0], tok[1], tok[2], tok[3], tok[4]));
}
Assuming your Car class has a constructor which accepts the 5 arguments.
Edit: (To fit requirement of using Array)
When you use array, you have to pre-allocate a fixed array length first. Using array is not suitable for storing data from files because there can exist any number of lines of data. Anyway, to answer your question on using array:
String[][] data = new String[numRecords][5]; //numRecords equals total car objects
int x=0;
while ((str = br.readLine()) != null) { //Not checking your loop
String[] tok = str.split(" "); //str holds all car information
data[x] = tok; //Assign entire row of tok into data
x++;
}
Once again, I seriously do not recommend reading data file into an array. If you really have to do so, you can pre-determine number of records in the text file first, then set the array size accordingly.
Side note: 2D arrays are also not a suitable data structure for storing data such as a car object with its own attributes.

You want a two dimensional array. However, note that the array size must be known in advance and you don't know how many lines are in the file. So, first read everything into a secondary linked list data structure (you could also read the file twice, this is not efficient). Now you have all the strings, make a two dimensional array and then split each string into an array of tokens, using the " " delimiter. If you want to treat the tokens as integers and strings, you can use an array of Object instead and store Integer, String, etc. Off the top of my head, something like this follows - also note in your post, you can't start a method with numbers :)
String[] ImpData = null;
try {
String str;
List<String> allStrings = new LinkedList<String>();
BufferedReader br = new BufferedReader(new FileReader("imp.txt"));
while ((str = br.readLine()) != null) {
allStrings.add(str);
}
br.close();
String[][] ImpData = new String[allStrings.size()][];
for(int i=0; i<allStrings.size();i++){
ImpData[i] = allStrings.get(i).split(" ");
}
} catch (IOException exc) {
System.out.println("IO error!" + exc);
}

I think what you are looking for is a 2-dimensional array.
The first dimension is the index for the car, the second are the 5 pieces that make it up. It looks like this: (not actual language, just a guide to build it.)
array is car[int][string, string, string, int, int]
car[0][Toyota,Supra,Black,280,80]
car[1][Ferrari,F430,Red,510,95]
So, referencing car[1] will tell you all about that car.
That's one idea, anyway...

for Car
class Car {
public String brand, model, colour;
int power, int tank;
}
structure
List<Car> cars = new ArrayLis<Car>()'
the most important part is safe analize line and fill part of data. The simplest (but not the best) is:
In out loop when You have line str line by line, set analyse:
String arg[] = str.split(" ");
Car c = new Car();
c.brand = arg[0];
c,model = arg[1];
c.color = arg[2];
c.power = Integer.parseInt(arg[3],0);
c.tank = Integer.parseInt(arg[4],0);
and then
cars.Add(c);

Related

Java .split() Array out of bounds

I keep getting this Array out of bounds error for the following code.
brock.txt = reflection program, routine, Arrow, snake game,
public static void main(String[] args) {
String filename = "brock.txt";
String line;
String [] cities = {};
int x = 0;
try {
BufferedReader eshread = new BufferedReader( new FileReader (filename));
line = "";
while ((line = eshread.readLine()) != null ) {
String[] store = line.split(",");
System.out.println(store[0]);
System.out.println(store[1]);
System.out.println(store[2]);
cities[x] = store[2]; //< keep getting an error here
x++;
}//end while loop
eshread.close();
}//end try
catch(IOException iox) {
System.out.println("failiure");
}//end catch
String [] cities = {} will make the array size to 0,when x is greater than 0 the error will occur,that's the reason,so you need to make cities a fixed size at first or use List to do it
You Must define the size of cities or use a list .
You initialized cities with an empty array({}), which means it has a length of 0(not an null, but an empty array). By using cities[0] you are expecting it has at least one element, which is not true.
To fix this, use an ArrayList<String> instead of a String array.
In agreement with the other comments. The issue is with the size of cities array which is being set to 0 and hence the issue for array out of bounds.
I tried the following code and it works if you want to work with a String array.
Else an ArrayList is a better solution if the size is not defined.
String [] cities = new String[10];

Java - Read a list of categories from a file

I have multiple .txt file(s) with different amounts of fruits in different categories. An example is this:
General Fruits:
apple
orange
grape
Specific Fruits x:
0: dragon fruit
1: lychee
2: star fruit
3: pomegranate
Specific Fruits y:
0: coconut
1: durian
Assuming can I read the file and store apple, orange, grape into a generalFruit[] string array, store dragon fruit, lychee, star fruit, pomegranate into a specificFruitX[] string array, store coconut, durian into a specificFruitsY[] string array?
So far, I have:
try (BufferedReader br = new BufferedReader(new FileReader(fileChooser.getSelectedFile().toString()))) {
String line;
String [] generalFruit = new String[50];
String [] specificFruitX = new String[50];
String [] specificFruitY = new String[50];
while ((line = br.readLine()) != null) {
// process the line.
System.out.println(line);
}
}
Thanks.
Yeah obviously you can do that,
What you need to follow below steps and you will do it.
-1 In while loop check if You have if(line.equals("General Fruits:"))
-2 If above condition is true make a boolean which turns On now.
-3 Now see if that boolean is on put the next string in Array generalFruit[]
Its really easy you can do it !!!
Yes, there are many easy ways to read files and set values into Lists, I always use *.properties files to show static combos normally, if you want to read that file to show many lists, you need to create something like this:
List<String> generalFruits = new ArrayList<String>();
List<String> specificFruitX = new ArrayList<String>();
List<String> specificFruitY = new ArrayList<String>();
When you use ArrayList, you have dynamic size of arrays, Is not a good practice set static sizes (50) to your lists, because your files may have many and many rows with fruits and if you have more than 50, you will get and exception.
Then, as you read the file, create objects inside the list, for example:
generalFruits.add(new String(line));
You have to do the same for each list you want to show in your app.
I hope it helps you.
Check out this code, I have made it work to read just General Fruits.
You can work on rest by understanding it.
String [] generalFruit = new String[4];
boolean generalFruitboolean=false;
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
String line;
int i=0;
while ((line = br.readLine()) != null) {
if(line.equals("General Fruits:") == true){
generalFruitboolean=true;
i=0;
}
if(generalFruitboolean==true && i<4){
generalFruit[i]=line;
i++;
}
}
for (int j = 0; j < generalFruit.length; j++) {
System.out.println(generalFruit[j]);
}
}
Hope it will be helpful. best of luck

text file to 2d arrays in java

I have had a look at other posts, but I am still stuck on this issue for a while now. I have a text file that has various new lines, each of different length. I want to store them in a 2d array so that I can call specific locations i.e. word[1][4].
I've managed to store them in an array - my code is below. Thanks for your help!
String line = null;
ClassToRead txtFile = new ClassToRead("test.txt"); //reading using bufferReader
String [][] words = new String[txtFile.readLines()][]; //this is where I want to store the words
while( (line = br.readLine())!= null ){
String [] newData = line.split("\\s+");
System.out.println(Arrays.toString(newData)); //prints out array
}
//I want to use specific locations in the 2d array e.g. System.out.println(words[3][5]);
Try to add the arrays to the 2d array... you could use a counter like in the example bellow.
int counter = 0;
while( (line = br.readLine())!= null ){
String[] newData = line.split("\\s+");
words[counter] = newData;
counter++;
System.out.println(Arrays.toString(newData)); //prints out array
}

How to compare against a null element in an array in java?

I have a program where I need to store the results in an arraylist:-
public class ReseedingDBRandomElements {
public static void main(String[] args){
try {
// getting the field Keyword from the csv
String csvfile="/Users/dray/Downloads/ReseedingDBRandomKeywords.csv";
BufferedReader br =new BufferedReader(new FileReader(csvfile));
StringTokenizer st = null;
String line="";
int linenumber=0;
int columnnumber;
// initializing the parameter for each column
int free = 0;
int free1 = 0;
// create the ArrayList
ArrayList<String> Keyword = new ArrayList<String>();
ArrayList<String> Alternate = new ArrayList<String>();
// reading through the csv file
while((line=br.readLine())!=null){
linenumber++;
columnnumber = 0;
st = new StringTokenizer(line,",");
while(st.hasMoreTokens()){
columnnumber++;
String token = st.nextToken();
if("Keyword".equals(token)){
free=columnnumber;
System.out.println("The value of free :"+free);
}else if ("Alternate".equals(token)){
free1=columnnumber;
System.out.println("The value of free1 :"+free1);
}
if(linenumber>1){
if (columnnumber==free)
{
Keyword.add(token);
}else if (columnnumber==free1){
Alternate.add(token);
}
}
}
}
// converting the keyword ArrayList to an array
String[] keyword = Keyword.toArray(new String[Keyword.size()]);
for(int i=0;i<keyword.length;i++){
System.out.println(" The value of the keyword is :"+keyword[i]);
}
// converting the alternate ArrayList to an array
String[] alternate = Alternate.toArray(new String[Alternate.size()]);
for(int i=0;i<alternate.length;i++){
System.out.println("The value of the alternate is :"+alternate[i]);
}
ArrayList<String> AlternateNew = new ArrayList<String>();
for(int i=1;i<keyword.length;i++){
if(keyword[i].equals(keyword[i-1])){
AlternateNew.add(alternate[i-1]);
}else if(!(keyword[i]==(keyword[i-1]))){
AlternateNew.add(alternate[i]);
}
}
String[] alternatenew = AlternateNew.toArray(new String[AlternateNew.size()]);
System.out.println("The length of the array is :"+alternatenew.length);
for(int i=0;i<alternatenew.length;i++){
System.out.println("the value of the alternatenew :"+alternatenew[i]);
}
}catch (Exception e){
System.out.println("there is an error :"+e);
}
}
}
The following is the csv file
Keyword,Alternate
ego kit,baby doll
ego kit,garage park
ego kit,random beats
galaxy tab,venus
galaxy tab,earth
galaxy tab,sun
What I am trying to do is compare elements and store it in an arraylist and display the results, but when last element is getting compared i.e 'galaxy tab' is getting compared to an empty field after last 'galaxy tab', it is not storing the previous result in the arraylist which is 'sun'
The following is the result of the program :
The value of the alternate is :baby doll
The value of the alternate is :garage park
The value of the alternate is :random beats
The value of the alternate is :venus
The value of the alternate is :earth
The last element is not getting stored in the arraylist.
Do not understand why? New to Java programming.
This section has a few problems also present throughout
AlternateNew.add(alternate[0]);
for(int i=1;i<keyword.length;i++){
if(keyword[i]==(keyword[i-1])){
AlternateNew.add(alternate[i]);
}else if(!(keyword[i]==(keyword[i-1]))){
AlternateNew.add(alternate[i]);
}
}
The naming convention in Java is to start with a lowercase letter for a variable name (unless it is a constant), which is why object AlternateNew is highlighted as if it were a class name.
The else if block tests the opposite of the same condition as its if. You could comment out if(!(keyword[i]==(keyword[i-1])), delete, or replace it with a more readable reminder comment, and the result would be the same.
AlternateNew.add(alternate[i]); happens regardless of this condition, in either branch of the if, so either remove the if statement entirely or fix some typo.
As for your actual [edit: original] question, I can't find anything wrong. Are you sure you didn't forget to save the csv file? I ran it using a text file and got output contrary to your post!

Storing input from text file

My question is quite simple, I want to read in a text file and store the first line from the file into an integer, and every other line of the file into a multi-dimensional array. The way of which I was thinking of doing this would be of creating an if-statement and another integer and when that integer is at 0 store the line into the integer variable. Although this seems stupid and there must be a more simple way.
For example, if the contents of the text file were:
4
1 2 3 4
4 3 2 1
2 4 1 3
3 1 4 2
The first line "4", would be stored in an integer, and every other line would go into the multi-dimensional array.
public void processFile(String fileName){
int temp = 0;
int firstLine;
int[][] array;
try{
BufferedReader input = new BufferedReader(new FileReader(fileName));
String inputLine = null;
while((inputLine = input.readLine()) != null){
if(temp == 0){
firstLine = Integer.parseInt(inputLine);
}else{
// Rest goes into array;
}
temp++;
}
}catch (IOException e){
System.out.print("Error: " + e);
}
}
I'm intentionally not answering this to do it for you. Try something with:
String.split
A line that says something like array[temp-1] = new int[firstLine];
An inner for loop with another Integer.parseInt line
That should be enough to get you the rest of the way
Instead, you could store the first line of the file as an integer, and then enter a for loop where you loop over the rest of the lines of the file, storing them in arrays. This doesn't require an if, because you know that the first case happens first, and the other cases (array) happen after.
I'm going to assume that you know how to use file IO.
I'm not extremely experienced, but this is how I would think about it:
while (inputFile.hasNext())
{
//Read the number
String number = inputFile.nextLine();
if(!number.equals(" ")){
//Do what you need to do with the character here (Ex: Store into an array)
}else{
//Continue on reading the document
}
}
Good Luck.

Categories

Resources