0

I am trying to get the last element from the end of each line of my ArrayList/array.

For example i have these records int my list: (don't mind the language, Greek names)

Nikos Pappas : 321/2012999, C,8.53  
Marios Athanasiou : 321/2012001, A,6.89  
Stavroula Markou : 321/2011001, D,7.00  
Giannis Kallogirou : 321/2009005, ST, 6.89  
Nikoletta Stefanou : 321/2010001, D, 7.25  
Stathis Petrou : 321/2011002, E, 8.10  
Kostas Tzovalis : 321/2007667, C, 5.00  
Michalis Kotsis : 321/2009723, D, 7.12  
Maria Katsanou : 321/2012002, C, 5.50  

And I want to take: 8.53, 6.89,....,5.50 (marks of students)

This is what I've made so far (the file is the file which contains the above info)

  public static void main(String[] args)  {

    BufferedReader br = null;
    ArrayList <String> list = new ArrayList <> ();

    try
    {
        br = new BufferedReader(new FileReader("C:/Users/Stefi/Desktop/java_ask3.txt"));
        String str;


        //System.out.print("mpika");

        while((str = br.readLine()) != null)
        {
            list.add(str);
            System.out.println(str);
        }
    }
    catch(IOException e)
    {
        System.out.println("Κάτι πήγε στραβά! Προσπάθησε πάλι.");
    }
    finally
    {
        try
        {
            if (br != null)
            {
                br.close();
            }
        }
        catch(IOException e2)
        {
            System.out.println("Δεν μπορεσα να κλείσω το αρχείο.");
        }

    }

int x = list.size();
    String [] array = new String[x];
    array = list.toArray(array);

    for(int i=0; i<array.length; i++)
    {
        System.out.println(array[i]);
    }

    String [] f = new String[list.size()];
    String vathmos;

     for(int i=0; i<array.length; i++)
    {
        vathmos = list.get(i).replaceAll("\\D+", "");
        f[i] = vathmos;
    }


    System.out.println("\n\n\n Float Print\n");
    for(int i=0; i<array.length; i++)
    {
        System.out.println(f[i]);
    }

}

this is an example of my output:

3212012999853     
3212012001689    
3212011001700    
3212009005689

It takes all the numbers it finds. But I don't know how to take only the last float number. I know it's totally wrong to work like this, and work like this because I'll never get the float i want.

I also tried to convert my list into array and take the last element but didn't work out.

4
  • 2
    Why dont you create a Class Student that will have all these attributes(name,id,mark etc) of a student. After constructing those objects and adding them into the list through your main, simply iterate the list, get the mark of each student and print it? Commented Jan 8, 2014 at 2:00
  • 1
    Haven't thought about it. I got stuck with this idea and couldn't think anything else. Commented Jan 8, 2014 at 2:33
  • Aha, in general though I am suggesting you to totally avoid "spaghetti code" even if you are still in the begginning. This is because you will get used to it, its not reusable, its not readable, etc. Overall, its a bad practice. If you wish to keep your current implementation, at least create public static methods right after your main that will handle single modules and use them in your main. Commented Jan 8, 2014 at 2:41
  • 1
    Thanks! I'll keep that in mind and i will practise this way tomorrow. I knew it was a messy method but i was stuck! Thanks again for your reply! Commented Jan 8, 2014 at 2:45

4 Answers 4

1

You can try this

String s = line.replaceAll(".*(\\d+\\.\\d+)$", "$1");
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks!! That worked prety well and easy for me. It was exactly what i was looking for!
0

Split the line by a comma then get the last element of the resulting array

String[] splitArr = line.split(",");
String lastNumber = splitArr[splitArr.length - 1];

But best solution would be to have a Student class as suggested in comments

1 Comment

It worked out with the "best answer mark". I know it's a messy way and the best is with a Student Class, and i will work it out tomorrow with this way! Thanks a lot! I will keep that in mind!
0

If you store your records as Strings, you can use the substring method:

grade = Double.parseDouble(array[i].substring(array[i].length() - 3)); if you are sure the grade is always in x.xx form at the end of each String.

Also consider creating a class that would contain all the information about students in seperate fields, for example:

public class Student{
    public String name;
    public String surname;
    public int age;
    public double grade;
}

Of course this is just an example, you may hide implementation and provide methods you want as well. Then you could create any kind of collection of Student objects, so getting the specified value of any field for any student would be easy.

1 Comment

It worked out with the "best answer mark". But i will work it out with this way tomorrow because this is the correct way, so will have practise with both ways. Thanks a lot!
0

I can suggest couple String functions to add to your code. This is not tested code though -

Using String.split();

//This will hold all the numbers as String
List<String> masterList = new ArrayList<String>();
while((str = br.readLine()) != null)
{
       String [] lineValues = String.split(",");
       int countElements = lineValues.Length();
       masterList.Add(lineValues[countElements - 1]);
}

Using lastIndexOf();

//This will hold all the numbers as String
List<String> masterList = new ArrayList<String>();
while((str = br.readLine()) != null)
{
       int lastIndex = str.lastIndexOf(",");           
       masterList.Add(str.substring(lastIndex, str.length() - 1));
}

Once you have the masterList populated, you can loop through it and extract the float using

 Float.valueOf(masterList.get(i));

1 Comment

Advice taken! Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.