Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 6 of 6

Thread: adding main method to a code

  1. #1
    Junior Member
    Join Date
    Jul 2009
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default adding main method to a code

    import java.util.Random;
     
    public class test {
     
    	 public int produceNumber()
    	    {
     
    	        Select = (s.nextInt(sList.length));
     
    	        return Select;
    	    }
     
    public static void main(String[] args){
        String[] sList = { "item 1", "item 2", "item 3", "item 4"};
     
        Random s = new Random();
        int Select = 0
     
        String list = sList[produceNumber()];
     
    }
    }

    hello, i need help adding a main method to a pre made code. I have no idea where to put public static void main and get the code to work. I know i don't have a good understanding of structure and class so please explain if you can help me.

    thanks


  2. #2
    Member Fendaril's Avatar
    Join Date
    Nov 2008
    Posts
    54
    Thanks
    7
    Thanked 6 Times in 5 Posts

    Default Re: adding main method to a code

    Quote Originally Posted by IDK12 View Post
    import java.util.Random;
     
    public class test {
     
    	 public int produceNumber()
    	    {
     
    	        int Select = (s.nextInt(sList.length));
     
    	        return Select;
    	    }
     
    public static void main(String[] args){
        String[] sList = { "item 1", "item 2", "item 3", "item 4"};
     
        Random s = new Random();
        int Select = 0;
     
        String list = sList[produceNumber()];
     
    }
    }

    hello, i need help adding a main method to a pre made code. I have no idea where to put public static void main and get the code to work. I know i don't have a good understanding of structure and class so please explain if you can help me.

    thanks
    There are a few errors in your code. First is in your produceNumber() method. Select has no type. From the looks of it you may want to define select as an integer before returning it inside the method. Also your second definition in your main invocation leaves out a semi-colon. I try to fix the code for you.

    Can you also explain what you are trying to do in your code. I can't seem to figure out your logic just by looking at it.
    Last edited by Fendaril; August 30th, 2009 at 09:44 PM.

  3. #3
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: adding main method to a code

    It looks like you're having variable scope issues.

    You declared and initialized Random s= new Random() in your main method, but used it inside the produceNumber() method.

    Here's a brief tutorial on scope:

    Pretend your computer was a person working on a piece of paper. They can write stuff to that paper, erase stuff, and move stuff around. When you call a method, imagine that the person got a new piece of paper. Everything on the other sheets of paper are effectively out of scope. This means on this new piece of paper, it won't know that Random s even existed.

    You can pass variables/objects to the method via arguments. This can be visualized by copying the variables/objects onto the new sheet of paper before setting the original aside. Again, everything on that original piece of paper is invisible to the current piece of paper being worked on. It's a little more complicated than that when you start dealing with passing by reference or by value, but not by too much.

    When your method returns, this is analogous to throwing away the paper for that method and resuming work on the original paper. If your method returns a value, that value is copied back onto the main paper, but once the method ends, anything on it's paper is effectively gone (especially true with Java's garbage collector).

    So, let's modify your original code:
    import java.util.Random;
     
    public class test {
     
    	 public int produceNumber(int maxNum)
    	    {
    	       Random s = new Random();
    	        int Select = (maxNum);
     
    	        return Select;
    	    }
     
    public static void main(String[] args){
        String[] sList = { "item 1", "item 2", "item 3", "item 4"};
     
        int Select = 0;
     
        String list = sList[produceNumber(sList.length)];
     
    }
    }

    As a side note:

    The produceNumber method in this example is basically dead weight. It's encapsulating a function held within Random, which is not useful. I'd also recommend that you capitalize the first letter of class names. So the final product would be:
    import java.util.Random;
    public class Test
    {
    public static void main(String[] args){
        String[] sList = { "item 1", "item 2", "item 3", "item 4"};
     
        int Select = 0;
       Random s = new Random();
        String list = sList[s.nextInt(sList.length)];
     
    }
    }
    Last edited by helloworld922; August 30th, 2009 at 11:34 PM.

  4. #4
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: adding main method to a code

    If you want to call a method from the static main, you might also want to consider either making that method static as well or instantiating the class first.

    // Json

  5. #5
    Junior Member
    Join Date
    Jul 2009
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: adding main method to a code

    Quote Originally Posted by helloworld922 View Post
    It looks like you're having variable scope issues.

    You declared and initialized Random s= new Random() in your main method, but used it inside the produceNumber() method.

    Here's a brief tutorial on scope:

    Pretend your computer was a person working on a piece of paper. They can write stuff to that paper, erase stuff, and move stuff around. When you call a method, imagine that the person got a new piece of paper. Everything on the other sheets of paper are effectively out of scope. This means on this new piece of paper, it won't know that Random s even existed.

    You can pass variables/objects to the method via arguments. This can be visualized by copying the variables/objects onto the new sheet of paper before setting the original aside. Again, everything on that original piece of paper is invisible to the current piece of paper being worked on. It's a little more complicated than that when you start dealing with passing by reference or by value, but not by too much.

    When your method returns, this is analogous to throwing away the paper for that method and resuming work on the original paper. If your method returns a value, that value is copied back onto the main paper, but once the method ends, anything on it's paper is effectively gone (especially true with Java's garbage collector).

    So, let's modify your original code:
    import java.util.Random;
     
    public class test {
     
    	 public int produceNumber(int maxNum)
    	    {
    	       Random s = new Random();
    	        int Select = (maxNum);
     
    	        return Select;
    	    }
     
    public static void main(String[] args){
        String[] sList = { "item 1", "item 2", "item 3", "item 4"};
     
        int Select = 0;
     
        String list = sList[produceNumber(sList.length)];
     
    }
    }

    As a side note:

    The produceNumber method in this example is basically dead weight. It's encapsulating a function held within Random, which is not useful. I'd also recommend that you capitalize the first letter of class names. So the final product would be:
    import java.util.Random;
    public class Test
    {
    public static void main(String[] args){
        String[] sList = { "item 1", "item 2", "item 3", "item 4"};
     
        int Select = 0;
       Random s = new Random();
        String list = sList[s.nextInt(sList.length)];
     
    }
    }

    Can you explain for me what encapsulating mean. And why shoudn't i use that producenumber method. Isn't the whole point of orient programming language all about, to have different methods and classes?

  6. #6
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: adding main method to a code

    Encapsulation is restricting outside access to your object's fields (and even some methods) directly via other methods. Here's a simple example:

    say you wanted a class that represented fractions. You would have 2 variables, one for the numerator and one for the denominator. It would be silly to allow someone to set the denominator to zero since that wouldn't be a good fraction. The only way to do this is via encapsulation. If you define the denominator field public, outside sources can access/modify it however they want. If you set it private/protected, outside sources can't access/modify it at all. However, internal sources still have access (and in the case of protected, so do inheriting classes).

    So let's create our encapsulated fraction:
    public class Fraction
    {
         private int n, d;
         public Fraction(int numerator, int denominator)
         {
              // numerator can be anything
              this.n = numerator;
              // don't allow denominator to be 0
              this.setDenominator(denominator);
         }
     
         public void setDenominator(int denominator)
         {
              if (denominator != 0)
                   this.d = denominator;
              else
                   throw new RuntimeException();
         }
     
         public int getDenominator()
         {
              return d;
         }
     
         public void setNumerator(int numerator)
         {
              this.n = numerator;
         }
     
         public int getNumerator()
         {
              return n;
         }
     
         public double computeDecimal()
         {
              return (double)n/d;
         }
    }

    Yes, the point of OOP is to spread out the task, but at a certain point your methods should do something (sometimes a lot of things).

    It isn't necessary for you to create your own method, as in this case where you're trying to encapsulate the Random class in it's entirety. Kind of unnecessary, since someone has already encapsulated Random in it's entirety (it's called the Random class). It may be useful to encapsulate if you wanted to restrict access to certain parts of the Random class, but that is not the case here.

    Also, encapsulation is generally only used when you have multiple classes. It's impossible to restrict internally access to any of the fields. It's also impossible to restrict access between objects of the same type (including the static instance). So, this is perfectly legal:
    public class Cheater
    {
         private int myNum;
         public Cheater(int i)
         {
              myNum = i;
         }
     
         public static int cheat(Cheater other)
         {
              return other.myNum;
         }
    }
    import java.util.Scanner;
    public class GuessingGame
    {
         public static void main(String[] args)
         {
              System.out.println("A: Let's play a  guessing game!");
              Cheater a;
              a = new Cheater((int)Math.Random()*100);
              System.out.println("B: I'm going to tell you A's number. It's: " + Cheater.cheat(a));
              System.out.println("A: Guess a number 0-100: ");
              if (new Scanner(System.in).nextInt() == Cheater.cheat(a))
              {
                   System.out.println("A: How'd you know?");
              }
              else
              {
                   System.out.println("A: Ha, you're wrong");
              }
         }
    }

Similar Threads

  1. Java program to do Matrix operation
    By saladfingers73 in forum Collections and Generics
    Replies: 5
    Last Post: March 7th, 2012, 09:17 AM
  2. Replies: 16
    Last Post: August 27th, 2010, 03:30 PM
  3. adding get mothods to a class extending thread
    By aliaa2a in forum Object Oriented Programming
    Replies: 6
    Last Post: August 3rd, 2009, 06:41 AM
  4. Replies: 9
    Last Post: June 27th, 2009, 04:05 PM
  5. adding rows to coloumns. Netbeans
    By haygaurav in forum Java IDEs
    Replies: 1
    Last Post: April 1st, 2009, 03:16 PM