Violet_82 89 Posting Whiz in Training

No that's fine, I'd like to try to learn that, but I'm not too sure what a properly formatted request should be. The link you sent a while back essentially says that a GET request would be something like this:

GET http://fashionboutique.com/customers
    Accept: application/json

So I guess this should be my "GET request from scratch"? If that's the case I could combine them in a string and pass them on onto the server as you suggested. Then the server would return back the dummy string, in a string as you've shown in your reply, so something likeso literally Dummy, 1, 9.99. When you then say that I need to decode and parse the string, you mean converting that return string to a json object (JSONObject)?

Violet_82 89 Posting Whiz in Training

Thanks for the feedback. Fair comment on setters and getters, I have the tendency to add them all the time, I will remove the ones that are not needed.

Because you will be passing the messages by simple method calls you do not need any http classes. Just construct the request string and pass it to the server

I might have misunderstood what you said earlier but I thought that this was the way to construct the request

 String USER_AGENT = "Mozilla/5.0";
        String url = "http://www.google.com";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        // optional default is GET
        con.setRequestMethod("GET");
        //add request header
        con.setRequestProperty("User-Agent", USER_AGENT);
        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        //print result
        System.out.println(response.toString());
    }

So if I understand correctly you're saying I only need something like this

public void contructGetRequest() throws Exception {
        String USER_AGENT = "Mozilla/5.0";
        String url = "http://www.google.com";
        server.passRequestToServer(USER_AGENT, url);
    }

and the server will have that method which will return the Dummy, 1, 9.99 formatted as json?

Violet_82 89 Posting Whiz in Training

OK, so I've started up with something, but I'm not entirely sure that the GET request is right.
Here's what I have so far:

public class TestRest {

    private static Server server;
    private static Client client;
    public static void main(String[] args) {
        server = new Server("Dummy", 1, 9.99);
        client = new Client(server);

    }

}

The Server class

public class Server {   
    private String resourceName;
    private int ID;
    private double price;

    public Server(String resourceName, int iD, double price) {
        this.resourceName = resourceName;
        ID = iD;
        this.price = price;
    }

    public String getResourceName() {
        return resourceName;
    }
    public void setResourceName(String resourceName) {
        this.resourceName = resourceName;
    }
    public int getID() {
        return ID;
    }
    public void setID(int iD) {
        ID = iD;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }

    public String parseRequest() {
        //TODO:find out how to parse request
        String message = null;      
        return message;
    }

}

The client class

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class Client {

    Server server;

    public Client(Server server) {
        this.server = server;
    }

    public Server getServer() {
        return server;
    }

    public void setServer(Server server) {
        this.server = server;
    }

    public void contructGetRequest() throws Exception {
        String USER_AGENT = "Mozilla/5.0";
        String url = "http://www.google.com";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        //add request header
        con.setRequestProperty("User-Agent", USER_AGENT);

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode); …
Violet_82 89 Posting Whiz in Training

OK great, thanks, I will give it a go and post the code here then.
When you mentioned Client and Server I didn't realize you were talking just about normal java classes, that's why I was a bit confused as to where to start from, but from what I can see you mean just simple java classes, that certainly gives me something to start with :-)!

Violet_82 89 Posting Whiz in Training

HI thanks. I gave that a good read, I think I have an idea of how it works now. However, I'm not sure where to start from. I mean, I saw this one here https://spring.io/guides/gs/rest-service/ which is a start and does a lot of the configuration for you essentially - but I'm mindful of your suggestion not to go for an already developed solution, but surely in the real world all the configuration and setting up is probably done for you - for example I wouldn't really know how to start coding for this one...

Violet_82 89 Posting Whiz in Training

Fair enough. I only suggested Java as that's the language I know, but I see your point. Do you suggest any specific guide/tutorial that you know could help at all?

Violet_82 89 Posting Whiz in Training

Hi guys,
I wonder if this is something I could do on this forum.
I've never worked with REST, so I thought that it could be a good exercise to try to develop a very small and simple Java application and try to make use of REST as well.
I found a brief which seems simple enough, I'll share it with you (I'm happy to change this of course if you think it's useful as for me it's just practice).

As a Rest Client
I want to submit new orders for bricks
So I can start customers’ orders

Given
A customer wants to buy any number of bricks
When 
A "Create Order" request for a number of bricks is submitted
Then
An Order reference is returned
And
The Order reference is unique to the submission

There will be more stuff later about retrieving an Order, but I thought this is a good start.

Now, I said above that I have no experience with REST, so I've been doing a bit of research and before I start coding I thought it might be a good idea to sort of clarify how we should proceed and the tech needed (I could also upload everything to git so that anybody else interested in it could benefit).

I guess I could start with a normal Java project, have a POJO Order class and a Brick one and a main class which would create the necessary objects, they seem to …

Violet_82 89 Posting Whiz in Training

ANd yes, those two overriden methods are not doing anything, it was just something else I was trying intead of doing the way I did it in the end - which I didn't really like it anyway.

Violet_82 89 Posting Whiz in Training

Hi guys, I was trying to sort an arrayList using a comparator but I didn't have much luck, or at least it seems like there is something slightly wrong with it.
I have these objects in the arrayList

employeeCollection.add(new Employee("Dan", 112));
employeeCollection.add(new Employee("Tim", 2));
employeeCollection.add(new Employee("Rick", 11));
employeeCollection.add(new Employee("Jack", 19));
employeeCollection.add(new Employee("Sid", 1));

and before sorting I have this

Name: Dan: 
ID number: 112:
Name: Tim: 
ID number: 2:
Name: Rick: 
ID number: 11:
Name: Jack: 
ID number: 19:
Name: Sid: 
ID number: 1:

and after sorting I have this:

Name: Dan: 
ID number: 112:
Name: Jack: 
ID number: 19:
Name: Rick: 
ID number: 11:
Name: Sid: 
ID number: 1:
Name: Tim: 
ID number: 2:

so it didn't go that well. Here is the code I've used, and the questions are:
-why isn't this sorted properly?
-what would I need to do to sort it in ascending order

/*
 * This tests Array list of employees*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TestCollections {
    private static List<Employee> employeeCollection = new ArrayList<Employee>();

    public static void main(String[] args) {
        createEmployees();

    }

    private static void createEmployees() {
//      for(int i = 0; i < 10; i++) {
//          Employee employee = new Employee("Jo_" + i, i);
//          employeeCollection.add(employee);
//      }
        employeeCollection.add(new Employee("Dan", 112));
        employeeCollection.add(new Employee("Tim", 2));
        employeeCollection.add(new Employee("Rick", 11));
        employeeCollection.add(new Employee("Jack", 19));
        employeeCollection.add(new Employee("Sid", 1));

        printEmployees();

        //Collections.sort(employeeCollection);
        // Sorting
        Collections.sort(employeeCollection, new Comparator<Employee>() {
            @Override
            public int compare(Employee employee, Employee employee1)
            {

                return  employee.getName().compareTo(employee1.getName());
            }
        }); …
Violet_82 89 Posting Whiz in Training

Right, lol. I find it a bit odd but yes, understood :-), thanks!

Violet_82 89 Posting Whiz in Training

Hi guys,
I seem to have an issue with a boolean method returining a value. Here is the code excerpt - irrelevant code omitted:

public class StreamsTest {

    public static void main(String[] args) {
        String[] arr = new String[]{"a", "b", "c"};         
        //convert array to string with streams
        List<String> list = Arrays.stream(arr).collect(Collectors.toList());        
        isElementInIt(list);   
    }

    static boolean isElementInIt(List<String> list) {
        if(list.isEmpty()) {
            return false;
        }
        else {
            for (String string : list) {
                if (string.contains("a")) {
                    return true;
                }
                else {
                    return false;
                }
            }
        }       
    }
}

STS says that the isElementInIt method should return a boolean value, but it's already doing that whatever happens, so I'm not too sure why the error. Any idea?
thanks

Violet_82 89 Posting Whiz in Training

sorry for leaving this for so long.
So this is actually more interesting than I thought.
I did try to repair windows but when I get to the reinstall screen the language available there is only english. SO did a bit of research, turned out that by using some software called Vistalizator I could install the other language I needed. I did that as a MUI package - that's because you can only do it this way in Windows 7 home premium apparently, but when I go back to the repair screen I still get only english and sadly choosing the other language is absolutely crucial.
So what alternative do I have? Download a copy (legit of course) of Windows 7 and use my windows key - if that's still legible at the back of my laptop?

Violet_82 89 Posting Whiz in Training

cool thanks guys. I forgot to mentioned that the language of WIndows needs to be changed too, which is why I was thinking to reinstall the OS directly from the recovery partition. @JamesCherril, I will start with your suggestion as I do have the recovery partition. WHen you say the recovery image, do you mean the recovery partition or do I have to create a recovery image from the recovery partition?

Violet_82 89 Posting Whiz in Training

Hi chaps, I have a Dell XPS17, dual booting with Windows and Ubuntu on it.
I have to give it away and therefore reinstall windows. Usually, I'd format the whole HD and reinstall Windows, but I don't have the Windows CD – it wasn't dispatched with the laptop unfortunately – so I'd like to try to do everything with the Recovery partition. I checked and it appears to be there. Now, can I format the whole HD except the Recovery partition so that I reinstall windows and remove Ubuntu with some Windows' utility rather than manually formatting it?

Violet_82 89 Posting Whiz in Training

Right, so I followed your advice and now I have this structure:
Library.ts:
-Contains an array of Book and add, remove and edit book;
Book.ts:
-Contains the properties of the book, author, title etc with setters and getters
book-form.component:
-This component handles the logic of the form submission. When the form is submitted the data is passed to it and this component uses the form data to create a Book object and to stash it into the array of Book
So far so good.
I then have a separate book.component which handles the dispay of the books in a table. This table has the records but also the remove and edit buttons. And this is where the problems start. Somehow I have to be able to call the remove and edit method which are in the Library.ts class from here, but the object of type Library is only created in the other component, so is there a way to share that Library object so I can access it from here too?

Violet_82 89 Posting Whiz in Training

thanks, yes I think it makes sense although ultimately I want that array to be replaced by data that comes from a database. In any case, in terms of code structure, you're saying to have like two classes, one like Book like

export class Book{
    private _bookID: number;
    private _bookAuthor: string;
    private _bookTitle: string;
    private _location: string;
    private _medium: string;
    private _notes: string;

    public set bookID(bookID: number){
        this._bookID = bookID;
    }...

and one Library like

//import {Book} from './book';

    export class Library{

      private _books: Book[];
      public get books(){
        return this._books;
      }

      public addBook(){
      //// TODO: 
      }
      public removeBook(){
      //// TODO: 

is that what you meant?

Violet_82 89 Posting Whiz in Training

Hi guys, I've got an issue with my angular application, I've got a form which is meant to create a new record (object) and push this object into an array.
My set up is the following:
I have a book.component.ts whic contains an array of IBooks as such:

books: IBook[] = [
        {
            "bookID":356,
            "bookAuthor":"John Beck",
            "bookTitle":"The story of my life",
            "location":"Shelf downstairs",
            "medium":"paper",
            "notes":""
        },
        {
            "bookID":900,
            "bookAuthor":"Jack Mills",
            "bookTitle":"They",
            "location":"Shelf downstairs",
            "medium":"PDF",
            "notes":"This is on my laptop and phone"
        }
    ];

This file also contains the static method

static createNewRecord($record): void{
        console.log("createNewRecord() called");
        console.log($record);
        this.books.push($record);
        console.log($record);
      //  $event.preventDefault();
    }

This method is static because it gets called from another component - the book-form.component - which is essentially a form which allow users to create a new books' object. The idea is that when the users submits the form the createNewRecord is called and adds the record to the books array. Now, when I run the application the compiler tells me that
"books.component.ts (51,14): Property 'books' does not exist on type 'typeof BooksComponent'." which kind of makes sense because I'm trying to access a non-static member (books) from a static method createNewRecord. My question is, how would I get around that?
Like I said the reason why I made that method static is because I needed to access it from another component.
I suppose I could make the array static too, but I'm not sure that's the right way to go. What do …

Violet_82 89 Posting Whiz in Training

OK got it, thanks for clarifying it.

Violet_82 89 Posting Whiz in Training

The first way it adds the first user then notifies him for each product, then it adds the second user and notifies both him and the first again

Hang on why does it notify the first user again if the second iteration of the first loop is on the second user, meaning, why is everybody notified again and again?

Violet_82 89 Posting Whiz in Training

Right, interesting. I fixed it, but alas, I don't understand why this fixes it. Basically rather than looping through users and then products and call setAvailable from there, so like this:

for(Observer user : users){
            for(Product currentProduct : products){
                currentProduct.addObserver(user);
                currentProduct.setAvailable(true);

            }
        }

I did this:

        for(Observer user : users){
            for(Product currentProduct : products){
                currentProduct.addObserver(user);
                //System.out.println(user + " " + currentProduct);
            }
        }
        for(Product currentProduct : products){
            currentProduct.setAvailable(true);
        }

and that works fine. Why can't I notify the observers inside the double for loop?

Violet_82 89 Posting Whiz in Training

HI guys, as I was playing with observers today I came across something interesting.
I have a program which keeps a list of users (Observers) and products (Observables) and the idea is that whenever the availability (that's a property of a product) changes the Observers are notified of this change. It all worked OK when there was 1 product with multiple users but now that I have multiple products things are falling apart and it seems I'm causing a memory leak somewhere - probably due to the fact thtat I'm not fully understanding the Observer pattern.
So when I try to print out the number of products per user (there should be only 3 product per user) the programs output the same product multiple times.
Let's have a look at the code and output:
Here is the product I'm observing:

//Product: this is the Observable
package observers;

import java.util.Observable;

public class Product extends Observable
{

    private boolean isAvailable = false;
    private String size = "";
    private String colour = "";
    private String name = "";

    public Product(boolean isAvailable, String size, String colour, String name)
    {
        this.name = name;
        this.isAvailable = isAvailable;
        this.size = size;
        this.colour = colour;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public boolean isAvailable()
    {
        return isAvailable;
    }
    public void setAvailable(boolean isAvailable)
    {
        this.isAvailable = isAvailable;
        //if(isAvailable()){
            setChanged();//set the flag to indicate that this observable has changed
            notifyObservers();//notify everyone
        //}
    }
    public String …
Violet_82 89 Posting Whiz in Training

Cool, thanks.

The only annoying thing in the Java API version is that Observable is a class so if you want to use it you can't extend any of your own classes (no multiple inheritance)

Yes I was actually wondering about this when I started witht he above code. However you can create, presumably, your own Observer interface with the methods you want to implement? But that should be independent from the java version used.

Violet_82 89 Posting Whiz in Training

hi guys, I've come across observers while working ona very very large project, and I didn't quite understand how they were structured and I suppose this had something to do with the huge size of the project itself.
Anyway, I then decided to delve a little more into that, I had a look in a few places, believe I understand more or less the theory and wrote some code - well in fact it's code that I got from a few places, play with it a little bit and then pretty much re wrote it again..
So, to my question now: could someone cast an eye on it and:
1)let me know if it makes sense (it works as expected
2)is that it? Does it, although very simplistically, represent the meaning and purpose of what the observer pattern is meant to be used for?
3)any suggestiong as to it can be improverd, expanded etc
The code is pretty simple, there is a bankAccount object - the Observable - and then I created a few Observers using a loop - the number is fixed to 7 in my example. The test class creates the Observable objects passing the Observable as a parameter to it, then it adds the observers to the list of observers and changes the Observable triggering the update method. that's it.
Here is the code:

//the observable
import java.util.Observable;

public class BankAccount extends Observable
{

    private int balance = 0;

    public …
Violet_82 89 Posting Whiz in Training

Ah OK I understand, thanks for th examples! Th orElse is actually rather useful!

Violet_82 89 Posting Whiz in Training

thanks so I made som changes, more or less what yo've suggested, however, what if I want to get some defalt values if the object is null?
Here is what the main class looks like now

package optional_test;
import java.util.Optional;

public class Optional_test {

    public static void main(String[] args) {
        Optional<Customer> customer1 = Optional.ofNullable(new Customer("John", "Doe"));
        Optional<Customer> customer2 = Optional.empty();
            /*if(customer1.isPresent()){
                System.out.println(customer1.orElse(new Customer("Unknown", "Unknown")));
            }*/
        customer1.ifPresent(value -> {
            System.out.println(value.toString());
        });
        /*if(customer2.isPresent()){
            System.out.println(customer2.orElse(new Customer("Unknown", "Unknown")));
        }*/
        customer2.ifPresent(value -> {
            System.out.println(value.toString());
        });     

    }

}

The output is now John doe only which is good but I'd like to get something as a default for when the object is null and it doesn't look like ifPresent allows me

Violet_82 89 Posting Whiz in Training

Hi guys, I'm playing around ith optionals a little, but I'm not surewhether this is the correct behavious as I'm getting a null pointer exeption (I thought the point of Optionals was not to get a null pointer.)
SO I'm setting an object to null and before calling toString on it I'm using isPresent() on it. Here is the code:

package optional_test;
import java.util.Optional;

public class Optional_test {

    public static void main(String[] args) {
        Optional<Customer> customer1 = Optional.ofNullable(new Customer("John", "Doe"));
        Optional<Customer> customer2 = null;
        if(customer1.isPresent()){
            System.out.println(customer1.get());
        }
        if(customer2.isPresent()){
            System.out.println(customer2.orElse(new Customer("Unknown", "Unknown")));
        }

    }

}

And the cCustomer class:

package optional_test;

import java.util.Optional;

public class Customer {
    private String name;
    private String surname;
    public Customer(String name, String surname) {
        this.name = name;
        this.surname = surname;
    }
    public Optional<String> getName() {
        return Optional.ofNullable(this.name);
    }
    public void setName(String name) {
        this.name = name;

    }
    public Optional<String> getSurname() {
        return Optional.ofNullable(this.surname);
    }
    public void setSurname(String surname) {
        this.surname = surname;
    }
    @Override
    public String toString(){
        return "Name: " + getName() + ". Surname: " + getSurname();
    }
}
Violet_82 89 Posting Whiz in Training

