Page 1 of 2
1
2
LastLast
  1. #1
    High Overlord Zhaveros's Avatar
    10+ Year Old Account
    Join Date
    Jun 2011
    Location
    Vancouver Island, B.C. Canada
    Posts
    192

    Java question about multiple methods and classes

    So right now I've stopped learning new shit about java and I'm just practising what I already know. So the issue I'm having right now is I'm trying to set a value of a variable by using a method from another class. I'll give the code I have the works with strings in reverse.


    Main class:

    Code:
    import java.util.Scanner;
    import java.util.Random;
    
    public class Prac1 {					
    									    
    	public static void main(String[] args) {
    		Scanner YourName = new Scanner(System.in);
    		Prac2 pr = new Prac2();
    		
    		System.out.println("What is your name?");
    		
    		String temp = YourName.nextLine();
    		pr.setName(temp);
    		pr.saying();
    		
    		
    		
    		
    	}
    }
    Second class:
    Code:
    public class Prac2 {
    	
    	private String Name;
    	
    	public void setName(String name) {
    		Name = name;
    	}
    	public String getName() {
    		return Name;
    	}
    	public void saying() {
    		System.out.printf("Your name is %s", getName());
    	}
    	
    }
    Any advice would be appreciated.

    ---------- Post added 2012-10-03 at 07:17 PM ----------

    Ok, so I'm going to try and do it the same way as above. If it works, I will try and reverse it.

  2. #2
    It would help If you said what is happening. As someone that doesn't use Java very much, it looks like your problem might be that you aren't importing the file of your second class for the first class.

  3. #3
    High Overlord Zhaveros's Avatar
    10+ Year Old Account
    Join Date
    Jun 2011
    Location
    Vancouver Island, B.C. Canada
    Posts
    192
    The code above works. What I'm trying to do is get it to do that with integers. If I can get it to do that, I want to see if I can do it in reverse so my main class does it instead of my second class. I know this seems quite nooby but I am still learning.

    ---------- Post added 2012-10-03 at 07:27 PM ----------

    Ok, so I tried it like above using the relatively same code:
    int temp = YourName.nextLine();
    pr.setNm(temp);

    Problem is, is that I can't use temp the same way I did with the string because the code above doesn't like Int.
    Anyone know how to make this work?

  4. #4
    You need to keep in mind the datatype. for the scanner, nextLine() returns a string; if you want to read an integer you can use nextInt(). As far as "reversing" I'm not sure what you intend to do with each class.

  5. #5
    Mechagnome
    10+ Year Old Account
    Join Date
    Nov 2010
    Location
    Melbourne, Australia
    Posts
    626
    Java standards says you should use lower case variables. Obviously it's not breaking anything but it's a *very* good habit to get into.

    I'm not quite sure exactly what you're trying to do, but there's no real reason to have 2 classes to do that, just stick the main function into Prac2. I'm assuming that's what you mean by 'reversing' it?

  6. #6
    High Overlord Zhaveros's Avatar
    10+ Year Old Account
    Join Date
    Jun 2011
    Location
    Vancouver Island, B.C. Canada
    Posts
    192
    Ok, so in order to get some practice, I'm trying to create a small name data base using a switch statement. But before I do that, I'm trying to figure out how to use multiple classes better. I'm going to be using the same code as above(Modified to work with what I'm trying to do), but with a third class that contains the switch statement as well as the names. I know I could do this all in one code but as I said earlier; I'm just trying to practice using multiple classes.

    And thank you both for the advice so far.

  7. #7
    There are 2 ways to do it:

    Code:
    int a;
    Scanner scan = new Scanner(System.in);
    a = scan.nextInt();
    or

    Code:
    int a = 5;
    Scanner scan = new Scanner(System.in);
    a = new Integer(scan.nextLine());
    Use the 1st option. Second one works too but...I don't like it.

    Edit:

    Your setName(String name) is wrong.

    It should be:

    Code:
    public void setName(String name) {
             this.name = name; 
    }
    And rename your instance variable "Name" to "name".

    I'm not quite sure exactly what you're trying to do, but there's no real reason to have 2 classes to do that, just stick the main function into Prac2. I'm assuming that's what you mean by 'reversing' it?
    If he wants to do it in the right way, he needs 2 classes.

    By right way I mean Object-oriented programming (which is what you MUST do if you are using Java).

    Edit2:

    The way below won't let your user put a "g" (for example) in your int variable (which could throw the RuntimeException InputMismatchException):

    Code:
    int a = 5;
    while (true) {
          try {
                 Scanner scan = new Scanner(System.in);
                 a = scan.nextInt();
                 break;
                 } catch (InputMismatchException e) {
                    System.err.println("It has to be a number!");
                    continue;
                 }
            }
    The only way to get out of while is typing a number.
    Last edited by Thyranne; 2012-10-04 at 02:08 PM.

  8. #8
    Your other problems have been answered, so I guess I could ask this:

    Have you studied generics yet? Doing that will accomplish your goals using only one class (if you've done it right), and you could always create some container class (or hell, even an array will do) that holds however many records you want.

  9. #9
    High Overlord Zhaveros's Avatar
    10+ Year Old Account
    Join Date
    Jun 2011
    Location
    Vancouver Island, B.C. Canada
    Posts
    192
    Sorry for the late reply. Not sure if this is an illegal bump or not. So what I want to do is create a name data base. The only way to do so with my current knowledge is to make 3 classes. I want to make a RNG that will pick a name based on the number it generates. Now yes I know I can do this all in one class, but I'm trying to practice using multiple classes and seeing what I can do with them. So what I have to do:
    Make a class with a switch statement and a lot of names.
    Make it so I can have a RNG in my main class that will pick one of the names is display it in my main class.

    So in order to achieve this with my current knowledge(Still on beginner tutorials.) is to create a name string like so


    RNG will determine below
    Code:
    String nm;
    
    switch (nm) {
    case 0:
    nm = "You got the cool weapon you've been going for, for the last month!";
    break;
    case 1:
    nm = "Grats, my pally friend, we dropped some priest gear for you";
    break;
    default:
    System.out.println("No valid numbers");
    Forget if I put something here, will know when I actually use this code
    }


    ---------- Post added 2012-10-04 at 10:18 AM ----------

    So the code works, but how do I set the value of nm via RNG from my main class?

    ---------- Post added 2012-10-04 at 10:19 AM ----------

    Also, I haven't the slightest clue what generics are. I'm only beginning to dwell on arrays.

  10. #10
    I don't think you can use Switch-Case with Strings. Ints and Chars only.

    What you can do is create a 'database' class that handles names and text. You would also index classes via integer.

    Code:
    public class GameDatabase
    {
        // 1 = Mage
        // 2 = Warrior
        // 3 = Legolas
    
        String[] classNames = new String[3];
        String[] toasts = new String [2];
    
        GameDatabase()
        {
            classNames[0] = "Mage";
            classNames[1] = "Warrior";
            classNames[2] = "Legolas";
    
            toasts[0] = "Congratulations @@@@@@ on leveling up!";
            toasts[1] = "Grats, my @@@@@@ friend, some gear dropped for you!";
        }
    
        public String getClass(int classID)
        {
            return classNames[classID];
        }
    
        public String getToast(int toastID, int classID)
        {
            modifiedToast = //Some code that replaces the "@@@@@@" with the class name
            return modifiedToast;
        }
    }
    
    public class GameThread
    {
        public static void main(String[] args)
        {
            //Initialize Database
            GameDatabase gameDB = new ClassDatabase();
    
            System.out.println(getToast( 0; 1)); //Should print "Congratulations Mage on leveling up!"
        }
    }
    There are probably more optimal ways of managing this (eg. writing a database file and having the game thread parse it into an array when it starts up)

  11. #11
    High Overlord Zhaveros's Avatar
    10+ Year Old Account
    Join Date
    Jun 2011
    Location
    Vancouver Island, B.C. Canada
    Posts
    192
    The code you linked makes some sense to me but I'm not sure about some things like "String[] classNames = new String[3];", is it some type of String array or just a different type of String?

    ---------- Post added 2012-10-04 at 08:43 PM ----------

    So to simplify what I'm trying to do: I'm trying to learn how to create and manage databases. Like say I make a game. One part class contains the skills of one monster, another controls the players abilites. How would I do this? Don't forget, I'm a programming noob so don't make it complex, lol.

    Also bonus points for the answer. Is my main class pretty much the engine of Java programs?

  12. #12
    Deleted
    Quote Originally Posted by Zhaveros View Post
    The code you linked makes some sense to me but I'm not sure about some things like "String[] classNames = new String[3];", is it some type of String array or just a different type of String?[COLOR="red"]
    String Array. The number can of course be substituted for a variable (e.g. counter).
    Quote Originally Posted by Zhaveros View Post
    Also bonus points for the answer. Is my main class pretty much the engine of Java programs?
    The main method is simply where the execution starts (when you compile and opt to run the program). Main is present in other languages as well, with the same purpose.

  13. #13
    Quote Originally Posted by yurano View Post
    I don't think you can use Switch-Case with Strings. Ints and Chars only.
    As of Java 7 you can. Before 7 you could easily simulate it though, switching on an Enum class.

    Code:
    public enum Videogame
    {
    	SKYRIM
    	, OBLIVION
    	, MORROWIND
    	, YOUHADANERROR;
    	
    	public static Videogame getGame(String gameName)
    	{
    		try
    		{
    			return valueOf(gameName);
    		}
    		catch (Exception e)
    		{
    			return YOUHADANERROR;
    		}
    	}
    }
    
    //get gameName from somewhere
    
    switch (Videogame.valueof(Videogame.getGame(gameName))
    {
    	case SKYRIM:
    	//stuff
    	case OBLIVION:
    	//more stuff
    	case MORROWIND:
    	//even more stuff
    	default:
    	//you done messed up
    }
    Probably a null check you could throw in there, but that format should work for any "String switch" pre-7, which certainly has its uses (looking at you, Android). However any chance you can use Java 7, String switching is certainly way better.

    @Zhaveros

    Have you considered looking into a book on Java and Object-Oriented programming in general? Understanding snippets of code like that is a lot less cryptic when you get a good, basic understanding of how things work.

  14. #14
    Quote Originally Posted by yurano View Post
    I don't think you can use Switch-Case with Strings. Ints and Chars only.

    What you can do is create a 'database' class that handles names and text. You would also index classes via integer.

    There are probably more optimal ways of managing this (eg. writing a database file and having the game thread parse it into an array when it starts up)
    You can since Java 7.

    Quote Originally Posted by Zhaveros View Post
    Sorry for the late reply. Not sure if this is an illegal bump or not. So what I want to do is create a name data base. The only way to do so with my current knowledge is to make 3 classes. I want to make a RNG that will pick a name based on the number it generates. Now yes I know I can do this all in one class, but I'm trying to practice using multiple classes and seeing what I can do with them. So what I have to do:
    Make a class with a switch statement and a lot of names.
    Make it so I can have a RNG in my main class that will pick one of the names is display it in my main class.

    So in order to achieve this with my current knowledge(Still on beginner tutorials.) is to create a name string like so


    RNG will determine below
    Code:
    String nm;
    
    switch (nm) {
    case 0:
    nm = "You got the cool weapon you've been going for, for the last month!";
    break;
    case 1:
    nm = "Grats, my pally friend, we dropped some priest gear for you";
    break;
    default:
    System.out.println("No valid numbers");
    Forget if I put something here, will know when I actually use this code
    }


    ---------- Post added 2012-10-04 at 10:18 AM ----------

    So the code works, but how do I set the value of nm via RNG from my main class?

    ---------- Post added 2012-10-04 at 10:19 AM ----------

    Also, I haven't the slightest clue what generics are. I'm only beginning to dwell on arrays.
    If you want to generate random numbers, use the static method random() in the Math class.

    For example, a random number between 1 and 100:

    Code:
    System.out.println((int)(Math.random()*100));
    But you wanna do it using a database right?

    So, first you have to open a connection.

    I'll give you an example using Firebird (because this is the only database I have right now).

    YourConnection.java
    Code:
    public class YourConnection{
    
        public Connection getConnection() {
            Connection con = null;
            try {
                Class.forName("org.firebirdsql.jdbc.FBDriver");
                con = DriverManager
                        .getConnection(
                                "jdbc:firebirdsql:localhost:C:\\somewhere\\anotherplace\\yourdatabase.fdb", //change the C:\\somewhere\\anotherplace\\yourdatabase.fdb to the place where is your database
                                "SYSDBA", "masterkey"); //"SYSDBA" is the username, and "masterkey" is the password
            } catch (ClassNotFoundException | SQLException e) {
                System.out.println(e.printStackTrace());
            }
            return con;
        }
    }
    Game.java
    Code:
    public class Game {
    
        private int id;
        private String name;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    }
    ClassThatWillTakeTheGame.java
    Code:
    public class ClassThatWillTakeTheGame { // sorry for the big name
    
        public Game getGame(int id) throws SQLException {
            Connection connection = new YourConnection().getConnection(); // we got the
                                                                        // connection
            PreparedStatement stmt = null; // created the Statement. ALWAYS use
                                            // PreparedStatement, never Statement
            ResultSet rs = null; // The ResultSet. Both stmt and rs have to be null
                                    // in this part
            String sql = "SELECT name FROM game WHERE id = ?";
            Game game = null;
            try {
                stmt = connection.prepareStatement(sql); // we already sent the sql
                                                            // to the database but
                                                            // we still have one
                                                            // thing to change: the
                                                            // "?". If your SQL is
                                                            // wrong or if the table
                                                            // doesnt exist, it'll
                                                            // throw a SQL exception
                stmt.setInt(1, id); // replaced the "?" with the variable id
                rs = stmt.executeQuery(); // now we execute the query and rs will
                                            // receive the resultset
                if (rs.next()) { // since we are expecting only 1 thing, we use if,
                                    // if we are expecting more than one then we use
                                    // while. If in this case, rs.next() returns
                                    // false it means that nothing was found
                    game = new Game();
                    game.setId(id);
                    game.setName(rs.getString("name")); // here we set the name of
                                                        // the game. We used
                                                        // rs.getString("yourColumnName")
                                                        // to get the value of the
                                                        // column.
                }
    
            } catch (SQLException e) {
                // do w/e what you want here
            } finally { // this part is important. finally will always run, doesn't
                        // matter if your try threw a SQLException, it'll always
                        // execute we have to check if rs is not null, if it's not
                        // null then we close it. Same for stmt and connection.
                        // Remember, close everything that you open (in this case,
                        // ResultSet, PreparedStatement and Connection) and always
                        // in this order
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
                if (connection != null) {
                    connection.close();
                }
            }
            return game;
        }
    }
    Main.java
    Code:
    public class Main {
        public static void main(String[] args) throws SQLException {
            Game game = new Game();
            ClassThatWillTakeTheGame iDontKnow = new ClassThatWillTakeTheGame();
            int gamesInDataBase = 5; // change it to w/e you want
            game = iDontKnow.getGame((int) (Math.random() * gamesInDataBase));
            if (game == null) {
                System.out.println("Ops, no game was found");
            } else {
                System.out.println(new StringBuilder()
                        .append("The RNG number was ").append(game.getId())
                        .append(" and the game that was found with that ID was ")
                        .append(game.getName()));
            }
        }
    }
    I didn't test it but I'm sure it'll work.

    Edit:

    Firebird driver:

    http://www.firebirdsql.org/en/jdbc-driver/

    Firebird:

    http://www.firebirdsql.org/en/firebird-2-5-1/
    Last edited by Thyranne; 2012-10-05 at 12:20 PM.

  15. #15
    Epic! Wayne25uk's Avatar
    10+ Year Old Account
    Join Date
    Feb 2012
    Location
    Maltby,Rotherham
    Posts
    1,738
    If you want to learn how to code in Java and other languages try this nifty website i use daily.

    www.codecademy.com

    Maybe to the OP try your question there i know there is a lot of experts that would explain your problem to you.

  16. #16
    High Overlord Zhaveros's Avatar
    10+ Year Old Account
    Join Date
    Jun 2011
    Location
    Vancouver Island, B.C. Canada
    Posts
    192
    Alright thank you all for the suggestions. Creating a database is a lot more complex than I thought, lol. So the responses gave me more questions than answers. I understand a majority of the code though. So any suggestions to a good for Java and object oriented programming? And perhaps a dumbed down definition of object oriented programming.

  17. #17
    Quote Originally Posted by Zhaveros View Post
    Alright thank you all for the suggestions. Creating a database is a lot more complex than I thought, lol. So the responses gave me more questions than answers. I understand a majority of the code though. So any suggestions to a good for Java and object oriented programming? And perhaps a dumbed down definition of object oriented programming.
    Sorry, I didn't understand the bolded part.

  18. #18
    High Overlord Zhaveros's Avatar
    10+ Year Old Account
    Join Date
    Jun 2011
    Location
    Vancouver Island, B.C. Canada
    Posts
    192
    Quote Originally Posted by Thyranne View Post
    Sorry, I didn't understand the bolded part.
    I think I just fucked up on writing that sentence. I didn't pay much attention to what I wrote but I believe I was asking for a good Java and Java object oriented programming book.

  19. #19
    Quote Originally Posted by Zhaveros View Post
    I think I just fucked up on writing that sentence. I didn't pay much attention to what I wrote but I believe I was asking for a good Java and Java object oriented programming book.
    Hmmm...there is a book called Java Head First (something like that). I've never read it but many people say it's a good book.

  20. #20
    Quote Originally Posted by Thyranne View Post
    Hmmm...there is a book called Java Head First (something like that). I've never read it but many people say it's a good book.
    Hitting up something like Data Structures and Algorithm Analysis (Mark Allen Weiss) would be my suggested route, simply because of the extremely high quality of sample code it provides. However it assumes there's some hurdles someone has already jumped before getting into its (rather dense) content.

    I've read some of Head First Java, and although it's alright there's some seriously stupid stuff they do, often unintentionally obfuscating some things because the authors wanted to be hip and funny.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •