Java / Android Coding - Beginners Help

Soldato
Joined
28 Apr 2011
Posts
15,224
Location
Barnet, London
Some of you may have seen my other thread in which I have explained I'm attempting to learn Java, with a goal of then moving on to Android and being able to write my own apps. In my youth I did a lot of programming, but never really progressed out of Basic.

I have bought a couple of video tutorial courses on Udemy and working my way through them.

I'm making this thread for me to ask for a little help in understanding some things. At the moment I don't think it's falling into place just yet. Perhaps because I keep thinking of classes like procedures, when they are not, they are objects.

Now, doing ArrayLists I can't get my head around the structure of calling the variable from within the ArrayList. When to use 'this.' and when it's 'Customer' for the class or 'customer' for the variable and when I link these with a '.'

I'm sure it sounds silly for seasoned programmers, but maybe someone can phrase it in a way it will click with me?

Here's a bit of code for example -

Code:
package com.AndyCr15;

import java.util.ArrayList;

/**
 * Created by AndyCr15 on 01/03/2017.
 */
public class Branch {
    private String branchName;
    private ArrayList<Customer> customers;

    public Branch(String branchName, ArrayList<Customer> customers) {
        this.branchName = branchName;
        this.customers = new ArrayList<Customer>();
    }

    public String getName() {
        return branchName;
    }

    public boolean newCustomer(String customerName, double intialAmount) {
        if (findCustomer(customerName) == null) {
            this.customers.add(new Customer(customerName, intialAmount));
            return true;
        }
        return false;
    }

    public boolean addCustomerTransaction(String customerName, double amount) {
        Customer existingCustomer = findCustomer(customerName);
        if (existingCustomer != null) {
            existingCustomer.addTransaction(amount);
            return true;
        }
        return false;
    }

    private Customer findCustomer(String customerName) {
        for(int i = 0; i<this.customers.size(); i++){
            if (this.customers.get(i).getCustomerName().equals(customerName)) {
                return this.customers.get(i);
            }
        }
        return null;
    }
}

And this is Customer -

Code:
package com.AndyCr15;

import java.util.ArrayList;

/**
 * Created by AndyCr15 on 01/03/2017.
 */
public class Customer {
    private String customerName;
    private ArrayList<Double> transactions;


    public String getCustomerName() {
        return customerName;
    }

    public ArrayList<Double> getTransactions() {
        return transactions;
    }

    public Customer(String customerName, double initialAmount) {
        this.customerName = customerName;
        this.transactions = new ArrayList<Double>();
        addTransaction(initialAmount);
    }

    public void addTransaction(double amount) {
        this.transactions.add(amount);
    }

}

So the line I still look at and think 'I wouldn't have been able to recall that' is -

Code:
if (this.customers.get(i).getCustomerName().equals(customerName)) {
                return this.customers.get(i);
            }

Can anyone help me get my head round how it works?

I guess it's the whole thing about Branch in itself is a list of branches, how do I link customer lists to each branch? When do I use this. rather than just the ArrayList name. How/why do I keep just using . to link different commands together? I get confused as to when am I getting customer as a 'card of information' and when am I getting a piece of information from that card.

I suppose the weird thing is, actually all the code makes sense as I read it through, I know what each bit is doing, but I struggle to know it well enough to recall how I should use it, unless I look things up. As I said, I'm looking for it to 'click'.

Any help, or I should just keep cracking on and it will come in time? (I know in the other thread I was told to crack on, but I guess I worry I should be learning quicker.)

(Long post, thanks for taking the time to read)
 
Thanks for the help. It all makes sense. I just can't recall and write it myself. I guess I can learn through repetition of doing it over and over. I started one like the above, but for a shoe shop, with a shoe class made of style, colour, size and price. I guess just keep making things like this and I will get the hang of it.

I've not got as far as maps yet. I'm only 22% of the way into the course. The first 15% flew by too, it's really slowed down now... so I could be doing this for some time!
 
So... I think I'm getting it as I just debugged and got working this code -

Customer is made of -

private String customerName;
private ArrayList<Double> transactions;

Code:
public void listCustomerTransactions(String name) {
        Customer currentCustomer = findCustomer(name);
        ArrayList<Double> transactions = currentCustomer.getTransactions();
        int totalTransactions = transactions.size();
        for (int i = 0; i < totalTransactions; i++) {
            double amount = transactions.get(i);
            System.out.println("Transaction " + (i+1) + " was " + amount);
        }
    }

    private Customer findCustomer(String customerName) {
        for (int i = 0; i < this.customers.size(); i++) {
            if (this.customers.get(i).getCustomerName().equals(customerName)) {
                return this.customers.get(i);
            }
        }
        return null;
    }

To visualise it, I have a rolodex of Customers. Each card in the rolodex has a customer name written on and any transactions they have made listed.

When I "Customer currentCustomer = findCustomer(name);" it effectively finds the correct card, pulls it from the rolodexand photocopies it*. I label this photocopy currentCustomer.

Then when I "ArrayList<Double> transactions = currentCustomer.getTransactions();" I've copied down the transactions from the photocopy onto a piece of paper in front of me.

When I "double amount = transactions.get(i);" I've counted through this handwritten list (starting at zero) to the i'th item on the list and made that be my variable 'amount'.

Am I visualising it right?

* does it do this? Do the transactions info come, can I access the transactions without the writing them down on paper that comes next? Or do I just get a reference of where the card is? More like a little label is stuck to the card in the rolodex with currentCustomer written on it? I still need to take the name or transactions of the card if I want to use them?
 
Yeah, that makes sense, although I would have thought finding the customer just the once and then using that reference would be more efficient, not keep going through the rolodex each time? But yes, maybe no need to reference the transactions into a new Array. (I realise here it's not copying the transaction list of the rolodex card, it's sticking a little post-it saying here are the transactions.)

The problem I'm finding, a lot of the time people that explain Java use a lot of Java terminology when explaining it. I prefer the 'rolodex' type of explanation... (or relating it to physical actions at least)

Thanks for the help. Moving on to Inner and Abstract Classes & Interfaces now! :)
 
Thats some good progress you're making!

Thanks. I have a very logical mind, which I think helps. I honestly wonder sometimes if I'm clever enough though! We'll see I guess :)

Interesting reading what you're coming across, ever thought of keeping this thread alive as a little mini blog type thing? Not sure if that is against forum rules.

I don't see why not. Do you mean just for interest, or maybe so it might help others setting off on the same path as me?

I've actually just bought another Udemy Course. Related to the comment above about how a tutor explains something, I thought I'd try someone else. I watched one preview video and liked how this guy explained things. Quite surprising it's only 12 hours, but 165 videos... We'll see how I get on with that one as well as the first I bought.
 
I'm happy to work up my own portfolio, but I guess that will take a fair bit of time, so I think the qualification is better to have for me. I see it's multiple choice too, which will help me as I think I can read and understand the code a lot better than I can write it at the moment! I assume there are some mock versions I can try before, to see if I'm good enough (not now, but in time). I also note it's only 65% for a pass? Doesn't sound hard at this point?

The first course I started had me install Intellij IDEA to code with, which does seem pretty good, but the second course the guy uses Eclipse, which is the one I've heard Devs talk about in the past. I know it's rather subjective, but which is 'better' to work with?

Also, really finding this second (much shorter) course much better. It's odd, the first course I've written lots of code, worked through various challenges. The second, I've not written any code, but understanding things so much better. For example, I've just done a lesson on Static variables and methods. I had no idea what Static meant before. All makes sense now!

I think perhaps it's good to do both. On the one hand, writing the code itself is a great thing to be doing, but there are plenty of times I've not really understood why I was using the code I did. I think I'll get ahead on this second course and then 'keep up' with the first, writing code and putting into practise the things I've learnt.
 
Thanks for the comments guys. Hacker Rank looks fun. Just did one of the ijntroduction tests and found it quit easy. I think that will work quite well in conjunction with my course that doesn't have me programming much. Thanks.

**EDIT** The challenges often say this -

/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */

I've not come across this yet though? StdIn and StdOut?

**EDIT** So StdIn and StdOut aren't commands or variables? Just to use scanner and then system.out.println is apparently what it's after...
 
Last edited:
hi andy. can you link to the video training you're bought and howd you'd rate them so far? is something i'd like to do too

The first one I signed up to is this one. It's over 60 hours in content with lots of challenges along the way (which probably at least doubles the course time, if not more). Doing 30 mins to an hour a day, I think this would take around 3 months for me to do. I'm 26% of the way in and it does seem very thorough.

The second one is this one. I feel the guy is explaining more in the early stages and I think I'd have done better to start here and then run the first along side it as I go. Only 12 hours of content, no challenges but a few quiz's. I'm 25% of the way in and at this point it's not covered a lot of what Tim has in the first, but at the same time there's a lot more things that clicked and make sense to me now.
 
I agree he's very active in adding new content and answering questions. I recommend take a look at the second one I posted though too. If you get it on sale for £15, it's well worth it.
 
I need some help with today's '30 days of coding' challenge.

I actually thought it was quite easy, but my code gets run time errors from test 2 onwards.

Here's the challenge. Here's my code -

Code:
public class EvenOddString {
    static String[] output = new String[2];
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int numberOfWords = sc.nextInt();
        sc.nextLine();

        for (int j = 0; j < numberOfWords; j++) {
            String string = sc.nextLine();
            int length = string.length();
            String evens = "";
            String odds = "";

            // collect the even letters

            for (int i = 0; i < length; i += 2) {
                evens = evens + string.charAt(i);
            }
            // collect the odd letters

            for (int k = 1; k < length; k += 2) {
                odds = odds + string.charAt(k);
            }
            output[j] = (evens + " " + odds);
        }
        for (int x = 0; x < numberOfWords; x++) {
            System.out.println(output[x]);
        }
    }
}

Any ideas? I'm guessing something is too big for something... but the parameters sat it's never more than 10,000 characters in the string, so int's should be fine. Anything else I'm missing?

** EDIT **

Never mind... I'm a n00b. I limited the string array to 3... set to 10 and all is good :)
 