It will be running in a browser.
So, here are a few more details.
The application is essentially meant to allow users to input books (Title, author and a few more fields) using a form and when the form is submitted all that data go to a database (mySql).
Currently I have only the frontend part, done entirely in angularjs 2.
I've never really stored any application data in a database before, so I'm really not sure what approach to take.
I've done more readings since after this post, and it turns out that, as you're pointing out, I need another layer, something like a webservice that takes the data from my application - which is now in Json - and sends it to the database.
After that I will have to retrieve that data too, but one thing at the time, let's think about how to send it and store it to the database first.
If you want to have a look at some code it's all in here https://github.com/Antobbo/Books-Proj-last/tree/master/src/app, if you want some specific bits, please do let me know

Violet_82 89 Posting Whiz in Training

Hi guys, I'm fairly new to angularjs 2 (I've only used 2) and I have a small application with a form. Currently I'm able to get the form data as an objects and print it to the console.log,

onSubmit(form: any):void{
       console.log(form);
   }

producing this:

Object {author: "Author test", title: "Title test", location: "Location test", medium: "Medium test", notes: "Notes test"}

but what I want to do now is to push that data to a mysql database. I have no idea what needs to be done, so I'm doing a bit of reading here and there, but I have to say I didn't find that much useful info: often they do it in angularjs rather than angularjs 2, so I'm not sure that applies to me. So, generally speaking, what do I need? Do I need to convert the object to Json or is it good to go as it is? If you guys have any suggestions or links for me to read, then please fire away
cheers

Violet_82 89 Posting Whiz in Training

Right thanks guys, really good suggestions! I will try to work on the code of the organisation I work for, but I can't bring that at home with me unfortunately so it might be proving a little challenging, that's why I was thinking to get hold of some code from the net too :-)

Violet_82 89 Posting Whiz in Training

OK great, thanks for the advice. So in terms of practice is getting stuff from the internet (github) and modify it a good idea? Do you know any other resource where I could get some code and play with it?
thanks

Violet_82 89 Posting Whiz in Training

In any case, is it still worth me looking at the Java theory, as there are things that I haven't really touched upon, or just doing some practice (and if so what would be the best way to practice on medium/large application? Get a project off github and modify it?)

Violet_82 89 Posting Whiz in Training

that is a great idea, but I don't believe the organisation I work for has any...shame because it would be reallly helpful.

Violet_82 89 Posting Whiz in Training

