• Forum
  • Lounge
  • -JAVA-Im trying to dynamically create ob

 
-JAVA-Im trying to dynamically create objects and then slap them on array list

Pages: 123
Only i cant find a tutorial on it,

Now i could ask in a java forum but you will find, just like i did, that no one can make a coherent forum for java that makes sense is well written and easy to use!

What I wanted to do is have an object that had a member function that i could store any amount of strings on, it also has a name in which i could refer to that list with.

so i would have a cuisine object, it would have its title and recipie.

so in the main menu i could add a title followed by the recipe, this object would be stored on a list, i could also enter the name of the recipe and get said list.

This is the ugly monster I created, this is my first java program please font laugh at my spelling it hurts deep, way down in my soul.

Oh yeah and i know its fundementally flawed


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.*;

public class meals extends recipie {
    static int clue = 0;
    ArrayList<recipie> objlist = new ArrayList<recipie>();
    recipie Robj = new recipie();
    ListIterator objitr = objlist.listIterator();
    Scanner input = new Scanner(System.in);


    public void addobject() {//this is all wrong i know, here is where
        Robj.setname();      //i wanted to add new objects on
        Robj.addrecipie();   //i was hoping i could use some sort of
        objlist.add(Robj);   //static variable in order to move objlist
    }            //ahead by one before add object is called again, just how??


        try {

            int num = 0;

            while (!compare.equals(temp)) {   //im not sure exactly whats wrong
                System.out.printf("%s", clue);  //here, i know it runs past the
                recipie obj1 = (recipie) objlist.get(num); //array and...boom
                num++;
                compare = obj1.getname();

            }
            System.out.printf("the recipe for %s is", objlist.get(num).getname());
            objlist.get(num).printrecipie();

        } catch (Exception e) {

            System.out.printf("nah we don't have that, or ... %s", e);

        }
    }
}


I call it all wierdly in main too

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class panel {

    public static void main(String[] args) {
meals numeal = new meals();
        boolean flag = true;
        while (flag) {
            System.out.println("do you wnt to 1 add a recipie or two get one or 3 quit?");
            Scanner option = new Scanner(System.in);
            int num = option.nextInt();


            switch (num) {
                case 1: {
                    
                    numeal.addobject();
                    break;
                }
                case 2: {
                    
                    System.out.println("enter the meal you are after");
                    String temp;
                    temp = option.next();
                    numeal.getobjrecipie(temp);
                }
                case 3:
                    flag = false;
                    break;

            }


        }

    }


}


lastly im sure this class is fine and is basic stuff, im just putting it here cos i know you guys can still find things in it that i could do better...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.*;

public class recipie {

    ArrayList<String> item = new ArrayList<String>();
    String temp, name;
    int number = 0;
    Scanner input = new Scanner(System.in);

    public void setname() {
        String x;
        System.out.printf("whats the meal called");
        x = input.next();
        x = name;
    }

    public String getname() {
        return name;
    }

    public void addrecipie() {
        System.out.printf("enter 5 things:");
        while (number < 5) {
            item.add(input.next());
            number++;


        }
    }


    public void printrecipie() {

        for (String x : item) {
            System.out.println(x);

        }
    }

}
Last edited on
closed account (3hM2Nwbp)
devonrevenge wrote:

What I wanted to do is have an object that had a member function that i could store any amount of strings on, it also has a name in which i could refer to that list with.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;

public class Driver
{
  private final Map<String, List<String>> container =
    new HashMap<String, List<String>>();

  public void addToList(String name, String value)
  {
    if(!container.contains(name))
    {
      container.put(name, new ArrayList<String>());
    }
    container.get(name).add(value);
  }

  List<String> getStrings(String name)
  {
    return container.get(name);
  }

  public static void main(String[] yearrghs)
  {
    Driver test = new Driver();
    test.addToList("test1", "test value 1");
    test.addToList("test1", "test value 1_2");
    test.addToList("test2", "test value 2");

    /*
    container
     -test1
       -test value 1
       -test value 1_2
      -test2
       -test value 2
    */    

    for(String s : test.getStrings("test1"))
    {
      System.out.println(s);
    }
  }
}


* Should note that I didn't compile it.
Last edited on
@Luc Lieber: I just want to thank you so much for putting braces on their own lines.
closed account (3hM2Nwbp)
I do that intentionally to piss off Java-noids.

:D

*yearrghs!
I do that intentionally to piss off Java-noids.


I think all Java users should convert to C# and then Java could seize to exist. ;-)
Heh, I'm currently writing some code for a class that uses Java, and the book and the professor both put braces on the same line as the initiating statement but ain't nobody got time for dat. Braces on their own line for life!

Wow, never knew anyone to be so anal about brace location. I always do it on their own line, but that is because that is how I prefer to do it. I've seen guys that do C++ and do int main(){ or datatype functionname(params){ in their code. It is the programmer's preference, just like a guy could be annoying and put his entire program on just one line of code.
closed account (3hM2Nwbp)
BHXSpecter wrote:
It is the programmer's preference


Afraid not. (with Java)

http://www.oracle.com/technetwork/java/codeconv-138413.html

Failing to follow the Sun (now Oracle) bible will get you instantaneously labeled as a heretic.


Aaaanyhow...

@devonrevenge -- any questions?
Last edited on
1
2
3
4
5
public void addobject() {//this is all wrong i know, here is where
   Robj.setname();      //i wanted to add new objects on
   Robj.addrecipie();   //i was hoping i could use some sort of
   objlist.add(Robj);   //static variable in order to move objlist
}            //ahead by one before add object is called again, just how?? 


Can't you just do the following?

1
2
3
4
5
6
7
8
public void addobject() {
   recipie recipieToAdd = new recipie();

   recipieToAdd.setname();
   recipieToAdd.addrecipie();

   objlist.add(recipieToAdd);
}


1
2
3
4
5
6
7
8
int num = 0;

while (!compare.equals(temp)) {   //im not sure exactly whats wrong
   System.out.printf("%s", clue);  //here, i know it runs past the
   recipie obj1 = (recipie) objlist.get(num); //array and...boom
   num++;
   compare = obj1.getname();
}


Like the poster on StackOverflow said, you're not keeping track of the index with respect to the size of objlist. You could use the Java for each loop to not have to keep track of the current index. Here is how I would do it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
recipie foundRecipie = null;

for(recipie checkRecipie : objlist)
{
   if(checkRecipie.getname().equals(compare))
   {
       foundRecipie = checkRecipie;
       break;
   }
}

if(foundRecipie != null)
{
   //found the recipie
}
Last edited on
Luc Lieber wrote:
Afraid not. (with Java)

http://www.oracle.com/technetwork/java/codeconv-138413.html

Failing to follow the Sun (now Oracle) bible will get you instantaneously labeled as a heretic.


I've been labeled and called worse than a heretic. For example, all my Java code for my first few apps are similar to this:
1
2
3
4
5
6
7
public class hello
{
	public static void main(String args[])
	{
		System.out.println("Hello World");
	}
}

[edit] mismatched code tags with quote tags
Last edited on by closed account z6A9GNh0
The only thing wrong with that is your placement of the [] for args. It's valid syntax, but it doesn't quite look right...
L B wrote:
The only thing wrong with that is your placement of the [] for args. It's valid syntax, but it doesn't quite look right...

Yeah, I should have copy and pasted it. I typed it by hand and just did args[] out of habit (thinking of the C++ argv[]), but the file is String[] args like it is supposed to be.

Though, it compiles with both forms as I just foud out :-/, figured it would have sent a error or something.
Last edited on by closed account z6A9GNh0

Afraid not. (with Java)

http://www.oracle.com/technetwork/java/codeconv-138413.html

Failing to follow the Sun (now Oracle) bible will get you instantaneously labeled as a heretic.


Guess what. We put braces on their own lines. I don't like it, but this is the standard that runs in our 99% Java / 1% C++ codebase. I guess this is because the initial coders who started the project were C++ and PHP coders that just switched to Java. We still have some code remaining from that times and it is terrible (still finding lots bugs in that old code after a few years) but no-one is courageous enough to rewrite it properly. :P

The most important thing is to keep it consistent. And Sun/Oracle did a lot of good work there - at least most of Java code out there places opening brace on the same line and uses 4-char indentation. Much better than many projects in other languages where everybody wanted to invent their own style of indentation, spacing, basic structures as lists strings... (Qt - I'm pointing my finger at you).

As for the original poster's code:

1. avoid static variables; really try to write your code without static at all - believe me, it is possible to write any code with one and only single static in main; I'm sure that decision alone will make your code immediately much, much better (you should avoid static in C++, too).

2. Name classes from capital letter. Code is to be read by programmers and all programmers expect Java classes names to be capitalized (the same applies for braces - if you write C++ code, you can do as you wish, because there is no official convention/code style standard).
Last edited on
cool thanks no questions cos im still too nooby to know better, its good to know the correct way its done AND the correct way of doing what i was doing,
i did look at c# first, it is easier to learn and more intuitive its also exactly the same!!

I heard fortran was different but forget that...for now.

EDIT: YOU GOT TO FOLLOW CONVENTIONS!? Thats not a healthy state of mind for creative types, in the long run understanding a code you know lets say english, written lets say in verse rather than in a yorkshire accent is only going to help you speak better more beautiful english
Last edited on
if you want to piss off everyone on the team, yep, write in creative code style.

You can have creative code that follows formatting convention. The formatting has no effect on the actual code you write.
You can use an IDE that formats your code the way to like and then just change the formatting, have your IDE autoreformat it, and then push a commit with the proper formatting, then set your IDE back to your preferred formatting.
thanks shaktar that was where i was coming from cool.
closed account (o1vk4iN6)
So much for individuality when it comes to programming in Java. I agree that a single project should follow a convention but as per a language I'm surprised Java doesn't throw errors if the source doesn't follow the naming convention.
so what have i done wrong here?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public void getobjrecipie(String compare) 
    {
         try {
             for (recipie recipes: objlist)
              {

               if (recipes.getname().equals(compare))
               {
                   recipes.printrecipie();
                   break;
               }

              }
             }
         catch (Exception e) 
         {
          System.out.printf("nah we don't have that, or ... %s", e);
         }
    }
Pages: 123