Last edited:
A small update. I finished the second video course a couple of days ago, so it took me just under 3 weeks, doing an hour or so a day. Mind you, watching video was probably only around a third/half of the time I would spend coding/learning. I've been stopping and taking notes, screenshots (annotated) as I go, to give me something to refer back to.

I'm now back on the first video course (Java Masterclass) with Tim B, and I think things are making a little more sense. I still find Tim sometimes assumes some knowledge when explaining something and loses me.

Right now, while learning about Abstract Classes and Interfaces (I think I have them locked down from the second course tbh) I'm installing the Android Developer Studio and I'm going to make a start into the Android course that Tim has done too. I guess the first 10% or so will be very simple stuff, but I'd like to at least get a look at how Android apps are made now, then we'll see which I'll work through more/quicker, Java or Android.

I'm getting on okay with the 30 Days of Code on HackerRank. It was pleasing today that I managed to do the challenge about Linked List and then Exceptions, pretty much just using my own notes and not needing to look for answers in the 'discussion' tab. Green ticks first time!

So, still enjoying it. Progress feels slow, but it is still progress!
 
Thanks, for the book there looks to be a new version of Jan 2017 which included Nougat, have added it to my wishlist.

Thanks for the link to the course, I think I've looked at one of them, but would maybe start with the beginners course first.

Beginners says 4 weeks... intermediate says 60 hours? Any idea how that works? 4 weeks doing how much each day? 60 hours or video content?
 
So not directly linked to Java as the title suggests, but I've published my first (two) Android apps!

https://play.google.com/store/apps/developer?id=AAUK

Yes, the Fart App is very childish and silly, but in my current Android course by Rob Percival a challenge was set around a sound app, so I adapted it a little :) I mainly did it as an experience of publishing an app and it was very interesting, it took three attempts.

1) The image I used I had found through a Google search and clearly Google knew and denied the app for copyright reasons.

2) Switched in my own image. Declined as although the app had a 12 rating (due to the nature of the image, slightly sexual) the icon and screenshots, which can be seen by anyone, not covered by the rating, were not appropriate. (Again, lycra clad buttocks)

3) Success! I blurred the screenshots and icon and we're all good! Then just had to remove a bug where the image was too large for my Pixel XL (worked fine on the emulator as a Nexus 4)

I then slightly adapted the Connect 3 app that I made in the course and added that. When all is okay, it seems to happen within 30 minutes or so, so pretty quick!

I can see why there are so many sound board apps though, they really are very easy to make. The fart app was almost going to be a 'Ferris Bueller Sound Board', but gathering all the media would have slowed things down somewhat, when the main reason was learning about uploading to the store.

I might do one in the future though :)
 
Thanks. At the moment I'm switching between Tim's Java course and Rob's Android course. I feel I should work through the Java one first but 1) Tim is quite slow and not the best teacher 2) the Android one is allowing me to actually get some apps/projects out there... hence I'm doing bits of both.

I have a couple of basic app ideas, one a copy of one I use now but has stopped being developed and another fairly simple one. Neither are very exciting, but give me a goal of something to work towards. There is no doubt the best way to learn is to do, doing these two apps I was googling how to do all kinds of (fairly simple) things. (Locking an app in portrait, changing theme colours, debugging an error on my Pixel where the image was simply too big)
 
So, the first two apps I made I've removed from the Play Store now, but I have three other apps. They're all relatively simple, although the kitchen timer took a good couple of weeks and a lot of hours to get it all working as intended.

https://play.google.com/store/apps/developer?id=AAUK

I'm now working on a Biking App which has a variety of features -

- Add multiple bikes you own
- Weather info and rain alerts*
- Log fuel ups and get various stats per bike (ave MPG, miles this year*)
- Log maintenance jobs with a cost if applicable (again, some stats like how much £££ per bike per year)
- Locations page with Biker hotspots or UK tracks shown on a map, with a favourites page to log your own.
- Emergency button*... for emergencies
- Ride Out page*, track each others location, group chat

* not implemented yet
 
Can anyone help me? I'm trying to parse an xml file located here http://m.highways.gov.uk/feeds/rss/AllEvents.xml

I have code that lets me do it when it's in my res folder (although I think it gave an error about the actual xml) but I can't make it connect and parse the xml via the url above. Can anyone help?

I have a SAXHandler all set up -

Code:
public class SAXHandler extends DefaultHandler{

    private TrafficEvent newTrafficEvent;
    private String content;
    private String latitude;
    private String longitude;

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        super.startElement(uri, localName, qName, attributes);
        if(qName.equals("title")){
            newTrafficEvent = new TrafficEvent();
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        switch (qName){
            case "title":
                newTrafficEvent.title = content;
                break;
            case "road":
                newTrafficEvent.road = content;
                break;
            case "category":
                newTrafficEvent.delay = content;
                break;

            case "latitude":
                latitude = content;
                break;
            case "longitude":
                longitude = content;
                newTrafficEvent.location = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
                break;
            case "description":
                newTrafficEvent.description = content;
                Traffic.trafficEvents.add(newTrafficEvent);
                break;
        }
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        content = String.copyValueOf(ch, start, length).trim();
    }
}
 
Back
Top Bottom