Yes, I actually noticed that, in fact one of the applications I'm working at use MVC extensively, but it's just so hard to understand what's going on, and I kind of wondering whether practicing MVC would help me to understand that or whether I should focuss more on how classes interact with one another in large system, as I this in as area where I know I'm weak

Violet_82 89 Posting Whiz in Training

Thanks, that's helpful :-). Coding-wise, I reckon I'm having a few issues with the MVC model, I mean it's pretty clear what it does and how it works in theory but when you try to look at larger projects it's incredibly difficult to find out what's what. Same things for design patterns in general, it's all OK (well the few design patterns I looked at) when it's a small application but when it grows in size it's a nightmare

Violet_82 89 Posting Whiz in Training

Well, it's not just a roadblock to be honest, but for example, say there is a bug in the application and I need to address it, where do I start from? I know a lot is specific to the application of course, but is there any general principle that I can apply across every application?

Violet_82 89 Posting Whiz in Training

Hi guys,
I wonder if you can help me.
As I’m now doing java development as a profession now, I’ve realized that I’m a little weak when it comes to fix, modify and understand code within large applications, and, needless to say, I need to find a way to get better at it.
So, I was wondering if any experienced java developer could give me some advices and perhaps help me in getting a little better.
Of course I know the basics, I’ve studied the theory, I know how to create classes, instantiate them, using interfaces etc – although this is more theoretical knowledge than practical in all honesty – but I feel like I’m lacking ‘something’, perhaps just experience…

Violet_82 89 Posting Whiz in Training

Great, thanks for all the advice guys!

Violet_82 89 Posting Whiz in Training

well,first of all thanks for doing that. For me, really, either way ...generally speaking, it kind of makes sense to me to allow some flexibility and I guess allowing the view to access the model isn't such a bad thing...
Going back to the application, as things currently are, my view has some knowledge of the model because it's using the model's getters to get data out of it:

public void displayStudent(StudentModel studentModel){
            System.out.println("Student is: " + studentModel.getName() + " " + studentModel.getSurname() + "\n" + "Number: " + studentModel.getNumber());
        }

So, is that it then? Are we kind of happy with this?
At the end of the day the purpose of this os for me to understand some basic concepts like MVC :-)

jkon commented: Yes , that makes perfectly sense to me +9
Violet_82 89 Posting Whiz in Training

well, my perspective is that, generally speaking and more from the theory than experience an object, like the student in this case, should be aware of all its properties and methods, so, what @JamesCherrill says seems to me to be more logical. However, when I looked up the MVC model in java, I've found different approaches and I went for what I understood better, which is this one here http://www.tutorialspoint.com/design_pattern/mvc_pattern.htm, nice and simple and that's what I've based my original code on, and in this approach the model doesn't seem to have any methods in it. As what I'm learning is all about OO, then I shall prefere an OO approach.
If having a student factory helps with creating multiple students, then so be it, I will try to add it in. I'm simply taking it slowly as MVC is, for me, a new concept. So, where do we go from here?

Violet_82 89 Posting Whiz in Training

Right, let's see if I understand.
So, based on your suggestions, my view class now looks like this:

package view;

import model.StudentModel;

public class StudentView {       
    public void displayStudent(StudentModel studentModel){
            System.out.println("Student is: " + studentModel.getName() + " " + studentModel.getSurname() + "\n" + "Number: " + studentModel.getNumber());
        }
}

I pass a StudentModel reference to it and I get the individual fields from the model with getters.

For the model class itself, I've only added a constructor:

public StudentModel(String name, String surname, int number) {
        super();
        this.name = name;
        this.surname = surname;
        this.number = number;
    }

because I would have to create a StudentModel object from somewhere rather than from the StudentModel itself?
In the Controller class I'm not too sure... I've added a method called createStudent() which creates a new StudentModel object, and I'm also calling the method in the view, like so:

package controller;

import model.StudentModel;
import view.StudentView;

public class StudentController {
    StudentModel studentModel;
    StudentView studentView = new StudentView();
    public void createStudent(){
        studentModel = new StudentModel("John", "Smith", 34566);        
        studentView.displayStudent(studentModel); 
    }

}

Finally the StudentDemo for now has only a call to the createStudent method and the creation of the controller, like so:

import controller.StudentController;
import view.StudentView;

public class StudentDemo
{ 
    public static void main(String[] args)
    {
        StudentController studentController = new StudentController();
        studentController.createStudent();

    }    

}

Is that any better?
With these changes now I seem to be able to handle multiple students: if inside the controller I create another student, it gets outputted OK, for example …

Violet_82 89 Posting Whiz in Training

Hi guys,
as I'm looking into the MVC pattern, I thought I'd create a small application to understand a bit more.
Let's look at the code:

//model
package model;

public class StudentModel
{
    private String name;
    private String surname;
    private int number;    

    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getSurname()
    {
        return surname;
    }
    public void setSurname(String surname)
    {
        this.surname = surname;
    }
    public int getNumber()
    {
        return number;
    }
    public void setNumber(int number)
    {
        this.number = number;
    }

}

//controller
package controller;

import model.StudentModel;
import view.StudentView;

public class StudentController
{
    private StudentModel studentModel;
    private StudentView studentView;
    public StudentController(StudentModel studentModel, StudentView studentView)
    {
        super();
        this.studentModel = studentModel;
        this.studentView = studentView;
    }
}

//view
package view;

public class StudentView
{

    public void displayStudent(String name, String surname, int number){
        System.out.println("Student is: " + name + " " + surname + "\n" + "Number: " + number);
    }
}

//demo
import model.StudentModel;
import view.StudentView;
import controller.StudentController;

public class StudentDemo
{

    public static void main(String[] args)
    {
        StudentView studentView = new StudentView();
        StudentModel model = createStudent("John", "Smith", 34567);
        StudentController studentController = new StudentController(model, studentView );
        studentView.displayStudent(model.getName(), model.getSurname(), model.getNumber());

    }
    public static StudentModel createStudent(String name, String surname, int number){
        StudentModel studentModel = new StudentModel();
        studentModel.setName(name);
        studentModel.setSurname(surname);
        studentModel.setNumber(number);
        return studentModel;
    }

}

OK so, everything works OK, in the sense that I get printed what I expected. But then I run into a problem: what if I want to have multiple students? Does …

Violet_82 89 Posting Whiz in Training

Ah, and I have to add that the solution I described above doesn't work. To get it to work, I have to check if the zeroth element of the array has the topic already, and if not, to add it in. That works very well, but still intrigued as to whether I can implement the solution described above, in which I insert the stringified version of the topic object into the JSON string.

Violet_82 89 Posting Whiz in Training

Yes, apologies, copy and paste error, I meant to paste the version with stringify, I wouldn't stringify a string, lol!
Basically the application takes in a json string, then I need to turn that into an array of object literals because I need it to create abjects out of them. In the application I can add more objects and then, on demand (by clicking an Export button), I need to package all the objects inside a new json string for export. The user could the, if he wants, get the JSON string produced and use it in the application and create objects from it, it's a continuous process of parsing a string and stringify object literals.

I can't add the topic to the array. I will try to explain why. When I click on the Export button I get all the objects present in the application (they are stored in an array of literals) and convert them to JSON. So let's call this array myObject. Everytime I add a new object, this array gets update and the new object added to it. Now, when the Export button is called, Just before converting it to JSON I unshift the topic, as a new object, in it. No doubt you see the problem here: say that I press the button once to start with , everything is fine. But then I keep using the application again, I add a few objects in it, click the Export button again, and bang, now …

Violet_82 89 Posting Whiz in Training

Hi guys, I have a rather interesting problem. Basically my application has a javascript object literal in this format:

var myObject = '{text:"my text 1", anotherProperty1:"This is another property1", anotherProperty2:"This is another property2", anotherProperty3:"This is another property3"},' +
'{text:"my text 2", anotherProperty1:"This is another property1", anotherProperty2:"This is another property2", anotherProperty3:"This is another property3"},'+
'{text:"my text 3", anotherProperty1:"This is another property1", anotherProperty2:"This is another property2", anotherProperty3:"This is another property3"}';

At some point I stringify it

function exportString(){
    var jsonString = JSON.stringify(myObject);
    ...
}

and jsonString contains this as expected:

[
    {"text":"my text 1", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
    {"text":"my text 2", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
    {"text":"my text 3", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"}

]

And now the problem. After I stringify it I need to add another string to it, at the very beginning, so that I end up with something like this:

[
    {"Topic":"This is my topic"},
    {"text":"my text 1", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
    {"text":"my text 2", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"},
    {"text":"my text 3", "anotherProperty1":"This is another property1", "anotherProperty2":"This is another property2", "anotherProperty3":"This is another property3"}

]

The reason why I have to do it after I stringify, is pretty long, I will try to summarize it here: my myObject is itself a property of a bigger object, and it gets …

Violet_82 89 Posting Whiz in Training

HI thanks, I've spent a bit of time doing some reading, watching some videos on pluralsight and looking at a few tutorial, just to get an idea of what the whole thing is about. It's definitely interesting, but I suppose it's quite hard to choose which pattern to use, when to use it and what to use it for unless you've done this for years. In any case, while I totally appreciated what you said about using a design pattern with a 'small' program, the examples I've seen - presumably for demonstration purposes - used only a bunch of classes, and I suppose that was the idea I had in mind, like creating a small application just to understand the principles of a specific design pattern. I do understand now though, that it shouldn't be the application to determine the pattern to follow, but rather what it is that you want to achieve in the application that should dictate which design pattern to use. So, let's forget the remote controlled car application I proposed earlier on, what would you think would be a good, small (because the last thing I want is to work on something large for 6 months and then never finish it) application I could create? I tried to have a look online for "java projects for design patterns" but I didn't come up with anything useful. Perhaps I could - again -have a look at some kind of employee application, like creating several employees with all …

Violet_82 89 Posting Whiz in Training

Hi guys,
as I have never used any design pattern I thought I might try to learn something by developing a small application.
What I'm thinking is something like a radio controlled car simulation - I mean a really really simplified version of it of course - something like creating a car object, a remote controller object and verious methods to move forward, back, left and right (the methods can just output something to the console). Nothing too complicated.
So, first of all, do you think that it is a good idea? If not what should I do to improve it?
Would such an application allow me to use any design pattern, if so which one do you recommend (as mentioned I've never used any so I will have to look into that before develop the application).
If you think it's good, I'd start with some pseudocode, of course.
In general, any suggestion at all?

Violet_82 89 Posting Whiz in Training

Actually that Object.keys(jsonStringParsed)[0] isn't so good after all, because it returns the label as a string, which means that I can't use it in this fashion as I thought I would:
jsonString.Object.keys(jsonStringParsed)[0].xxxx, as it says that the keys is undefined...

EDIT: OK, I figured that out, strange syntax for me, it will now be jsonString[Object.keys(jsonStringParsed)[0]].xxxx

diafol commented: Great - you saved me a post :) +15
Violet_82 89 Posting Whiz in Training

yes that's a good point, I think I have a rough idea of how the structure is going to look like but I can't be 100% sure. As mentioned I don't have direct control over the json string generated, but only indirect, so I'd imagine we would then decide on some kind of standard, otherwise, as you said, how would I even know how to access the data in it?!

Violet_82 89 Posting Whiz in Training

Interesting. So technically I don't have to have the label in it, that's good. Still I don't really know whether when they produce the json string they will or not include the label. They are likely to export their data as a json string so I don't know whether the export will include a label or not, and I have no idea if there is a way to find out unfortunately or a way to control that, like to force it to include or not a label.
In any case I've just found a way to access the actual label of the json object so that I don't have to hardcoded it every time I want to access the object. Apparently I need to use this:
console.log("label: " + Object.keys(jsonStringParsed)[0]);
and that gives me 'details'.
I found this here just for reference: http://stackoverflow.com/questions/22565077/javascript-get-json-key-name

Violet_82 89 Posting Whiz in Training

the problem with the label is that I have to include it when accessing the objects, and i don't want that, I want direct access to the objects, that's why I was thinking to remove the label altogether. The reasons for that is that, when the json string is created - because it's created outside the application - I can't guarantee that the label is 'details' or whatever else, so I thought it'd be tricky to access the objects when you're not sure what the label is. For now I have hardcoded it, but that's not a good solution as the author can call it anything. You suggested

var data = jsonString.details;
var firstItemText = data[0]['text'];

but there is still the label in there, so I need to replace that jsonString.details find a way to get that 'details' programmatically and not hardcode it, but, alas, I couldn't find any. Is there any way to return just the label?