# Java Thread



## Cromewell

Please post any questions relating to Java here. Please also specify which external libraries, if any, you are using.

You can also use this thread to post code you wish to share.


----------



## salvage-this

Thanks for posting this up Cromewell!  

I figure that I'll start it off by sharing a game I made for one of my labs last semester.  

To get it to work.  Create 3 classes in a Java IDE.  Game, Player and Pile.  Copy the corresponding code into each class.  Compile and create a game off of the Game Class.  

I tested it for general bugs.  If you find any more feel free to let me know.

Enjoy!


Game Class:


		Code:
	

import java.util.Scanner;
import java.util.Random;
/**
 * Class Game starts and plays the game of Nim
 * 
 * @author Salvage-This
 * @version 1.0
 */
public class Game
{
    Scanner scan = new Scanner(System.in);
    String gameType;
    Player player1 = new Player();
    Player player2 = new Player();
    Pile gamePile = new Pile();
    int move;
    int nextTurn;
    String playAgain;
    public Random rand;
    
    /**
     * Constructor for objects of class Game
     */
    public Game()
    {
        rand = new Random();
        System.out.println("Welcome to the game of Nim!\n");
        System.out.println("Take between 1 and half of the marbles in the pile.\n");
        System.out.println("The player stuck with the last marble loses.\n");
        setup();
        play();
    }
 
    /**
     * Setup method -  sets up the game type and the players
     * 
     * @param  none
     * @return void 
     */
    public void setup()
    {
        System.out.println("Would you like to play against the computer <C>?\n");
        System.out.println("Would you like to play against another person <P>?\n");
        System.out.println("Would you like to see an automated game <A>?\n");
        String gameType = scan.nextLine();
        if(gameType.contains("c") || gameType.contains("C"))
        {
            hvcSetup();
        }
        else if(gameType.contains("p") || gameType.contains("P"))
        {
            hvhSetup();
        }
        else if(gameType.contains("a") || gameType.contains("A"))
        {
            cvcSetup();
        }
        else
        {
            System.out.println("Invalid Choice!\n");
            setup();
        }
    }   
    
    /**
     * method human vs. computer setup- sets the players for human vs. computer
     * 
     * @param  none
     * @return void
     */
    public void hvcSetup()
    {
        //calls a setup for one human and one computer
        player1.humanSetup();
        player2.computerSetup();
        nextTurn = rand.nextInt(2);
    }
    
    /**
     * method human vs. human setup- sets the players for human vs. human
     * 
     * @param  none
     * @return void
     */
    public void hvhSetup()
    {
        //calls a setup for two human players
        player1.humanSetup();
        player2.humanSetup();
        nextTurn = rand.nextInt(2);
    }
    
    /**
     * method computer vs. computer setup- sets the players for computer vs. computer
     * 
     * @param  none
     * @return void
     */
    public void cvcSetup()
    {
        //calls a setup for two computer players
        player1.computerSetup();
        player2.computerSetup();
        nextTurn = rand.nextInt(2);
    }
    
    /**
     * Method Play- calls take turn and determins the end fo the game 
     * 
     * @param  none
     * @return void
     */
    public void play()
    {
        boolean gameOver = false;
        while(gameOver == false)
        {
            System.out.println("The Pile has " + Pile.numberRemaining + " marbles.\n");
            switch(nextTurn)
            {
                case 0:
                move = player1.takeTurn();
                Pile.numberRemaining = Pile.numberRemaining - move;
                System.out.println(player1.playerName + " has removed " + 
                move + " marbles.\n");
                if(Pile.numberRemaining == 1)
                {
                    System.out.println(player2.playerName + " loses!\n");
                    gameOver = true;
                    rematch();
                }
                else
                {
                    nextTurn = 1;
                }
                break;
                
                case 1:
                move = player2.takeTurn();
                Pile.numberRemaining = Pile.numberRemaining - move;
                System.out.println(player2.playerName + " has removed " + 
                move + " marbles.\n");
                if(Pile.numberRemaining == 1)
                {
                    System.out.println(player1.playerName + " loses!\n");
                    gameOver = true;
                    rematch();
                }
                else
                {
                    nextTurn = 0;
                }
                break;
            }
        }
    }
    
    /**
     * method rematch- checks if the player wants a rematch
     * 
     * @param  none
     * @return void
     */
     public void rematch()
     {
        System.out.println("Would you like to play again? <Yes> or <No>");
        playAgain = scan.nextLine();
        if(playAgain.contains("y") || playAgain.contains("Y") || 
        playAgain.contains("yes") || playAgain.contains("Yes"))
        {
            new Game();
        }
        else if(playAgain.contains("n") || playAgain.contains("N") || 
        playAgain.contains("no") || playAgain.contains("No"))
        {
            System.out.println("Thanks for playing!");
        }  
    } 
}


Player Class:


		Code:
	

import java.util.Scanner;
import java.util.Random;
/**
 * Class Player sets up the players
 *  
 * @author Salvage-This
 * @version 1.0
 */
public class Player
{
    private int x;
    String playerName;
    Scanner scan = new Scanner(System.in);
    public Random rand;
    public int familyRand;
    int playerType;
    int counter;
    int move;
    boolean isSmart;
    int smartSet;
    int inPileNow;
    boolean doneNow = false;
    int exponent = 6;
    boolean isHuman;
    
    
    /**
     * Constructor for objects of class Player
     */
    public Player()
    {
        rand = new Random();
    }

    /**
     * method getName
     * 
     * @param  none
     * @return string name
     * 
     */
    public String getName()
    {
        return playerName;
    }
    
    /**
     * method humanSetup
     * 
     * @param  none
     * @return void
     */
    public void humanSetup()
    {
          System.out.println("Please enter your name > ");
          playerName  = scan.nextLine();
          isHuman = true;
    }
    
    /**
     * method computerSetup- calls whoAmI() to determine computer player profile
     * 
     * @param  none
     * @return void
     */
    public void computerSetup()
    {
        whoAmI();
    }

    /**
     * method setName- sets string name to player name
     * 
     * @param  String Name
     * @return void
     */
    public void setName(String Name)
    {
        playerName = Name;
    }
    
    /**
     * method whoAmI- chooses the computer profile that will be selected for the game
     * 
     * @param  none
     * @return void
     */
    public void whoAmI()
    {
        //0 = Brian
        //1 = Meg
        //2 = Stewie
        //3 = Chris
        familyRand = rand.nextInt(4);
        switch(familyRand)
        {
            case 0:
                playerName = "Brian";
                isSmart = true;
                counter = 0;
                isHuman = false;
                break;
                
            case 1:
                playerName = "Meg";
                smartSet = rand.nextInt(2);
                switch(smartSet)
                {
                    case 0:
                        isSmart = true;
                        break;
                    
                    case 1:
                        isSmart = false;
                        break;
                }
                counter = 0;
                isHuman = false;
                break;
                
            case 2:
                playerName = "Stewie";
                smartSet = rand.nextInt(2);
                switch(smartSet)
                {
                    case 0:
                        isSmart = true;
                        break;
                    
                    case 1:
                        isSmart = false;
                        break;
                }
                counter = 0;
                isHuman = false;
                break;
                
            case 3:
                playerName = "Chris";
                isSmart = false;
                counter = 0;
                isHuman = false;
                break;
        }
    }
        
    /**
     * method takeTurn- finds whether player is human or computer and calls a move 
     * 
     * @param  none
     * @return int move
     */
    public int takeTurn()
    {
        inPileNow = Pile.numberRemaining;
        if(isHuman == true)
        {
            boolean legalMove = false;
            while(legalMove == false)
            {
                System.out.println(playerName + ", How many marbles would you like to take? > ");
                move = scan.nextInt();
                if((1 <= move) && (move <= (inPileNow/2)))
                {
                    legalMove = true;
                }
                else
                {
                    System.out.println("That is not a legal move");
                }
            }
        }
        else
        {    
            switch(familyRand)
            {
                case 0:
                    move = smartMove();
                    break;
                    
                case 1:
                    if(isSmart == true)
                    {
                        move = smartMove();
                        counter ++;
                    }
                    else if(isSmart == false)
                    {
                        move = stupidMove();
                        counter ++;
                    }
                    
                    if(counter == 3)
                    {
                        isSmart = !isSmart;
                        counter = 0;
                    }
                    
                    break;
                    
                case 2:
                    if(isSmart == true)
                    {
                        move = smartMove();
                    }
                    else if(isSmart == false)
                    {
                        move = stupidMove();
                    }
                    isSmart = !isSmart;
                    break;
                    
                case 3:
                    move = stupidMove();
                    
                    break;
                }
            }
        return move;
        }
    
    /**
     * method smartMove- calculates a smart move if possible
     * 
     * @param  none
     * @return int move
     */
    public int smartMove()
    {
        inPileNow = Pile.numberRemaining;
        if((inPileNow == 1) || (inPileNow == 3) || (inPileNow == 7) || (inPileNow == 15)
        || (inPileNow == 31) || (inPileNow == 63))
        {
            System.out.println("Forced a Stupid Move\n");
            move = stupidMove();
        }
        else
        {
            doneNow = false;
            while(doneNow == false)
            {
                if((Math.pow(2, exponent)-1) > inPileNow)
                {
                    exponent--;
                } 
                else if((Math.pow(2, exponent)-1) < inPileNow)
                {
                    doneNow = true;
                }
            
            }
        move = inPileNow - (int)(Math.pow(2, exponent)-1);
        }
    return move;
    }
    
    /**
     * method stupidMove- calculates a stupid move
     * 
     * @param  none
     * @return int move
     */
    public int stupidMove()
    {
        inPileNow = Pile.numberRemaining;
        move = (rand.nextInt(inPileNow/2) + 1); 
        return move;
    }     
}


Pile Class:


		Code:
	

import java.util.Random;
import java.util.Scanner;
/**
 * Create a Pile for the game and make changes to the pile
 * 
 * @author Salvage-This
 * @version 1.0
 */
public class Pile
{
    public static Random rand;
    Scanner scan;
    String Pile;
    public static int numberRemaining;
    int move;

    /**
     * Calls new pile to make a new pile for the game
     */
    public Pile()
    {
        rand = new Random();
        next();
    }
    
    /**
     * Next Method calls resetPile 
     * 
     * @param  none
     * @return void
     */
    public void next()
    {
        resetPile();
    }
            
    /**
     * Randomises a new pile between 10 and 100
     * 
     * @param void   
     * @return initalPile
     */
    public static int resetPile()
    {
        
        int initalPile;
        initalPile = (rand.nextInt(90) + 11);
        numberRemaining = initalPile;
        return initalPile; 
    }
    
    /**
     * Changes the number of marbles in the pile
     * 
     * @param playerMove
     * @return int numberRemaining
     */
    public int removeNumber()
    {
         numberRemaining = (numberRemaining - move);
         System.out.println("the number remaining is " + numberRemaining);
         return numberRemaining;
    }    
}


----------



## NyxCharon

I've got a problem for anyone who can help. 
Problem description:
"write a method that reads a file and returns an array list of all positive integers that were found in the file. Break up floating-point numbers and numbers containing commas. (14.9 results in two integers 14 and 9, and 200,000 results in 200 and 0.)

For example, consider this file:

In his final budget, the Republican governor declared a fiscal emergency to add urgency to the state budget process after a legislative impasse in 2009 that lasted over 100 days in the midst of recession.

The budget aims to close a $19.9 billion deficit over the next year and a half, relying mostly on spending cuts of $8.5 billion, which the governor called "draconian," and $6.9 billion in federal funds. The state will spend $82.9 billion in fiscal 2010-2011, beginning in July.

Under the cuts, more than 200,000 children will lose eligibility for health insurance.

Your method should return an array list [2009, 100 ,19, 9, 8, 5, 6, 9, 82, 9, 200, 0].

Hint: in.useDelimiter("[^0-9]+"); "


This is my attempt:


		Code:
	

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
     
public class FindNumbers
{
   /**
      This class reads a file and returns an array list of all numbers in the file. 
      Only numbers following the Java number convention are matched. For example,
      14.9 is recognized but 200,000 results in two numbers 200 and 0.
      @param filename the file name
      @return a list of numbers
   */
   public static ArrayList<Double> read(String filename) throws IOException
   {

    ArrayList<Double> nums=new ArrayList<Double>();
    Scanner in=new Scanner(filename);
    in.useDelimiter("[^0-9]+");
   while(in.hasNext())
{
double num=Double.parseDouble(in.next());
nums.add(0,num);
}

return nums;


   }
}



I'm not really sure how the delimiter works, as is now i just return a empty ArrayList.


----------



## NyxCharon

One more problem i need help with, if someone would be so kind.

Problem:
Your task is to read a file containing arithmetic instructions such as

3 + 4
4 - 10
7 * 11

Each instruction contains an integer, an operator (+, -, or *), and another integer.

Return an array list of the results. If there is any error, throw an IOException.



		Code:
	

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*; 
public class Arithmetic
{
   /**
      This class reads a file containing arithmetic expressions and returns an 
      array list of the results. 
      @param filename the file name
      @return a list of results
   */
   public static ArrayList<Integer> read(String filename) throws IOException
   {
     ArrayList<Integer> nums=new ArrayList<Integer>();

      FileReader file=new FileReader(filename);
      Scanner in=new Scanner (file); 

      
while(in.hasNextLine())
{
String line=in.nextLine();
if (line.length() != 0 )
{

int space=line.indexOf(" ");
int space2=line.lastIndexOf(" ");
String operation=line.substring(space,space2);
int num1=Integer.parseInt(line.substring(0,space));
int num2=Integer.parseInt(line.substring(space2,line.length()));

if(operation.equals("+"))
nums.add(0,(num1+num2));

if(operation.equals("/"))
nums.add(0,(num1/num2));

if(operation.equals("*"))
nums.add(0,(num1*num2));

if(operation.equals("-"))
nums.add(0,(num1-num2));

}
}
   
return nums;



}
 
  // This method checks your work. Do not modify.
   
   public static String check(String filename)
   {
      try
      {
         return read(filename).toString();
      }
      catch (IOException ex)
      {
         return "I/O exception thrown";
      }
      catch (Exception ex)
      {
         return ex.getMessage();
      }
   }
}


----------



## Cromewell

For the first one, why is your list typed as a double? You know from the requirements you are only looking for integers.

I generally don't like static methods but that isn't the problem here. Look at where you are creating your Scanner, here's the class reference: http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html

Check out the ways you can create the object and you should see your error 

I'll have a look at the second one later today.


----------



## mihir

So we have a java thread to now.
Hey cromwell how about a Python thread.
And if you want I can give an intro on python.


----------



## Cromewell

There have been several threads from the start. Check the sticky: http://www.computerforum.com/189564-programming-sticky.html

No python thread as of yet. If you want one feel free to make one using this thread's format and PM me, I'll add it to the sticky.


----------



## NyxCharon

Cromewell said:


> For the first one, why is your list typed as a double? You know from the requirements you are only looking for integers.
> 
> I generally don't like static methods but that isn't the problem here. Look at where you are creating your Scanner, here's the class reference: http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html
> 
> Check out the ways you can create the object and you should see your error
> 
> I'll have a look at the second one later today.



The double thing was actually a messup on the programmers part. That was completed before given to the students. I actually sorted both of these out today, so thanks for looking at them at least. 
I can post  my final code for either if anyone was interested for any reason.


----------



## Cromewell

I didn't have time to build the second one but from the look of it I think the only thing that isn't right is your Scanner. Same problem as the first


----------



## Cromewell

Closer look at #2, the scanner call actually looks ok.

I would rather see methods that do the work (i.e. add(num, num) subtract(num,num), multiply(num,num)....) instead of everything all in one read method but it should still work and it's a simple enough task that it doesn't make the read method overly complex.

When adding elements to your list you don't need to specify the index you want to add to, you can just say list.add(element);. It still works as you have it but less typing is always a plus.

As is, your code will throw a number format exception, the problem is in the location of space2 and how substring works.

You'll also want to print out the operation that you've read to see exactly what it looks like, you've got a bonus character.


----------



## NyxCharon

Finished the first program, and almost finished with this second one. Everything works out, except I'm not throwing a exception when i should be. The input in the tester is "four" which obviously doesn't work. What would be the easiest way to throw a exception for something like that? 
Other then that, it works fine.



		Code:
	

import java.io.File;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Scanner;

import java.io.*; 

public class Arithmetic

{

   /**

      This class reads a file containing arithmetic expressions and returns an 

      array list of the results. 

      @param filename the file name

      @return a list of results

   */

   public static ArrayList<Integer> read(String filename) throws IOException

   {

     ArrayList<Integer> nums=new ArrayList<Integer>();



      File file=new File(filename);

      Scanner in=new Scanner (file); 









while(in.hasNextLine())

{

String line=in.nextLine();

if (line.length() != 0 )

{







int space2=line.lastIndexOf(" ");

String operation=line.substring(space+1,space2);

int num1=Integer.parseInt(line.substring(0,space));

int num2=Integer.parseInt(line.substring(space2+1,line.length()));



if(operation.equals("+"))

nums.add(num1+num2);



else if(operation.equals("/"))

nums.add(num1/num2);



else if(operation.equals("*"))

nums.add(num1*num2);



else if(operation.equals("-"))

nums.add(num1-num2);

else throw new IOException();

}





}

   

return nums;







}

 

  // This method checks your work. Do not modify.

   

   public static String check(String filename)

   {

      try

      {

         return read(filename).toString();

      }

      catch (IOException ex)

      {

         return "I/O exception thrown";

      }

      catch (Exception ex)

      {

         return ex.getMessage();

      }

   }

}


----------



## Cromewell

You'll have to change your method definition to throw some kind of exception:


		Code:
	

String operation;
int num1;
int num2;
try{
operation=line.substring(space+1,space2);

num1=Integer.parseInt(line.substring(0,space));

num2=Integer.parseInt(line.substring(space2+1,line.length()));
}
catch (Exception E){ //this can be more specific, I just can't remember what these will throw off hand
throw new BadInputException("Values Missing from Input, found: " + line)
}


----------



## NyxCharon

that worked, i just changed throw new BadInputException(); to throw new IOException();

Thanks


----------



## Dropkickmurphys

Bananapie said:


> I am looking for some assistance involving a JAVA program
> 
> I am to input a maximum of 4 digits of type Integer. It is valid if it does not include any letters, otherwise(if it does include letters), throw an exception error.
> 
> My problem is deciphering if it does have letters or not.
> 
> I have tried several things, but the way that I have now SHOULD work from what I can tell, but isn't. It is as follows.
> 
> 
> 
> Code:
> 
> 
> try
> 
> {
> idN = keyboard.nextInt();
> idString = Integer.toString(idN);
> if (idN < 1)
> throw new Exception ("Badge # cannot be zero, or negative");
> if (idString.length() > 4)
> throw new Exception ("Badge # cannot be longer than"
> + " 4 digits.");
> 
> for (int i = 0; i <= idString.length()-1; i++)
> {
> array[i] = idString.charAt(i);
> System.out.print(array[i]);
> 
> }
> 
> for (int x = 0; x < 4; x++)
> {
> if (array[x] == '1' || array[x] == '4' || array[x] == '7' ||
> array[x] == '2' || array[x] == '5' || array[x] == '8' ||
> array[x] == '3' || array[x] == '6' || array[x] == '9' ||
> array[x] == '0')
> done = true;
> else
> {
> 
> throw new Exception("Cannot include a letter.");
> 
> }
> }
> 
> done = true;
> idNum = idN;
> 
> 
> }
> catch(Exception e)
> {
> System.out.println("Error: "+e.getMessage());
> }
> 
> 
> In this code, the first two exceptions are if it contains more than 4 digits, and it cannot be a negative.
> 
> It's probably something simple. It's probably along the lines of where I convert the int to a String, and then to  a char array... as that is the only way I know of doing it.
> 
> Any help appreciated!



Try saving the input numbers as a string and use the Pattern.matches class. you could do something like:



		Code:
	

String s = "123557ab";

if(Pattern.matches("[0-9]",s)) {
//Do something if it only contains numbers
}
else {
//Do something if it contains other characters.
}


[0-9] is a regular expression to check whether the string only contains numbers.
alternatively you could just try and parse the string as an integer and if it fails throw an error. (see parseInt http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Integer.html#parseInt(java.lang.String))

Hope that helps. I haven't tested it, although I think it will work.


----------



## Dropkickmurphys

Where are you putting this code in respect to what you first posted? It could be something to do with the other loops you use.

If possible could you post the whole lot again?


----------



## Dropkickmurphys

Why are you putting it all in a while loop, if you are setting done to true whatever happens?


----------



## Cromewell

This is the same problem as people were having in the C/C++ thread. My suggestion would be to read the user input as a string then try to parse an int out of it. You look like you are on your way there now, just need to finish converting it over.



> Why are you putting it all in a while loop, if you are setting done to true whatever happens?


The set to true only happens if no exception is thrown.


----------



## Cromewell

I'm not sure, it's probably with the way you wrote it. In my version it's working as it should. I don't think it's a hierarchy thing, can you post up your code?


----------



## Cromewell

Move this line:
idN = Integer.parseInt(idNum);
to after the point that you check you can parse an integer out of the string. It's throwing an inputmismatch exception which is being caught by your generic exception handler and displaying that unexpected text.


----------



## NyxCharon

I've been helped in this thread, so time to give back 

My latest project ("NameSurfer"), in case anyone wanted something to play with.
Rather simple, you type in a name and the program then plots how popular a name was in a given decade. Only the top 1000 names from each decade are included. If the name was above the top 1000, a 0 is plotted. Search returns the top year for that name in the console. It's rather simple, but a lot can be added to it.
Main class is NameFrame


Edit:Here, it wont fit in more then like 3 post, so i zipped it up for download,

http://www.adrive.com/public/2702e0abc06625cbf74d7ed12861e1ded5446bb346fd6b42239468f84326715d.html


----------



## danthrax

Question for you savvy Java folks.  I have dabbled in programming in a couple different languages (C#, VisualBasic, and C++) and I would really like to learn and understand Java well enough to write a program to solve a complex problem.  I'm interested in Java for several other reasons as well.

My question is, from what sources do you recommend learning Java?  I have heard of several different books that are good.  I tend to learn well (as I'm sure a lot of programmers do) from examples and trying things on my own.  Do any of you know of good online tutorials?  I have viewed several tutorials on YouTube that I have enjoyed so far. 

I've been reading through the Java thread and some of you are clearly very knowledgeable about the language!  So any input is greatly appreciated.

Thanks!


----------



## Cromewell

I used http://mindview.net/Books/TIJ/ it's pretty good and available online free from the author (although it's an older edition).


----------



## Krazyshank

*Need some help with user input (Java)*

I am currently trying to make a program that determines what instrument you should play from the users inputs. EX: Do you want to play a wind instrument?
then the user will input true or false. But i have no idea how to right user input to text strings and/or boolean logic variables. Here is my code so far, I am aware that it has many errors spelling/capitalization wise, but I can fix that later. Please just show me how I could accomplish this.
My code:
import java.util.Scanner;

class Instrument {
	public static void main(String[] arguments) {
	// Guessing Game intro start
		System.out.println("Hello there! I am the amazing, fantastic, intreaging guessing galore!")
		System.out.println("I will guess your destined instruement!")
	// Guessing Game intro end
	// Variables
		int questionsAsked = 0;
		String Saxophone = Saxophone;
		String Clairinet = Clairinet;
		String Flute = Flute;
		String Piano = Piano;
		String Barrackas = Barrackas;
		String Guitar = Guitar;
		String Violin = Violin;
		String Viola = Viola;
		String Chello = Chello;
		String Banjo = Banjo;
		String Harp = Harp;
		String String = String;
		String Drums = Drums;
		String Triangle = Triangle;
		String Bagpipes = Bagpipes;
		String Ocarina = Ocarina;
		String String = String;
		String Wind = Wind;
		String Hands = Hands;
		String Sticks = Sticks;
		String NoneOfTheFollowing = None Of The Following;
		String Answer = " ";
	// Boolean Logic
		boolean Reed = false;
		boolean Guitar = false;
		boolean	Violin = false;
		boolean Viola = false;
		boolean Chello = false;
		boolean Banjo = false;
		boolean Harp = false;
		boolean String = false;
		boolean Wind = false;
		boolean Hands = false;
		boolean Sticks = false;
		boolean NoneOfTheFollowing = false;
		boolean Saxophone = false;
		boolean Clairinet = false;
		boolean Flute = false;
		boolean	Piano = false;
		boolean Barrackas = false;
		boolean Drums = false;
		boolean Triangle = false;
		boolean Bagpipes = false;
		boolean Ocarina = false;
	// Questions
				System.out.println("Let the questions begin, answer with either /"true/" or /"false/"!");
				System.out.println("Do you want use " + Wind to play your instrument?");
			int questionsAsked = 1;
	// Key listener here, take answer and write to variable "Wind"
				System.out.println("I have asked you " + questionsAsked so far");
				System.out.println("Do you want to use a " + Reed to play your instrument?");
			int questionsAsked = 2;
	// Key listener here, take answer and write to variable "Reed"
				System.out.println("I have asked you " + questionsAsked so far");
				System.out.println("Do you want to use your " + Hands to play your instrument?");
			int questionsAsked = 3;
	// Key listener here, take answer and write to variable "Hands"
				System.out.println("I have asked you " + questionsAsked so far");
				System.out.println("Do you want to use " + Sticks to play your instrument?");
			int questionsAsked = 4;
	// Key listener here, take answer and write to variable "Sticks"
				System.out.println("I have asked you " + questionsAsked so far");
				System.out.println("Do you not want to use any of the following stated? " + NoneOfTheFollowing to play your instrument?");
			int questionsAsked = 5;
	// Key listener here, take answer and write to variable "NoneOfTheFollowing"
				System.out.println("I have asked you " + questionsAsked so far. Now I am ready to present my answer");
	// End questioning
	// Method Statements here
				System.out.println("Your favorite instrument is " + Answer")
				System.out.println("Is that the correct answer?")
	// Answer Key listener here

-----------------------------------------------
its not done and the import is not being used but as far as I know, its needed for the java scanner. so where it says // Key listener here, take answer and write to variable,  I want it to take the userinput and store it to teh string so I can use it later. im 13 so this code is good so far :/


----------



## Cromewell

I've merged your thread into our java thread.

First, what is going on with your variable declarations? You don't need to say String String = String;. This particular one is also important because you are trying to name a variable with a reserved word. Your string declarations can simply be String InstrumentName; or if you want to explicitly initialize String InstrumentName = "";.
Also, you're redeclaring questionsAsked a lot, that'll generate a compiler error.

The Java API doc is actually a pretty good reference guide (http://download.oracle.com/javase/6/docs/api/index.html). You do have to know what you are looking for though. In this case it's easy: Scanner.

There are some user input examples in this thread already but here's a quick rundown again:

Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextString(); //userInput now has a string read from standard in

Like with all user input you'll have to test to make sure that they gave you what you asked for (pesky users always want to break your code).


----------



## Krazyshank

Cromewell said:


> I've merged your thread into our java thread.
> 
> First, what is going on with your variable declarations? You don't need to say String String = String;. This particular one is also important because you are trying to name a variable with a reserved word. Your string declarations can simply be String InstrumentName; or if you want to explicitly initialize String InstrumentName = "";.
> Also, you're redeclaring questionsAsked a lot, that'll generate a compiler error.
> 
> The Java API doc is actually a pretty good reference guide (http://download.oracle.com/javase/6/docs/api/index.html). You do have to know what you are looking for though. In this case it's easy: Scanner.
> 
> There are some user input examples in this thread already but here's a quick rundown again:
> 
> Scanner scanner = new Scanner(System.in);
> String userInput = scanner.nextString(); //userInput now has a string read from standard in
> 
> Like with all user input you'll have to test to make sure that they gave you what you asked for (pesky users always want to break your code).



Thanks alot! But for the String String = String thing, the string data (Which is also the word string lol) was mean to be like for stringed instruments.

But anyway,
Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextString(); //userInput now has a string read 
So waht will that write the input to? The next string under it?
Oh and what could I use to fis the questionsAsked problem? And one more thing, so far does the code seem to be PARTIALY on the correct track for where I am going? DO i even need all those strings? I just put them in there just incase I needed them for declaring the answer.


----------



## Cromewell

> Thanks alot! But for the String String = String thing, the string data (Which is also the word string lol) was mean to be like for stringed instruments.


What I mean is, in general, you don't want to write a variable declaration like String name = name;. I figured out that you meant the string section of an orchestra but in that case you'll need a different name 


> But anyway,
> Scanner scanner = new Scanner(System.in);
> String userInput = scanner.nextString(); //userInput now has a string read
> So waht will that write the input to? The next string under it?


The input is stored in the userInput variable. When you write String userInput = scanner.nextString(); you are declaring a String variable named userInput and assigning it the value of a string read from scanner.


> Oh and what could I use to fis the questionsAsked problem?


 Just remove the int from all lines but the initial declaration.
class Instrument {
public static void main(String[] arguments) {
// Guessing Game intro start
System.out.println("Hello there! I am the amazing, fantastic, intreaging guessing galore!")
System.out.println("I will guess your destined instruement!")
// Guessing Game intro end
// Variables
int questionsAsked = 0;
// Questions
System.out.println("Let the questions begin, answer with either /"true/" or /"false/"!");
System.out.println("Do you want use " + Wind to play your instrument?");
questionsAsked = 1; //// <------------------Notice no int at the start of this line, you could also write this as an incremetal operation.......i.e. questionsAsked++;


> DO i even need all those strings? I just put them in there just incase I needed them for declaring the answer.


Depends on the requirements. Say I wanted to return all the answers they provided, in that case I would need to store all of their answers in a bunch of variables.


----------



## Krazyshank

Cromewell said:


> What I mean is, in general, you don't want to write a variable declaration like String name = name;. I figured out that you meant the string section of an orchestra but in that case you'll need a different name
> 
> The input is stored in the userInput variable. When you write String userInput = scanner.nextString(); you are declaring a String variable named userInput and assigning it the value of a string read from scanner.
> Just remove the int from all lines but the initial declaration.
> class Instrument {
> public static void main(String[] arguments) {
> // Guessing Game intro start
> System.out.println("Hello there! I am the amazing, fantastic, intreaging guessing galore!")
> System.out.println("I will guess your destined instruement!")
> // Guessing Game intro end
> // Variables
> int questionsAsked = 0;
> // Questions
> System.out.println("Let the questions begin, answer with either /"true/" or /"false/"!");
> System.out.println("Do you want use " + Wind to play your instrument?");
> questionsAsked = 1; //// <------------------Notice no int at the start of this line, you could also write this as an incremetal operation.......i.e. questionsAsked++;
> 
> Depends on the requirements. Say I wanted to return all the answers they provided, in that case I would need to store all of their answers in a bunch of variables.



Ok sweet, I will keep that in mind! I have also rewritten the program with the scanner in it and I used if and else statements to make things easier to understand and the program shorter. 

Ill reply back with the results later.


----------



## Krazyshank

Cromewell said:


> What I mean is, in general, you don't want to write a variable declaration like String name = name;. I figured out that you meant the string section of an orchestra but in that case you'll need a different name
> 
> The input is stored in the userInput variable. When you write String userInput = scanner.nextString(); you are declaring a String variable named userInput and assigning it the value of a string read from scanner.
> Just remove the int from all lines but the initial declaration.
> class Instrument {
> public static void main(String[] arguments) {
> // Guessing Game intro start
> System.out.println("Hello there! I am the amazing, fantastic, intreaging guessing galore!")
> System.out.println("I will guess your destined instruement!")
> // Guessing Game intro end
> // Variables
> int questionsAsked = 0;
> // Questions
> System.out.println("Let the questions begin, answer with either /"true/" or /"false/"!");
> System.out.println("Do you want use " + Wind to play your instrument?");
> questionsAsked = 1; //// <------------------Notice no int at the start of this line, you could also write this as an incremetal operation.......i.e. questionsAsked++;
> 
> Depends on the requirements. Say I wanted to return all the answers they provided, in that case I would need to store all of their answers in a bunch of variables.



Hey, how can I make the scanner work for integers? 
is it just
Scanner scanner = new Scanner(System.in);
int userInput = scanner.nextint();

???

and also, can I change
Scanner scanner = new Scanner(System.in);
String userInput = scanner.nextString();

The userInput string from that to any name?


----------



## Cromewell

> Hey, how can I make the scanner work for integers?
> is it just
> Scanner scanner = new Scanner(System.in);
> int userInput = scanner.nextint();


The doc page tells you all the methods on scanner, but yes it's just nextInt()  http://download.oracle.com/javase/6/docs/api/java/util/Scanner.html

You'll have to be careful about reading numeric types because it will throw exceptions if it doesn't find what it's looking for. You just need to use a try/catch block but if you are just starting out you may not have learned about those yet.


> The userInput string from that to any name?


Yes, the variable you are reading into can be whatever name you want.


----------



## Krazyshank

Okay, got another program here.
Its a calculator. I didnt look online to see what methods people used to code theres so here it is 

import java.util.Scanner;

class Calculator
	public static void main(String[] argments) {
		int answer = 0;
		System.out.println("Please type your starting number.");
		Scanner scanner = new Scanner(System.in);
		int firstNumber = scanner.nextInt();
		System.out.println("Please type /n/"+/" for addition /n/"-/" for subtraction /n/"//" for division /n or /"*/" for multiplication.");
		Scanner scanner = new Scanner(System.in);
		String type = scanner.nextint();
			if (type = +) {
				System.out.println("What number would you like to add to " + firstNumber?");
				Scanner scanner = new Scanner(System.in);
				int secondNumber = scanner.nextInt();
				int answer = firstNumber + secondNumber;
				System.out.println(" + firstNumber plus " + secondNumber equals " + answer.");
			else if (type = /)
				System.out.println("What number would you like to divide " + firstNumber by?");
				Scanner scanner = new Scanner(System.in);
				int secondNumber = scanner.nextInt();
				int answer = firstNumber / secondNumber;
				System.out.println(" + firstNumber divided by " + secondNumber equals " + answer.");
			else if (type = -)
				System.out.println("What number would you like to subtract from " + firstNumber?");
				Scanner scanner = new Scanner(System.in);
				int secondNumber = scanner.nextInt();
				int answer = firstNumber - secondNumber;
				System.out.println(" + firstNumber minus " + secondNumber equals " + answer.");
			else if (type = *)
				System.out.println("What number would you like to multiply " + firstNumber by?");
				Scanner scanner = new Scanner(System.in);
				int secondNumber = scanner.nextInt();
				int answer = firstNumber + secondNumber;
				System.out.println(" + firstNumber multiplied by " + secondNumber equals " + answer.");
			}
	}
}


For some reason,when I compile i get 67 errors!!11 D=
wahts wrong?


----------



## Cromewell

There's a whole host of things. The compiler should tell you what they are and the line number. Some of which we've already talked about, such as redeclaring variables.

Another thing, the escape character is \ not / which may cause cascading errors.

For one more I goofed on the scanner, to read a string it's just .next(); not .nextString();

Additionally, to compare non-primitives (int, float, double, etc) in Java use the .equals method otherwise you aren't doing the operations you think you are. Using == you are actually comparing the reference and testing if 2 objects are the same.


----------



## Bananapie

So I just got a program from my teacher. It started off as a basic airline reservation program. Show diagram of plane, show empty seats/taken seats without displaying info about that person. Menu driven/user input(We decide what info to collect)

I collected the Name of the person, the seat they plan to reserve, and their phone number.

I hand it in, get 100%. Well this program we were told was going to be built on incrementally. No problem, had a good feel for it.

Next class day, she gives us someone elses program and the new requirements that we have to meet... the new requirements are:
-Have user enter name, telephone number, address, city, state, and zip.
-Name cannot have any numbers
-Must issue an ID number to allow look-up of passenger in menu
-Must be able to search by phone number or id number in case the passenger forgets their seat.
-Change size of plane from 8 rows(4 columns) to 5 rows(4 columns)

Well the person's program I got was built SPECIFICALLY for the first requirements, and making it entirely far to difficult to make any changes to... and did a lot of unnecessary garbage in the mean time. 

It would be far easier to write an entirely new program to meet the requirements than edit this idiots program, but sadly that is not one of the requirements.  I know who's program it is, and really want to hurt them because they KNEW it would be built on.

Did I mention that he does this on an EXAM program? Meaning it's a pretty large part of my grade.

/end rant. fml :|


----------



## Troncoso

I'd like to play the java game. Can anyone recommend a good book to start out with.


----------



## Bananapie

Troncoso said:


> I'd like to play the java game. Can anyone recommend a good book to start out with.




When I started, I used *Introduction to Java Programming by Y. Daniel Liang*


----------



## Troncoso

Soo...looking for some java guys here.

I'm making a board game into a computer game. You choose a character and a path to follow. You roll the dice to move down the path and pick up attack cards and health cards along the way. You also have a chance of landing on a special ability, in which case a special ability card is added to your deck. <<<<< This is were my trouble is at the moment.

I have a method called drawCard() when I land on such spaces. the method chooses a random card, displays what it is, and adds it to an arrayList<Integer>.
Now, I have 2 methods that use this method. 1 Is playerTurn() and the other is computerTurn(). When I execute these methods independent of actually running the game, the draw card method works fine. I know this, because after the player or the computer has reached the end, it prints their stats along with all the cards in their deck. BUT, when I just play the game, it runs fine, but when a player reaches the end, it doesn't print which cards they have. Here is the code for all relevant classes:

MainGame


		Code:
	

import java.util.Scanner;
import java.util.Random;
import java.util.ArrayList;

/**
* Write a description of class MainGame here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class MainGame
{
    // instance variables - replace the example below with your own
    private Scanner input;
    private Random rand;
    private Character player, computer;
    private Path chosenPath, computerPath;
    private int spaces, computerSpaces, numTurns = 0;
    private int atkBonus, hpBonus, computerAtk, computerHp;
    private ArrayList<Integer> cardDeck, computerDeck;
    private SpecialCard specialCardDeck;
    private boolean playerTurn = true;
    private boolean lostTurn = false;
    private boolean compLostTurn = false;

    /**
     * Constructor for objects of class MainGame
     */
    public MainGame()
    {
        input = new Scanner(System.in);
        rand = new Random();
        showMenu();
        
    }
    
    /**
     * Display the instructions
     */
    public void showInstructions()
    {
        System.out.println("To begin playing, first choose a character.");
        System.out.println("Each character has different stats, so choose wisely");
        System.out.println("Once you've chosen a character, choose a path.");
        System.out.println("Each path contains a different amount of upgrades for your character.");
        System.out.println("These upgrades include attack, health and special abilities.");
        System.out.println("Which path you choose is up to you.\n");
        System.out.println("when the game starts, you will roll a dice.");
        System.out.println("The dice will show how many spaces you move.");
        System.out.println("If you land on an attack or health space, you will receive a bonus");
        System.out.println("If you land on a special ability space, a special ability card will \nbe added to your deck.");
        System.out.println("This will continue until you reach the arena. At that time, the \nrules for the arena will be displayed.");
        input.nextLine();
        showMenu();
    }
    
    /**
     * Show the menu
     */
    public void showMenu()
    {
        int choice = 0;
        
        System.out.println("1. New Game");
        System.out.println("2. Continue");
        System.out.println("3. Instructions");
        System.out.println("4. Quit\n");
        if (input.hasNextInt())
            choice = input.nextInt();
        input.nextLine();
        
        while (choice < 1 || choice > 4)
        {
            System.out.println("This choice is not valid. Please choose 1 through 4.\n");
            if (input.hasNextInt())
                choice = input.nextInt();
            input.nextLine();
        }
        
        if (choice == 1)
        {
            startGame();
        }
        else if (choice == 2)
        {
            continueGame();
        }
        else if (choice == 3)
        {
            showInstructions();
        }
        else if (choice == 4)
        {
            quit();
        }
    }
    
    public void startGame()
    {
        /****************
         * player setup *
         ****************/
        int choice = 0;
        System.out.println("Welcome! Before starting the game, please select your character:\n");
        System.out.println("1. Warrior:   20 Health  8-Sided Die");
        System.out.println("2. Soldier:   35 Health  6-Sided Die");
        System.out.println("3. Defender:  50 Health  4-Sided Die");
        System.out.println("4. Return to menu\n");
        if (input.hasNextInt())
                choice = input.nextInt();
        input.nextLine();
       
        while (choice < 1 || choice > 4)
        {
            System.out.println("This choice is not valid. Please choose 1 through 4.\n");
            if (input.hasNextInt())
                choice = input.nextInt();
            input.nextLine();
        }
        
        if (choice == 1)
        {
            player = new Character(20, 8, "Warrior");
        }
        else if (choice == 2)
        {
            player = new Character(35, 6, "Soldier");
        }
        else if (choice == 3)
        {
            player = new Character(50, 4, "Defender");
        }
        else if (choice == 4)
        {
            quit();
        }
        
        System.out.println("Now you must choose which path you will take:\n");;
        System.out.println("1. Balanced Path: Upgrades are even");
        System.out.println("2. Attack Path:   Mostly attack upgrades");
        System.out.println("3. Defense Path:  Mostly health upgrades");
        System.out.println("4. Special Path:  Less upgrades, more special abilities\n");
        if (input.hasNextInt())
                choice = input.nextInt();
        input.nextLine();
       
        while (choice < 1 || choice > 4)
        {
            System.out.println("This choice is not valid. Please choose 1 through 4.\n");
            if (input.hasNextInt())
                choice = input.nextInt();
            input.nextLine();
        }
        
        if (choice == 1)
        {
            chosenPath = new Path(.40, .40, .15, "Balance");
        }
        else if (choice == 2)
        {
            chosenPath = new Path(.60, .20, .15, "Attack");
        }
        else if (choice == 3)
        {
            chosenPath = new Path(.20, .60, .15, "Defense");
        }
        else if (choice == 4)
        {
            chosenPath = new Path(.35, .35, .24, "Special"); 
        }
        /******************
         * computer setup *
         ******************/
        int decision = rand.nextInt(3) + 1;
        if (decision == 1)
        {
            computer = new Character(20, 8, "Warrior");
        }
        else if (decision == 2)
        {
            computer = new Character(35, 6, "Soldier");
        }
        else if (decision == 3)
        {
            computer = new Character(50, 4, "Defender");
        }
        
        int decision2 = rand.nextInt(4) + 1;
        if (decision2 == 1)
        {
            computerPath = new Path(.40, .40, .15, "Balance");
        }
        else if (decision2 == 2)
        {
            computerPath = new Path(.60, .20, .15, "Attack");
        }
        else if (decision2 == 3)
        {
            computerPath = new Path(.20, .60, .15, "Defense");
        }
        else if (decision2 == 4)
        {
            computerPath = new Path(.35, .35, .24, "Special"); 
        }
        
        System.out.println("The computer chooses to be a " + computer.getCharType());
        System.out.println("and will travel the " + computerPath.getPathName() + " path\n");
        /******************
         * Start the game *
         ******************/
        spaces = chosenPath.getNumSpaces();
        computerSpaces = computerPath.getNumSpaces();
        System.out.println("Let the game begin!\n");
        input.nextLine();
        while (spaces > 0 || computerSpaces > 0)
            playGame(player, chosenPath, computer, computerPath);
    }
    
    public void continueGame()
    {
        System.out.println("Continuing game\n");
        input.nextLine();
        showMenu();
    }
    
    public void quit()
    {
        System.out.println("Ending game\n");
        input.nextLine();
        System.exit(0);
    }
    
    public void playGame(Character charChosen, Path pathChosen, Character computerChar, Path computerPath)
    {
        cardDeck = new ArrayList<Integer>();
        computerDeck = new ArrayList<Integer>();
        specialCardDeck = new SpecialCard();
        
        
        if (playerTurn == true)
        {
            if (spaces > 0)
            {
                if (lostTurn == false)
                {
                    playerTurn(player, chosenPath);
                    playerTurn = false;
                    System.out.println("************************\n");
                }
                else
                {
                    System.out.println("You lose this turn\n");
                    System.out.println("************************\n");
                    playerTurn = false;
                    lostTurn = false;
                }
            }
            else
            {
                System.out.println("You have reached the arena\n");
                System.out.println("************************\n");
                playerTurn = false;
            }
                
        }
        else
        {
            if (computerSpaces > 0)
            {
                if (compLostTurn == false)
                {
                    computerTurn(computer, computerPath);
                    playerTurn = true;
                    numTurns += 1;
                    System.out.println("************************\n");
                }
                else
                {
                    System.out.println("Computer loses this turn\n");
                    System.out.println("************************\n");
                    playerTurn = true;
                    compLostTurn = false;
                    numTurns += 1;
                }
            }
            else
            {
                System.out.println("The computer has reached the arena\n");
                System.out.println("************************\n");
                playerTurn = true;
                numTurns += 1;
            }
        }
        
    }
    
    
    private int rollMoveDice()
    {
        int roll = rand.nextInt(4) + 1;
        return roll;
    }
    
    /***************
     * player turn *
     ***************/
    public void playerTurn(Character charChosen, Path pathChosen)
    {
        String curSpace;
        System.out.println("Press enter to roll the die.");
        input.nextLine();
        int movement = rollMoveDice();
        int bonus = 0;
        System.out.println("You rolled a " + movement);
        input.nextLine();
        if (spaces - movement > 0)
        {
            spaces -= movement;
            curSpace = pathChosen.spaceValue();
            System.out.println("You landed on a " + curSpace + " space.");
            
            if (curSpace == "Attack")
            {
                bonus = rand.nextInt(3) + 1;
                atkBonus += bonus ;
                System.out.println("You gain " + bonus + " attack.\n");
            }
            else if (curSpace == "Defense")
            {
                bonus = rand.nextInt(3) + 4;
                hpBonus += bonus;
                System.out.println("You gain " + bonus + " health.\n");
            }
            else if (curSpace == "Special Ability")
            {
                drawSpecialCard(specialCardDeck, "You draw", cardDeck);
            }
            else if (curSpace == "Lose Turn")
            {
                lostTurn = true;
                System.out.println("You lose your next turn.\n");
            }
        }
        else
        {
            spaces = 0;
            System.out.println("You have reached the arena!\n");
            System.out.println("Total Attack bonus: " + atkBonus);
            System.out.println("Total Health bonus: " + (player.getInitHealth() + hpBonus));
            System.out.println("Special Cards in deck: ");
            for (int card = 0;card < cardDeck.size();card++)
            {
                System.out.println(cardDeck.get(card));
            }
        }
    }
    /*****************
     * Computer turn *
     *****************/
    public void computerTurn(Character charChosen, Path pathChosen)
    {
        String curSpace;
        System.out.println("Computer rolls the die.\n");
        int movement = rollMoveDice();
        int bonus = 0;
        System.out.println("Computer rolled a " + movement);
        if (computerSpaces - movement > 0)
        {
            computerSpaces -= movement;
            curSpace = pathChosen.spaceValue();
            System.out.println("The computer landed on a " + curSpace + " space.");
        
             if (curSpace == "Attack")
            {
                bonus = rand.nextInt(3) + 1;
                computerAtk += bonus ;
                System.out.println("Computer gains " + bonus + " attack.\n");
            }
            else if (curSpace == "Defense")
            {
                bonus = rand.nextInt(3) + 4;
                computerHp += bonus;
                System.out.println("Computer gains " + bonus + " health.\n");
            }
            else if (curSpace == "Special Ability")
            {
                drawSpecialCard(specialCardDeck, "The computer draws", computerDeck);
            }
            else if (curSpace == "Lose Turn")
            {
                compLostTurn = true;
                System.out.println("Computer loses next turn.\n");
            }
        }
        else
        {
            computerSpaces = 0;
            System.out.println("Computer has reached the arena!\n");
            System.out.println("Total Attack bonus: " + computerAtk);
            System.out.println("Total Health bonus: " + (computer.getInitHealth() + computerHp));
            System.out.println("Special Cards in deck: ");
            for (int card = 0;card < computerDeck.size();card++)
            {
                System.out.println(computerDeck.get(card));
            }
            
        }
    }
    
   
    
    public void drawSpecialCard(SpecialCard deck, String player, ArrayList<Integer> playerDeck)
    {
            deck.chooseCard();
            playerDeck.add(deck.getCard());
            System.out.println(player + " a special ability card:");
            System.out.println(deck.getCardDesc());
            System.out.println("Type: " + deck.getCardType() + "\n");
        
    } 
    
    public void resetSpaces()
    {
        spaces = 10;
        computerSpaces = 10;
    }
}


Path:


		Code:
	

import java.util.Random;
/**
* Write a description of class Path here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class Path
{
    // instance variables - replace the example below with your own
    private double atkChance, defChance, spChance;
    private double loseTurnChance = .05;
    private int numSpaces = 30;
    private String pathName;
    private String[] valuesOfSpaces;
    private Random rand;
    

    /**
     * Constructor for objects of class Path
     */
    public Path(double atkChance, double defChance, double spChance, String pathName)
    {
        this.atkChance = atkChance;
        this.defChance = defChance;
        this.spChance = spChance;
        this.pathName = pathName;
        generateSpaceValues();
        rand = new Random();
    }
    
    public double getAtkChance()
    {
        return atkChance;
    }
    
    public double getDefChance()
    {
        return defChance;
    }
    
    public double getSpChance()
    {
        return spChance;
    }
    
    public String getPathName()
    {
        return pathName;
    }
    
    public int getNumSpaces()
    {
        return numSpaces;
    }
    
    public void generateSpaceValues()
    {
        int tally = 0;
        double totalAtk = atkChance * 100;
        double totalDef = defChance * 100;
        double totalSp = spChance * 100;
        double totalLoseTurn = loseTurnChance * 100;
        valuesOfSpaces = new String[100];
        double defenseTally, spTally, loseTurnTally;
        
        for(int i = 0;i <totalAtk;i++)
        {
            valuesOfSpaces[i] = "Attack";
            tally += 1;
        }
        //tally += 1;
        defenseTally = tally + totalDef;
        for (int i = tally;i<(int)defenseTally;i++)
        {
            valuesOfSpaces[i] = "Defense";
            tally += 1;
        }
        //tally += 1;
        spTally = tally + totalSp;
        for (int i = tally;i<(int)spTally;i++)
        {
            valuesOfSpaces[i] = "Special Ability";
            tally += 1;
        }
        //tally += 1;
        loseTurnTally = tally + totalLoseTurn;
        for (int i = tally;i<(int)loseTurnTally;i++)
        {
            valuesOfSpaces[i] = "Lose Turn";
            tally += 1;
        }
        
    }
    
    public String spaceValue()
    {
        int value = rand.nextInt(100);
        return valuesOfSpaces[value];
    }


SpecialCard


		Code:
	

import java.util.ArrayList;
import java.util.Random;
/**
* Write a description of class SpecialCard here.
* 
* @author (your name) 
* @version (a version number or a date)
*/
public class SpecialCard
{
    // instance variables - replace the example below with your own
    private ArrayList<Integer> cards;
    private ArrayList<String> cardDesc;
    private ArrayList<String> cardType;
    private Random rand;
    private int pickedCard;
    private String pickDesc;
    private String pickType;
    private int cardRemove;
    private int totalCards = 25;

    /**
     * Constructor for objects of class SpecialCard
     */
    public SpecialCard()
    {
        cards = new ArrayList<Integer>();
        cardDesc = new ArrayList<String>();
        cardType = new ArrayList<String>();
        rand = new Random();
        createCards();
    }
    
    private void createCards()
    {
        for(int i = 0; i < 25; i++)
        {
            cards.add(i);
        }
        
        cardDesc.add("+1 Attack for next turn");
        cardDesc.add("+1 Attack for next turn");
        cardDesc.add("+2 Attack for next turn");
        cardDesc.add("+2 Attack for next turn");
        cardDesc.add("+3 Attack for next turn");
        cardDesc.add("+3 Attack for next turn");
        cardDesc.add("+4 Attack for next turn");
        cardDesc.add("+5 Attack for next turn");
        cardDesc.add("Regain 5 Health");
        cardDesc.add("Regain 5 Health");
        cardDesc.add("Regain 10 Health");
        cardDesc.add("Regain 10 Health");
        cardDesc.add("Regain 15 Health");
        cardDesc.add("Parry. Player rolls against opponent attack. \nIf the player rolls higher, the oponent takes damage \ninstead equal to the player's roll");
        cardDesc.add("Parry. Player rolls against opponent attack. \nIf the player rolls higher, the oponent takes damage \ninstead equal to the player's roll");
        cardDesc.add("Block. Opponent's next attack does no damage");
        cardDesc.add("Block. Opponent's next attack does no damage");
        cardDesc.add("Steal. Take an Attack bonus from the opponent \nand add it to your own Attack");
        cardDesc.add("Steal. Take a Health bonus from the opponent \nand add it to your own Health");
        cardDesc.add("Leech. You and the opponent swap all remaining health");
        cardDesc.add("Leech. You take 15 health from the opponent \nand add it to your own");
        cardDesc.add("Speed. Attack 2 times in one turn");
        cardDesc.add("Speed. The oponent's attack only does half damage");
        cardDesc.add("Reflect. When the opponent attacks you, they \nalso recieve damage equal to half of their attack");
        cardDesc.add("Revive. Play this card when you are killed to \ncome back to life with 15 Health");
        
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("After Oponent Attack");
        cardType.add("After Oponent Attack");
        cardType.add("After Oponent Attack");
        cardType.add("After Oponent Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("Before Attack");
        cardType.add("After Oponent Attack");
        cardType.add("After Oponent Attack");
        cardType.add("After Oponent Attack");
    }
    
    public void chooseCard()
    {
        int card = rand.nextInt(totalCards);
        pickedCard = cards.get(card);
        pickDesc = cardDesc.get(card);
        pickType = cardType.get(card);
        cardRemove = card;
    }
    
    public int getCard()
    {
        return pickedCard;
    }
    
    public String getCardDesc()
    {
        return pickDesc;
    }
    
    public String getCardType()
    {
        return pickType;
    }
    
    public void removePick()
    {
        cards.remove(cardRemove);
        totalCards -= 1;
    }



Thank you for any help you might be able to give. If you need more info, let me know.


----------



## Cromewell

This probably isn't all of the problem but you are using Character with a constructor of taking int, int, string. But Character is a class wrapper for the char primitive.

I can't even build your project to try and see what's going on without your Character class.


----------



## Troncoso

Oh, haha. I forgot to add that. But I figured out the problem. I do have another issue though.

I'm copying information from a text file to an array of objects of Cards. 
Some of the records have a new line character (\n) in the text file itself, but not all of them.
When I try to print the elements of the array, it prints the new line characters instead of going to the next line. So...

The Cards class, that just outlines the attributes of the objects:



		Code:
	

/********************************************
 * Outlines the fields of a card as well as *
 * defining methods to retrieve the fields. *
 ********************************************/
public class Cards
{
    private int cardNum;
    private String cardName;
    private String cardDesc;
    private String cardType;

    public Cards(int cardNum, String cardName, String cardDesc, String cardType){
        this.cardNum = cardNum;
        this.cardName = cardName;
        this.cardDesc = cardDesc;
        this.cardType = cardType;
    }
    
    public int getCardNum(){
        return cardNum;
    }
    
    public String getCardName(){
        return cardName;
    }
    
    public String getCardDesc(){
        return cardDesc;
    }
    
    public String getCardType(){
        return cardType;
    }
}


This is CardDecks that creates the array of Cards and reads off "cards.txt" to initialize the objects:



		Code:
	

import java.io.*;
import java.util.*;

/**************************************************************
 * Creates an array with all 25 of the special ability cards. *
 **************************************************************/
public class CardDecks
{
    private Cards[] deck;
    private File retrieveCards;
    private Scanner readFile, pressEnter;
    private Random rand;
    private int pickedCard, totalCards = 25;

    /******************************************************************
     * Open the "cards.txt" file, create the deck, and close the file *
     ******************************************************************/
    public CardDecks(){
        deck = new Cards[25];
        retrieveCards = new File("cards.txt");
        pressEnter = new Scanner(System.in);
        rand = new Random();
        openCardsFile();
        generateDeck();
        closeCardsFile();
    }
    
    /*******************************
     * Open the file, if it exists *
     *******************************/
    private void openCardsFile(){
        try{
            readFile = new Scanner(retrieveCards);
        }
        catch(Exception e){
            System.out.println("cards.txt file not found");
            pressEnter.nextLine();
            System.exit(0);
        }
    }
    
    /******************
     * Close the file *
     ******************/
    private void closeCardsFile(){
        readFile.close();
    }
        
    /************************************************************************
     * Uses the file to create each Card object with the appropriate fields *
     ************************************************************************/
    private void generateDeck(){
            for (int i = 0; i < deck.length; i++){
                deck[i] = new Cards(Integer.parseInt(readFile.nextLine()), readFile.nextLine(), readFile.nextLine(), readFile.nextLine());
            }  
    }
    
    /************************************************
     * Chooses a random card and returns it's index *
     ************************************************/
    public int randomCard(){
        pickedCard = rand.nextInt(26) - 1;
        return pickedCard;
    }
    
    /***************************************************************************
     * Get methods to return information about a card in the deck at index num *
     ***************************************************************************/
    public int getCardNum(int num){
        return deck[num].getCardNum();
    }
    
    public String getCardName(int num){
        return deck[num].getCardName();
    }
    
    public String getCardDesc(int num){
        return deck[num].getCardDesc();
    }
    
    public String getCardType(int num){
        return deck[num].getCardType();
    }
}


And this is the actual text file "cards.txt":



		Code:
	

1
+1 Attack
+1 Attack for next turn
Before Attack
2
+1 Attack
+1 Attack for next turn
Before Attack
3
+2 Attack
+2 Attack for next turn
Before Attack
4
+2 Attack
+2 Attack for next turn
Before Attack
5
+3 Attack
+3 Attack for next turn
Before Attack
6
+3 Attack
+3 Attack for next turn
Before Attack
7
+4 Attack
+4 Attack for next turn
Before Attack
8
+5 Attack
+5 Attack for next turn
Before Attack
9
+5 Health
Regain 5 Health
Before Attack
10
+5 Health
Regain 5 Health
Before Attack
11
+10 Health
Regain 10 Health
Before Attack
12
+10 Health
Regain 10 Health
Before Attack
13
+15 Health
Regain 15 Health
Before Attack
14
Parry
Player rolls against opponent attack.\nIf the player rolls higher, the oponent takes damage \ninstead equal to the player's roll
After Oponent Attack
15
Parry
Player rolls against opponent attack.\nIf the player rolls higher, the oponent takes damage \ninstead equal to the player's roll
After Oponent Attack
16
Block
Opponent's next attack does no damage
After Oponent Attack
17
Block
Opponent's next attack does no damage
After Oponent Attack
18
Steal Attack
Take an Attack bonus from the opponent\nand add it to your own Attack
Before Attack
19
Steal Health
Take a Health bonus from the opponent\nand add it to your own Health
Before Attack
20
Swap Health
You and the opponent swap all remaining health
Before Attack
21
Leech Health
You take 15 health from the opponent\nand add it to your own
Before Attack
22
Double Attack
Attack 2 times in one turn
Before Attack
23
Dodge
The oponent's attack only does half damage
After Oponent Attack
24
Reflect Attack
When the opponent attacks you, they\nalso recieve damage equal to half of their attack
After Oponent Attack
25
Revive
Play this card when you are killed to\ncome back to life with 15 Health
After Oponent Attack


And finally! the method I'm trying to use in MainGame to print the card info:



		Code:
	

public void drawSpecialCard(CardDecks deck)
    {
        int chosenCard = deck.randomCard();
        System.out.println("Player draws a special ability card:\n");
        System.out.println(" ------------------------------------------------------");
        System.out.println("|\t" + deck.getCardName(chosenCard));
        System.out.println("|\t" + deck.getCardDesc(chosenCard));
        System.out.println("|\tType: " + deck.getCardType(chosenCard));
        System.out.println(" ------------------------------------------------------\n");
    }


The problem is, when a record off the file is written to an object that has the "\n", it doesn't print properly.

So instead of going from:



		Code:
	

line1
line2
line3. \nAnother line


to 



		Code:
	

line1
line2
line3.
Another line


it prints



		Code:
	

line1
line2
line3. \nAnother line


----------



## NyxCharon

Try using a buffered reader.


----------



## Troncoso

NyxCharon said:


> Try using a buffered reader.



Care to say a bit more?


----------



## NyxCharon

Troncoso said:


> Care to say a bit more?



Yup, I'll give you a full example when I'm off work. I had a similar issue when i was writing a notepad like program, and using a buffered reader over a scanner worked to fix my problem. I'd write one out now, but I can't remember the exact code 

Edit: You are saying that it IS printing the "/n" character correct?


----------



## Troncoso

NyxCharon said:


> Yup, I'll give you a full example when I'm off work. I had a similar issue when i was writing a notepad like program, and using a buffered reader over a scanner worked to fix my problem. I'd write one out now, but I can't remember the exact code
> 
> Edit: You are saying that it IS printing the "/n" character correct?



It is printing the "\n" as in you see \n in the text, it doesn't cut to a new line. I used this to fix the issue though:



		Code:
	

if (deck.getCardDesc(chosenCard).length() > 38){
            if (deck.getCardDesc(chosenCard).length() > 76){
                wrapText1 = deck.getCardDesc(chosenCard).substring(0, 38);
                wrapText2 = deck.getCardDesc(chosenCard).substring(39, 76);
                wrapText3 = deck.getCardDesc(chosenCard).substring(77);
                System.out.println("| " + wrapText1 + "\n|   " + wrapText2 + "\n|   " + wrapText3);
            }
            else{
                wrapText1 = deck.getCardDesc(chosenCard).substring(0, 38);
                wrapText2 = deck.getCardDesc(chosenCard).substring(39);
                System.out.println("| " + wrapText1 + "\n|   " + wrapText2);
            }
        }
        else
            System.out.println("| " + deck.getCardDesc(chosenCard));


Not the neatness algorithm. But it does want I want it too. Thanks for the help though.


----------



## NyxCharon

Yea. I can still give you the example when I get back if you want?


----------



## Troncoso

That would be awesome. I'm still in the beginning stages of java, trying to learn as much as I can. I probably shouldn't have tried tackling a game so early, but it's actually going rather well.


----------



## Troncoso

What the heck is wrong with this? It's just suppose to take the array, and find the largest "span"(a span is the distance from one number to the next next duplicate. So an example:

{1,2,3,2,3,1} the largest span is 6 - from 1 to the next 1))

here is the code I thought would work:



		Code:
	

public class tests {;
	
	public static void main(String args[]){
		int largest = 0, end = 0;
		int[] nums = {1,2,1,1,3};
		int size = nums.length;
		  
		  for (int i = 0; i < size ; i++){
		       System.out.println(i);
		       System.out.println();
		       for (int j = 0; j < size ; i++){
		            if (nums[j] == nums[i]){
		            	end = j;
		                System.out.println(j);
		            }
		       }
		       if ((end - i + 1) > largest)
		            largest = (end - i) + 1;
		  }
		  System.out.println(largest);
	}
}


I put the print statements in there to show what values are being stored each time, which is always 0. and I keep getting this error:



		Code:
	

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
	at tests.main(tests.java:13)


Any help would be cool


----------



## NyxCharon

nums is of size 5. Arrays start at index 0, so when you try to access the number at slot 5, you cant because the biggest slot is 4. Hence, you get a error thrown. 

make it
int size = nums.length-1;


----------



## Troncoso

But when I use it in the for loop I say i< size, so it shouldn't try to aaccess a 5the element.


----------



## NyxCharon

figured it out, simple error. you had a i++ instead of a j++, so j never got incremented. 


		Code:
	

public static void main(String[] args) 
    {
       int largest = 0, end = 0;
		int[] nums = {1,2,1,1,3};
		int size = nums.length;
		  
		  for (int i = 0; i < size ; i++)
                  {
		       System.out.println(i);
		       System.out.println();
                           for (int j = 0; j < size ; j++)
                           {
                                if (nums[j] == nums[i])
                                {
                                    end = j;
                                    System.out.println(j);
                                }
                           }
		       if ((end - i + 1) > largest)
		            largest = (end - i) + 1;
		  }
		  System.out.println(largest);
	}


----------



## Troncoso

NyxCharon said:


> figured it out, simple error. you had a i++ instead of a j++, so j never got incremented.
> 
> 
> Code:
> 
> 
> public static void main(String[] args)
> {
> int largest = 0, end = 0;
> int[] nums = {1,2,1,1,3};
> int size = nums.length;
> 
> for (int i = 0; i < size ; i++)
> {
> System.out.println(i);
> System.out.println();
> for (int j = 0; j < size ; j++)
> {
> if (nums[j] == nums[i])
> {
> end = j;
> System.out.println(j);
> }
> }
> if ((end - i + 1) > largest)
> largest = (end - i) + 1;
> }
> System.out.println(largest);
> }



Haha. Oh man. How sad. At least I know that it was just an over sight. Thanks for the help


----------



## Bananapie

Troncoso said:


> Haha. Oh man. How sad. At least I know that it was just an over sight. Thanks for the help



Yeah, I was just reading your code and saw the mistake, haha. The chance to help someone out, and I am beat to it. 

How is your game coming along? I've been wanting to make a text based game for a while. I am relatively new as well, but I think it would be a blast just to write something up with no time limit or grade. Just need to figure out what I want to do exactly.


----------



## Troncoso

Bananapie said:


> Yeah, I was just reading your code and saw the mistake, haha. The chance to help someone out, and I am beat to it.
> 
> How is your game coming along? I've been wanting to make a text based game for a while. I am relatively new as well, but I think it would be a blast just to write something up with no time limit or grade. Just need to figure out what I want to do exactly.



Honestly, It's going a lot better than I thought. My usual experience with making anything, is having a really clear vision in my head of what I want and even detailed blue prints on how I'm gonna do it....but it never really turns out like I want.

This is an exception. So far, it's working just like I plan it to at each stage of production.

I urge you to go for it. I'm like you, I really enjoy programming when I'm programming what I want, and I don't have to finish by a certain date. As far as an idea is concerned, a lot come to you every day. Just get in the habit of thinking "hey, that would make a good program". That's what happened with me.


----------



## Bananapie

Troncoso said:


> Honestly, It's going a lot better than I thought. My usual experience with making anything, is having a really clear vision in my head of what I want and even detailed blue prints on how I'm gonna do it....but it never really turns out like I want.
> 
> This is an exception. So far, it's working just like I plan it to at each stage of production.
> 
> I urge you to go for it. I'm like you, I really enjoy programming when I'm programming what I want, and I don't have to finish by a certain date. As far as an idea is concerned, a lot come to you every day. Just get in the habit of thinking "hey, that would make a good program". That's what happened with me.



Yeah, I just need to get to it. It sounds amazing. Something I can build now and it be relatively well, and enjoyable, and expand on as I go. :good:

:edit: 
Definitely going to start brainstorming ideas for something to do for fun. So far, a kind of mix of Final Fantasy and other games, text based sounds most appealing at the moment. Not sure if I should plan to make it die(dice) based game or not. Would definitely make for something fun. Whether or not I am up to the skill level to do something of this sort, but basic, not sure. Worth the shot, and right now I am in the mood for a challenge. Given, it is only a side thing. Classes come first.


----------



## Troncoso

1 step at a time. I'm starting text based, because it's letting me concentrate on the game play mechanics. Final fantasy based(  if you are talking 1 and 2) would be really simple to start out with.


----------



## Bananapie

Troncoso said:


> 1 step at a time. I'm starting text based, because it's letting me concentrate on the game play mechanics. Final fantasy based(  if you are talking 1 and 2) would be really simple to start out with.



Yeah, one of the first couple, text based. Gives a lot of room later to add-on and whatnot. Definitely going to try and implement a character creation (Name/Gender/Race/Class and whatnot) to start. Then levels, stats/skills and such. Pretty basic stuff, but a lot to do. 

I figure that I have a lot of time left, why not do something that will last me.

I'm relatively new to programming in C++(which I plan to do the above in). I programmed previously in Java, which their syntax is close, but there is stuff that I am not entirely used to in C++ yet. Pointers and the sort, which this gives me reason to play with them.

Definitely not looking to do anything graphically any time soon. Just a clean cut text-based game, with the gameplay mechanics.  Just need to brainstorm movement of the game. Maybe a "Proceed to this destination in so-and-so moves" or a dice affiliated movement option. Get that and then do some kind of story/mission deal down the road.


----------



## zombine210

nice thread.

i'm just finishing through my first semester of Java. while i can't write something like this myself yet, i kind of understand what's going on in ya'll programs. it's pretty neat.

i also wanted to write a game, something simple like black jack.


----------



## Troncoso

if you've gone through a class (and actually learned the stuff), black jack won't be hard to accomplish (save if you want to build a GUI for it). I would try it, and if you really want to learn how to program, you'll find this will teach you more than anything.

I like classes on programming to learn syntax, semantics and what not, but when it comes to actual coding, you have to do it yourself to understand it.


----------



## ScottALot

This is supposed to use the Newtonian Method of finding which value of x makes f(x) = 0. The beginning creates random numbers for a6 through a0 so that the function is as follows:

f(x) = a6*x^6 + a5*x^5 ... a0*x^0

And the derivative is easy enough to figure out.

Newtonian's method a dynamic value of x that is represented as (x  in the function:

x: = x - f(x) / fprime(x)

The 'while' loop will continue looping until the value of f(x) (represented as double y) is less than the 0.001. In other words, it continues looping until it reaches a set accuracy. I did remember to set it so that f(x) is an absolute value so it doesn't loop more or less than it's supposed to.

The program works fine about half of the time, creating a valid approximation of x. However, the other half of the time, it goes into an infinite loop. I programmed this in an easy-teaching program/compiler/debugger called BlueJ, so the format may be a tad different.



		Code:
	

import java.util.*;

public class Newton
{
    public static void main(String [] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Scott Catlin (ScottALot)");
        System.out.println("Program v1.0.0");
        System.out.println("Bug Infested :D");
        System.out.println("Enter up to seven values for a[0] to a[6]. Input 0 for values you would not like to include.");
        System.out.println("All values can be easily edited in the source code. Simply replace the asix - azero values with your respective values.");
        double asix = Math.random();
        double afive = Math.random();
        double afour = Math.random();
        double athree = Math.random();
        double atwo = Math.random();
        double aone = Math.random();
        double azero = Math.random();
        System.out.println("");
        System.out.println(asix+"X^6 + "+afive+"X^5 + "+afour+"X^4 + "+athree+"X^3 + "+atwo+"X^2 + "+aone+"X^1 + "+azero+"X^0");
        System.out.println("");
        System.out.println("Enter in a random x-value");
        
        double x = input.nextDouble();
        double y = asix*Math.pow(x,6)+afive*Math.pow(x,5)+afour*Math.pow(x,4)+athree*Math.pow(x,3)+atwo*Math.pow(x,2)+aone*Math.pow(x,1)+azero*Math.pow(x,0);
        System.out.println("f("+x+") = "+y);
        double yprime = asix*Math.pow(x,6)+afive*Math.pow(x,5)+afour*Math.pow(x,4)+athree*Math.pow(x,3)+atwo*Math.pow(x,2)+aone*Math.pow(x,1)+azero*Math.pow(x,0);
        while (Math.abs(y)>0.001)
        {
            x = x-y/yprime;
            y = asix*Math.pow(x,6)+afive*Math.pow(x,5)+afour*Math.pow(x,4)+athree*Math.pow(x,3)+atwo*Math.pow(x,2)+aone*Math.pow(x,1)+azero*Math.pow(x,0);
            yprime = 6*asix*Math.pow(x,5)+5*afive*Math.pow(x,4)+4*afour*Math.pow(x,3)+3*athree*Math.pow(x,2)+2*atwo*Math.pow(x,1)+1*aone*Math.pow(x,0);
            System.out.println("f("+x+") = "+y);
        }
        System.out.println("");
        System.out.println("f(x) = 0 when x = approximately " + x);
        System.out.println("");
        System.out.print("Thank you for using my program. Improvements will be made in the future");
    }
}


NOTE: When I made azero = 1 or 0, it works 100% of the time... so maybe that's the source of the issue? I'd like to keep it random, but I might be having a dipshit moment with it.


----------



## Troncoso

ScottALot said:


> This is supposed to use the Newtonian Method of finding which value of x makes f(x) = 0. The beginning creates random numbers for a6 through a0 so that the function is as follows:
> 
> f(x) = a6*x^6 + a5*x^5 ... a0*x^0
> 
> And the derivative is easy enough to figure out.
> 
> Newtonian's method a dynamic value of x that is represented as (x  in the function:
> 
> x: = x - f(x) / fprime(x)
> 
> The 'while' loop will continue looping until the value of f(x) (represented as double y) is less than the 0.001. In other words, it continues looping until it reaches a set accuracy. I did remember to set it so that f(x) is an absolute value so it doesn't loop more or less than it's supposed to.
> 
> The program works fine about half of the time, creating a valid approximation of x. However, the other half of the time, it goes into an infinite loop. I programmed this in an easy-teaching program/compiler/debugger called BlueJ, so the format may be a tad different.
> 
> 
> 
> Code:
> 
> 
> import java.util.*;
> 
> public class Newton
> {
> public static void main(String [] args)
> {
> Scanner input = new Scanner(System.in);
> System.out.println("Scott Catlin (ScottALot)");
> System.out.println("Program v1.0.0");
> System.out.println("Bug Infested :D");
> System.out.println("Enter up to seven values for a[0] to a[6]. Input 0 for values you would not like to include.");
> System.out.println("All values can be easily edited in the source code. Simply replace the asix - azero values with your respective values.");
> double asix = Math.random();
> double afive = Math.random();
> double afour = Math.random();
> double athree = Math.random();
> double atwo = Math.random();
> double aone = Math.random();
> double azero = Math.random();
> System.out.println("");
> System.out.println(asix+"X^6 + "+afive+"X^5 + "+afour+"X^4 + "+athree+"X^3 + "+atwo+"X^2 + "+aone+"X^1 + "+azero+"X^0");
> System.out.println("");
> System.out.println("Enter in a random x-value");
> 
> double x = input.nextDouble();
> double y = asix*Math.pow(x,6)+afive*Math.pow(x,5)+afour*Math.pow(x,4)+athree*Math.pow(x,3)+atwo*Math.pow(x,2)+aone*Math.pow(x,1)+azero*Math.pow(x,0);
> System.out.println("f("+x+") = "+y);
> double yprime = asix*Math.pow(x,6)+afive*Math.pow(x,5)+afour*Math.pow(x,4)+athree*Math.pow(x,3)+atwo*Math.pow(x,2)+aone*Math.pow(x,1)+azero*Math.pow(x,0);
> while (Math.abs(y)>0.001)
> {
> x = x-y/yprime;
> y = asix*Math.pow(x,6)+afive*Math.pow(x,5)+afour*Math.pow(x,4)+athree*Math.pow(x,3)+atwo*Math.pow(x,2)+aone*Math.pow(x,1)+azero*Math.pow(x,0);
> yprime = 6*asix*Math.pow(x,5)+5*afive*Math.pow(x,4)+4*afour*Math.pow(x,3)+3*athree*Math.pow(x,2)+2*atwo*Math.pow(x,1)+1*aone*Math.pow(x,0);
> System.out.println("f("+x+") = "+y);
> }
> System.out.println("");
> System.out.println("f(x) = 0 when x = approximately " + x);
> System.out.println("");
> System.out.print("Thank you for using my program. Improvements will be made in the future");
> }
> }
> 
> 
> NOTE: When I made azero = 1 or 0, it works 100% of the time... so maybe that's the source of the issue? I'd like to keep it random, but I might be having a dipshit moment with it.



Are the 7 random numbers suppose to be whole numbers or can they be decimal values?


----------



## ScottALot

Troncoso said:


> Are the 7 random numbers suppose to be whole numbers or can they be decimal values?



Math.random() produces random numbers 0<=x<1, so decimals between 0 and 1.


----------



## Troncoso

Ah, well, I never use the Math class for random, there is actually a Random class you could use.

I don't know how well you know your way around Bluj, but it has a pretty extensive debugging mode. You need to find a set of data that gives you an infinite loop and hard code those numbers into your program. After that, you can set a break point at your while loop and keep stepping through it to see why it's not exiting the loop.


----------



## ScottALot

Teach me your ways.


----------



## Troncoso

ScottALot said:


> Teach me your ways.



Which ways are that?


----------



## ScottALot

Troncoso said:


> Which ways are that?



I meant teach me how to set up BlueJ so I can figure out why it's looping.


----------



## Troncoso

Ahh. Okay. Well, it's actually very simple. Once you've found a set of data that sends it into an infinite loop, hard code those numbers.

after you do that, on the line where your while loop starts, simply click in the white space to the left. It should create a little circle. That's your breakpoint. 






After that you simply run your program. When it gets to that while statement, it will stop, bring up the debugger window.





here, it'll show you the values of each variable as they are. From here, you press the "Step" button to go to the next line, after you press it each variable will update, if they have been changed. If you keeping doing this, you'll see why the values never meet the while loop condition.


----------



## Cromewell

Troncoso said:


> Ah, well, I never use the Math class for random, there is actually a Random class you could use.
> 
> I don't know how well you know your way around Bluj, but it has a pretty extensive debugging mode. You need to find a set of data that gives you an infinite loop and hard code those numbers into your program. After that, you can set a break point at your while loop and keep stepping through it to see why it's not exiting the loop.


Math.random() is actually creating an instance of the random class, it's just short cutting it and allows you to call nextInt, nextByte, nextXXXX...


ScottALot said:


> I meant teach me how to set up BlueJ so I can figure out why it's looping.


BlueJ is an option for a debugger, if you are using Eclipse as an IDE, it has a built in debugger you can use.


----------



## ScottALot

Cromewell said:


> Math.random() is actually creating an instance of the random class, it's just short cutting it and allows you to call nextInt, nextByte, nextXXXX...
> 
> BlueJ is an option for a debugger, if you are using Eclipse as an IDE, it has a built in debugger you can use.



I don't know what an IDE is... we're just learning how to create programs, so terms that might be common for people who learned to code outside of school.

EDIT: I know it means Integrated Development Environment... but that still means very little to me. It's like how the CIA is the Central Intelligence Agency; so, what, do they store all of the intelligence they can find into one center?


----------



## Cromewell

Think of using notepad and command line to build your program or Visual Studio (an IDE). Sure you can use notepad and enter commands into a prompt window, but having an IDE is easier and faster. They do other things as well, such as code completion (i.e. type ahead), syntax highlighing. And they typically have a built in debugger so you can step through your code and watch what it's doing


----------



## ScottALot

Cromewell said:


> Think of using notepad and command line to build your program or Visual Studio (an IDE). Sure you can use notepad and enter commands into a prompt window, but having an IDE is easier and faster. They do other things as well, such as code completion (i.e. type ahead), syntax highlighing. And they typically have a built in debugger so you can step through your code and watch what it's doing



Oh, so Eclipse, BlueJ, Notepad and more are different IDEs... got it!


----------



## Troncoso

ScottALot said:


> Oh, so Eclipse, BlueJ, Notepad and more are different IDEs... got it!



No. Eclipse and BlueJ are IDE's. Notepad is just a simple text editor.


----------



## Cromewell

The only thing I'd say about BlueJ is it's intended for use as a learning tool for object oriented programming in java to beginners. There's nothing wrong with it but you won't see it used outside of the education system.


----------



## Troncoso

Cromewell said:


> The only thing I'd say about BlueJ is it's intended for use as a learning tool for object oriented programming in java to beginners. There's nothing wrong with it but you won't see it used outside of the education system.



That's 100% true. That's all BlueJ is designed for. It really is excellent, though, for seeing how programs are working. The inspector, especially.


----------



## ScottALot

I've got Eclipse... any other stuff I should download to assist in programming?


----------



## Cromewell

Some projects will provide eclipse plugins, but if you just want to write code it has a lot of built in functionality that will help. Learning how to use the debugger will help a lot.

One thing to remember with eclipse is by default it will build your code automatically when you hit save so you don't have to search for how to compile.


----------



## Troncoso

I'm having some casting issues. I'm getting mixed results as to whether I can cast a super class to a sub class. Some say yeah you can, some say Java won't let you.

well, my code is simply:



		Code:
	

public void addGame(Game game, String typeGame){
        if (typeGame.equals("sugGame")){
            if (game instanceof SuggestionGame)
                SuggestionGame gameToAdd = (SuggestionGame) game;


But, when I try to compile, it tells me that the last line is not a complete statement....

Edit: Nevermind. I figured out a better way to do this that actually worked.


----------



## Troncoso

Got another question:

Is there some function in Java that would allow me to trigger a method when the respective object is returned by another method call?

Something like this:



		Code:
	

public void method() {
    Test test = sample.getSomething();


where getSomething() will return a Test object. 

When this happens I would like the test object to execute a method. Can I do that?


----------



## TrainTrackHack

> When this happens I would like the test object to execute a method. Can I do that?


Not the exact way you're thinking, no. What exactly are you trying to achieve? There's probably a better way to do whatever you're trying to do.


----------



## Troncoso

hackapelite said:


> Not the exact way you're thinking, no. What exactly are you trying to achieve? There's probably a better way to do whatever you're trying to do.



Well...that's what I'm trying to achieve...whenever I execute a method and a certain object is returned, I want that object to execute it's own method. 

What's going on, is, the user picks from a list of options, when they enter their choice, the object that is specified by that choice is returned, and printed on the screen via the toString() method.

Well, not only do I want that option to print it's toString method, but I also want to call another method. The object is created before hand, so putting it in the constructor wouldn't help.


----------



## TrainTrackHack

> What's going on, is, the user picks from a list of options, when they enter their choice, the object that is specified by that choice is returned, and printed on the screen via the toString() method.
> 
> Well, not only do I want that option to print it's toString method, but I also want to call another method. The object is created before hand, so putting it in the constructor wouldn't help.


Well you could just call the methods in the code where you're returning the object. I don' know how exactly you've set up your code (if you could post some, that would be helpful) but you could have something like



		Code:
	

Object methodThatReturnsObject() {
     Object object = theOneObjectYouWant;
     System.out.println(object);
     object.someOtheMethodYouWantToCall();
     return object;
}

So in this example methodThatReturnsObject would be triggered when the user enters a choice, and of course you'll need some code to make sure that theOneObjectYouWant corresponds to the choice the user made.


----------



## Troncoso

I'm a failure. Haha. What I did, was simply create a method within my superclass and then did an override in my subclasses so they all called what they were suppose to.

Instead of just printing the object, I set it equal to a variable, then printed it, then called that method.

Sorry to take you around like that, but at the very least, I got the idea from you.


----------



## mihir

I am planning to start android development. I need to get a book. Do you have any suggestions.I do not expect you to have used your suggested books, but if you know that the publisher/author is a good one that will do, also if some one else you know has used that book, that will also do.


----------



## mihir

Couldn't wait that long. Just drove out and got this for $7. Need to start with it this night.


----------



## Troncoso

Haha, You waited an hour, mate. Either way, is the book any good?


----------



## mihir

As a matter of fact I did not. I waited for five minutes and I got a reply from another source, as soon as I posted this. Got the book since I wanted cover some ground this night. It is exactly what I wanted. I also got some ebooks, for more examples. It is exactly what I wanted. It covers licensing and everything. Pretty good.Right now I am downloading Eclipse and Android SDK.


----------



## neilofbodom

Hi

I'm writing a program for a school project using JAVA on JCreator. it is a music trivia quiz and i'm currently working on the main menu. I imported these packages:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

The problem i encountered was when using the mouseClicked() method from the class MouseListener. I want the program to close when the user clicks on exit but it is not doing it. This is my code:

public void mouseClicked(MouseEvent e){
if (e.equals(exit)){
MainMenuWindow m = new MainMenuWindow();
m.setVisible(false);
}
}
Is there something wrong with the code or do i have to use some other commands?
Thanks

-neilofbodom


----------



## Troncoso

I don't understand what your code is doing. what is exit in



		Code:
	

if (e.equals(exit)){


?


----------



## neilofbodom

the 'exit' in the code is the button 'exit' that is displayed on the window

exit = new JButton("EXIT");


----------



## neilofbodom

i want the program to close if the user clicks on the exit button


----------



## Troncoso

ahhh, okay. Well if that's the case, shouldn't you just do



		Code:
	

if (e.equals(exit)){
     System.exit(0);
}


----------



## neilofbodom

i tried that but it didn't exit when i clicked the exit button. it didn't respond at all


----------



## NyxCharon

What is the exit? Are you referring to the top right corner exit button, or did you make your own? 

If it's the former, then you simply add 
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
to the class in which the JFrame is created.


----------



## neilofbodom

the exit button is a button i created myself. the program closes when the user clicks on the close button at the top right corner of the window. but i want the program to close when the user clicks on the exit button i created.


----------



## NyxCharon

Did you add the listener to the button?


----------



## neilofbodom

yes i added the mouse listener. the mouse clicked method is found in the mouse listener package


----------



## NyxCharon

Don't know what I was thinking earlier. You don't use a mouse listener man, you use a action listener. I wrote a quick app to show you how it works. Should compile fine for you.



		Code:
	

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author NyxCharon
 */
public class CloseButtonTest extends JFrame
{
    public CloseButtonTest()
    {
        JPanel pan=new JPanel();
        JButton exit=new JButton("Click to close");
        exit.addActionListener(new ExitListener());
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Close Test");
        setSize(60, 80);
        
        pan.add(exit);
        add(pan);
        
        setVisible(true);
        
        
    }
    
    //Action Listener, Fires when the button it is attached to is pressed. 
    class ExitListener implements ActionListener
	{
            public void actionPerformed(ActionEvent event)
            {
                System.exit(0);


            }
	}
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        CloseButtonTest run=new CloseButtonTest(); 
    }
}


----------



## neilofbodom

that's awesome man! thank you very much! one question tho, why can't you use the mouse listener? isn't it meant to do that?


----------



## TrainTrackHack

> that's awesome man! thank you very much! one question tho, why can't you use the mouse listener? isn't it meant to do that?


Mouse listeners are for tracking mouse actions such as clicking mouse buttons and wheel scrolling. However, clicking a button on you application is an "action" and you're supposed to use those listeners instead - that way using keyboard (using tab to select different buttons, space/enter to click) and different handedness is handled transparently without you doing anything about it. You could in theory use mouse listeners (can't tell why it didn't work in your particular case), but it's a lot harder and usually the result is glitchy on some systems. You generally use a mouse listener only if you want to register actions that the component doesn't support (such as clicking a panel or other non-button object) or you want to find out things like which exact button was pressed.


----------



## NyxCharon

neilofbodom said:


> that's awesome man! thank you very much! one question tho, why can't you use the mouse listener? isn't it meant to do that?



Hackapelite summed it up pretty well, but to expand, you could in theory still use one. However, The only way i could think that would work, is if on a mouse pressed/clicked event, you grabbed the coordinates, and then compared that to the area the button is in. Simply put, making a action listener simplifies all of this, so stick with that.


----------



## zombine210

mihir said:


> As a matter of fact I did not. I waited for five minutes and I got a reply from another source, as soon as I posted this. Got the book since I wanted cover some ground this night. It is exactly what I wanted. I also got some ebooks, for more examples. It is exactly what I wanted. It covers licensing and everything. Pretty good.Right now I am downloading Eclipse and Android SDK.



how's it going with this?
i just finished hello android using eclipse & AVD!
it's pretty cool. i don't know much java, and don't have any ideas for programs, but i'm in here; feels like i'm swimming with teh sharks.


----------



## Troncoso

So, for the first time I'm playing with GUI's in Java. I went the easy route and used WindowBuilder Pro in eclipse, rather than hard coding the entire interface. This is what I have:







Now, I have the JTextPane inside a JScrollingPane (on the right). What I would like is for the Scrolling Pane to auto-resize when the JFrame is re-sized. I've tried adding it to the panel's BorderLayout.Center, but that doesn't do anything. I try doing an event handler that checks that the Frame has been re-sized, but I run into an this error:



		Code:
	

Cannot refer to a non-final variable editor_scrPane inside an inner class defined in a different method


Here is the code I try:



		Code:
	

JScrollPane editor_scrPane = new JScrollPane();
		editor_scrPane.addHierarchyBoundsListener(new HierarchyBoundsAdapter() {
			@Override
			public void ancestorResized(HierarchyEvent e) {
				editor_scrPane.setSize(new Dimension());
			}
		});


I understand that code won't re-size properly, but the main focus is the fact that I can't reference the Scrolling Pane at all inside the event handler.


----------



## Cromewell

Try using 'this' instead of editor_scrPane.


----------



## Troncoso

Cromewell said:


> Try using 'this' instead of editor_scrPane.



Where?


----------



## Cromewell

Here:


		Code:
	

JScrollPane editor_scrPane = new JScrollPane();
		editor_scrPane.addHierarchyBoundsListener(new HierarchyBoundsAdapter() {
			@Override
			public void ancestorResized(HierarchyEvent e) {
				this.setSize(new Dimension());
			}
		});

though I'm not sure it will work, usually to do that you need to do exactly what the compiler told you, declare it as a final.


----------



## Troncoso

That doesn't work, but adding final does make the error go away.

Now, how will I actually account for the change in size of the window, to properly update the size of editor_scrPane?


----------



## Cromewell

Try passing the new height and width you want to the dimension yo uare creating. You'll have to figure out what they should be but that shouldn't be overly difficult. e.getChanged() will return the object which was resized.


----------



## neilofbodom

Hi, i'm working on a Java project as part of my a-level. I decided to create a music trivia quiz. I have encountered some problems in displaying the multiple choice answers using a JComboBox. The program reads the questions and answers from a text file I created separately. I think there is something wrong with my code. Is there anyone who would be willing to help me please? The code is quite long since it involves different classes so I won't paste it here. If anyone can help, i'll email the code.

Thank you very much 

-neilofbodom


----------



## Troncoso

neilofbodom said:


> Hi, i'm working on a Java project as part of my a-level. I decided to create a music trivia quiz. I have encountered some problems in displaying the multiple choice answers using a JComboBox. The program reads the questions and answers from a text file I created separately. I think there is something wrong with my code. Is there anyone who would be willing to help me please? The code is quite long since it involves different classes so I won't paste it here. If anyone can help, i'll email the code.
> 
> Thank you very much
> 
> -neilofbodom



You can go ahead and post the code here. Just be sure to use the "[COD E][/COD E]"
(No space before the E). 
That way, it'll restrict your code to a smaller window size.


----------



## neilofbodom

This is the code for the Main Menu Window. Depending on the user's choice, it calls another window.


		Code:
	

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MainMenuWindow extends JFrame implements MouseListener {

	private JButton start, exit;
	private JComboBox genreField;

	public MainMenuWindow() throws Exception{

		super("Main Menu");
		build();
	}

	public void build() throws Exception{
		this.setLayout(new BorderLayout());

		JPanel north = new JPanel(new FlowLayout(FlowLayout.CENTER));
		JLabel title = new JLabel("Main Menu- Music Trivia Quiz");
		title.setFont(new Font("Comic Sans",Font.BOLD,18));
		north.add(title);
		this.add(north,BorderLayout.NORTH);

		JPanel center = new JPanel(new GridLayout(1,1));

		JPanel genreLabelPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		JLabel genre = new JLabel ("Choose Genre: ");
		genreLabelPanel.add(genre);

		JPanel genrePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		String[] options = new String[3];
		options[0] = "Classical";
		options[1] = "Rock";
		options[2] = "Metal";
		for (int i = 0; i < options.length; i++){
			System.out.println(options[i]);
		}
		genreField = new JComboBox(options);
		genreLabelPanel.add(genreField);
		genrePanel.add(genreLabelPanel);
		genreField.addMouseListener(this);

		center.add(genreLabelPanel);
		center.add(genrePanel);

		this.add(center,BorderLayout.WEST);

		JPanel south = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		start = new JButton("START");
		start.setForeground(Color.WHITE);
		start.setBackground(Color.BLACK);

		exit = new JButton("EXIT");
		exit.setForeground(Color.WHITE);
		exit.setBackground(Color.BLACK);
		south.add(start);
		south.add(exit);
		start.addMouseListener(this);
		exit.addMouseListener(this);
		this.add(south,BorderLayout.SOUTH);

		north.setBackground(Color.BLACK);
		center.setBackground(Color.BLACK);
		south.setBackground(Color.BLACK);
		genreLabelPanel.setBackground(Color.BLACK);
		genrePanel.setBackground(Color.BLACK);
		this.setBounds(0,0,500,300);
		this.setResizable(false);
		this.setVisible(true);
	}

	public void mouseClicked(MouseEvent e){
		if (e.getSource().equals(start)){
			this.setVisible(false);
			String x = genreField.getSelectedItem().toString();
			if (x == "Rock"){
				StartRockWindow sr = new StartRockWindow();
				sr.setVisible(true);
			}else if (x == "Classical"){
				StartClassicalWindow sc = new StartClassicalWindow();
				sc.setVisible(true);
			}

		} else if (e.getSource().equals(exit)){
			this.setVisible(false);
		}
	}

	public void mouseEntered(MouseEvent e){

	}

	public void mouseExited(MouseEvent e){

	}

	public void mousePressed(MouseEvent e){

	}

	public void mouseReleased(MouseEvent e){

	}
}

/* That is the code for the main menu. The next code is for the Rock Window which opens if the user selects 'Rock' from the main menu. */

import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class StartRockWindow extends JFrame implements MouseListener{

	private JButton next, exit;
	private JComboBox choiceField;

	public StartRockWindow() throws Exception{
		super("Start Rock");
		build();
	}

	private void build() throws Exception{
		FileReader f = new FileReader("RockQuestions.txt");
  		BufferedReader br = new BufferedReader(f);
		String question = br.readLine();

		FileReader f1 = new FileReader("RockAnswers.txt");
		BufferedReader br1 = new BufferedReader(f1);
		String []choices = new String [60];

		for (int i = 0; i < 2; i++){
			choices[i] = br.readLine();
		}

		for (int i = 0; i < 20; i++){
			String q[] = new String[20];
			String a[] = new String[60];
			String[] choice = new String[3];

			this.setLayout(new BorderLayout());

			JPanel north = new JPanel(new FlowLayout(FlowLayout.CENTER));
			JLabel title = new JLabel("Rock Section");
			title.setFont(new Font("Comic Sans",Font.BOLD,18));
			north.add(title);
			this.add(north,BorderLayout.NORTH);

			JPanel center = new JPanel(new GridLayout(1,1));
			String x = "";

			switch (i){
				case 0: q[0] = question;
						a[0] = choices[0];
						a[1] = choices[1];
						a[2] = choices[2];
						if (x == a[0]){
							CorrectAnswerWindow ca = new CorrectAnswerWindow();
							ca.setVisible(true);
						} else {
							WrongAnswerWindow wa = new WrongAnswerWindow();
							wa.setVisible(true);
						}
						break;

			}


			JPanel question1LabelPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
			JLabel question1 = new JLabel ("Question "+(i+1)+": "+q[i]);
			question1LabelPanel.add(question1);

			JPanel choicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));


			for (int j = 0; j < choice.length; j++){
					choices[j] = choices[j];
			}

			choiceField = new JComboBox(choice);
			question1LabelPanel.add(choiceField);
			choicePanel.add(question1LabelPanel);
			choiceField.addMouseListener(this);

			center.add(question1LabelPanel);
			center.add(choicePanel);
			this.add(center,BorderLayout.WEST);

			JPanel south = new JPanel(new FlowLayout(FlowLayout.RIGHT));
			next = new JButton("NEXT");
			next.setForeground(Color.WHITE);
			next.setBackground(Color.BLACK);

			exit = new JButton("EXIT");
			exit.setForeground(Color.WHITE);
			exit.setBackground(Color.BLACK);
			south.add(next);
			south.add(exit);
			next.addMouseListener(this);
			exit.addMouseListener(this);
			this.add(south,BorderLayout.SOUTH);

			north.setBackground(Color.BLACK);
			center.setBackground(Color.BLACK);
			south.setBackground(Color.BLACK);
			question1LabelPanel.setBackground(Color.BLACK);
			choicePanel.setBackground(Color.BLACK);
			this.setBounds(0,0,500,300);
			this.setResizable(false);


			this.setVisible(true);
		}


	}

	public void mouseClicked(MouseEvent e) {
		if (e.getSource().equals(exit)){
			this.setVisible(false);
		} else if (e.getSource().equals(next)){
		}
	}

	public void mouseEntered(MouseEvent e){

	}

	public void mouseExited(MouseEvent e){

	}

	public void mousePressed(MouseEvent e){

	}

	public void mouseReleased(MouseEvent e){

	}

}


----------



## neilofbodom

My problem lies somewhere in the StartRockWindow class. I need to print on the window the question and a combo box containing the answers (multiple choice). It is printing the question but leaves the combo box empty. Any ideas?


----------



## Cromewell

Is there a reason a bunch of your methods throw a generic exception? Instead of catching it or throwing a more specific one?

Are you getting any exceptions in the console? I'm guessing that it's not finding your text file.


----------



## neilofbodom

Cromewell said:


> Is there a reason a bunch of your methods throw a generic exception? Instead of catching it or throwing a more specific one?
> 
> Are you getting any exceptions in the console? I'm guessing that it's not finding your text file.



I was getting exceptions so I decided to throw exceptions that way. I do not know how to do proper exception handling, i never understood them properly.

It finds the text file for the questions though because it displays them. I think it is finding the text file for the answers but it is not displaying them.


----------



## neilofbodom

Just want to let you know that i managed to solve the problem.
In the StartRockWindow class, the following line was incorrect: String []choices = new String [60];

It had to be: String []choices = new String [*3*];
 Also, the loop 
for (int i = 0; i < 2; i++){
			choices_ = br.readLine();
}

was combined with the other loop to get this:
for (int j = 0; j < choices.length; j++){
			choices[j] = br1.readLine();
			System.out.println(choices[j]);
}

thank you very much for you help anyway _


----------



## Cromewell

Good to hear you got it working.


neilofbodom said:


> I was getting exceptions so I decided to throw exceptions that way. I do not know how to do proper exception handling, i never understood them properly.
> 
> It finds the text file for the questions though because it displays them. I think it is finding the text file for the answers but it is not displaying them.


Exceptions are relatively easy to work with/understand. One is thrown when something doesn't work as intended. For files, it could be they weren't found, it was locked, etc. To handle them use try { code } catch (exceptionThatCodeThrows e) { code for when error occurs }

In your application, I think you are only dealing with IO exceptions, you always have them when dealing with files, but I haven't read through it all there may be another.


----------



## neilofbodom

Cromewell said:


> Good to hear you got it working.
> 
> Exceptions are relatively easy to work with/understand. One is thrown when something doesn't work as intended. For files, it could be they weren't found, it was locked, etc. To handle them use try { code } catch (exceptionThatCodeThrows e) { code for when error occurs }
> 
> In your application, I think you are only dealing with IO exceptions, you always have them when dealing with files, but I haven't read through it all there may be another.



Thanks Cromewell! i'll try it out


----------



## neilofbodom

In my code, I'm getting a nullPointerException. How is that caused and how can I solve it?
The code is as follows (there were some changes to my previous post):

private void build() throws Exception{
		FileReader f = new FileReader("RockQuestions.txt");
  		BufferedReader br = new BufferedReader(f);
		String question = br.readLine();

		FileReader f1 = new FileReader("RockAnswers.txt");
		BufferedReader br1 = new BufferedReader(f1);

		FileReader f2 = new FileReader("RockCorrectAnswers.txt");
		BufferedReader br2 = new BufferedReader(f2);
		correct = br2.readLine();

		for (int i = 0; i < 20; i++){
			String q[] = new String[20];
			String a[] = new String[60];
			String []choices = new String [3];

			this.setLayout(new BorderLayout());

			JPanel north = new JPanel(new FlowLayout(FlowLayout.CENTER));
			JLabel title = new JLabel("Rock Section");
			title.setFont(new Font("Comic Sans",Font.BOLD,18));
			north.add(title);
			this.add(north,BorderLayout.NORTH);

			JPanel center = new JPanel(new GridLayout(1,1));


			switch (i){
				case 0: q[0] = question;
						a[0] = choices[0];
						a[1] = choices[1];
						a[2] = choices[2];
						break;

			}


			JPanel question1LabelPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
			JLabel question1 = new JLabel ("Question "+(i+1)+": "+q_);
			question1LabelPanel.add(question1);

			for (int j = 0; j < 3; j++){
				choices[j] = br1.readLine();
				System.out.println(choices[j]);
			}

			JPanel choicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));


			choiceField = new JComboBox(choices);
			question1LabelPanel.add(choiceField);
			choicePanel.add(question1LabelPanel);
			choiceField.addMouseListener(this);

			x = choiceField.getSelectedItem().toString();

			center.add(question1LabelPanel);
			center.add(choicePanel);
			this.add(center,BorderLayout.WEST);

			JPanel south = new JPanel(new FlowLayout(FlowLayout.RIGHT));
			next = new JButton("NEXT");
			next.setForeground(Color.WHITE);
			next.setBackground(Color.BLACK);

			exit = new JButton("EXIT");
			exit.setForeground(Color.WHITE);
			exit.setBackground(Color.BLACK);
			south.add(next);
			south.add(exit);
			next.addMouseListener(this);
			exit.addMouseListener(this);
			this.add(south,BorderLayout.SOUTH);

			north.setBackground(Color.BLACK);
			center.setBackground(Color.BLACK);
			south.setBackground(Color.BLACK);
			question1LabelPanel.setBackground(Color.BLACK);
			choicePanel.setBackground(Color.BLACK);
			this.setBounds(0,0,500,300);
			this.setResizable(false);


			this.setVisible(true);
		}


	}

	public void mouseClicked(MouseEvent e) {
		if (e.getSource().equals(exit)){
			this.setVisible(false);
		} else if (e.getSource().equals(next)){
			if (x == correct){
				CorrectAnswerWindow ca = new CorrectAnswerWindow();
				ca.setVisible(true);
			} else {
				WrongAnswerWindow wa = new WrongAnswerWindow();
				wa.setVisible(true);
			}

		}
	}
The error lies in x = choiceField.getSelectedItem().toString();
Also, how can I compare 2 strings to see if they contain the same word? For example, if the correct answer is "ABC" but the user chose "DEF", how can I compare the 2 strings? 

Thanks in advance!_


----------



## Cromewell

A nullPointerException occurs when you try to use a null value when you need to use an object. Most often this happens if you try to do something like
ArrayList<String> abcd;
abcd.add("asdf");

instead of
ArrayList<String> abcd = new ArrayList<String>;
abcd.add("asdf");

Do you have an item selected in your combobox?

To compare strings use .equals(object) or .equalsIgnoreCase(object).


----------



## neilofbodom

Cromewell said:


> Do you have an item selected in your combobox?



Firstly, thank you very much for your reply. 

An item is selected by the user. The combobox has 3 options to choose from, 1 of which being correct.


----------



## Cromewell

Ok. Can you post up your text files? I don't need the full thing, just 1 complete question and answer.

edit: I'm also missing a bunch of classes. I've removed the StartClassicalWindow references but in StartRockWindow there are CorrectAnswerWindow and WrongAnswerWindow. It looks like I can safely remove them for now but if there are errors in them you may still get exceptions.

You have references to variables x and correct which have no declarations that I can find. That should be preventing your code from building. Is it possible there were other parts you changed but forgot to post?


----------



## neilofbodom

Cromewell said:


> Ok. Can you post up your text files? I don't need the full thing, just 1 complete question and answer.
> 
> edit: I'm also missing a bunch of classes. I've removed the StartClassicalWindow references but in StartRockWindow there are CorrectAnswerWindow and WrongAnswerWindow. It looks like I can safely remove them for now but if there are errors in them you may still get exceptions.
> 
> You have references to variables x and correct which have no declarations that I can find. That should be preventing your code from building. Is it possible there were other parts you changed but forgot to post?



RockQuestions.txt has:
Where was the band Led Zeppelin from?

RockAnswers.txt has:
England //this is the correct answer
Ireland
USA

You can ignore the StartClassicalWindow for now. 

CorrectAnswerWindow class:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class CorrectAnswerWindow extends JFrame implements MouseListener{

	private JButton cont;

	public CorrectAnswerWindow(){
		super("Correct Answer");
		build();
	}


	public void build(){

		this.setLayout(new BorderLayout());

		JPanel north = new JPanel(new FlowLayout(FlowLayout.CENTER));
		JLabel title = new JLabel("Music Trivia Quiz");
		title.setFont(new Font("Comic Sans",Font.BOLD,18));
		north.add(title);
		this.add(north,BorderLayout.NORTH);

		JPanel center = new JPanel(new FlowLayout(FlowLayout.CENTER));
		JLabel comment = new JLabel("CORRECT ANSWER! You get 2 points.");
		comment.setFont(new Font("Comic Sans", Font.BOLD, 28));
		center.add(comment);
		this.add(center,BorderLayout.CENTER);

		JPanel south = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		cont = new JButton("CONTINUE");
		cont.setForeground(Color.RED);
		cont.setBackground(Color.BLACK);
		south.add(cont);
		cont.addMouseListener(this);
		this.add(south,BorderLayout.SOUTH);
		this.setBounds(0,0,300,200);

		this.setVisible(false);
}

	public void mouseClicked(MouseEvent e) {
		if (e.getSource().equals(cont)){
			this.setVisible(false);
		}
	}

	public void mouseEntered(MouseEvent e){

	}

	public void mouseExited(MouseEvent e){

	}

	public void mousePressed(MouseEvent e){

	}

	public void mouseReleased(MouseEvent e){

	}
}

WrongAnswerWindow class:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class WrongAnswerWindow extends JFrame implements MouseListener{

	private JButton cont;

	public WrongAnswerWindow(){
		super("Wrong Answer");
		build();
	}


	public void build(){

		this.setLayout(new BorderLayout());

		JPanel north = new JPanel(new FlowLayout(FlowLayout.CENTER));
		JLabel title = new JLabel("Music Trivia Quiz");
		title.setFont(new Font("Comic Sans",Font.BOLD,18));
		north.add(title);
		this.add(north,BorderLayout.NORTH);

		JPanel center = new JPanel(new FlowLayout(FlowLayout.CENTER));
		JLabel comment = new JLabel("Wrong answer! You lose a point.");
		comment.setFont(new Font("Comic Sans", Font.BOLD, 28));
		center.add(comment);
		this.add(center,BorderLayout.CENTER);

		JPanel south = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		cont = new JButton("CONTINUE");
		cont.setForeground(Color.RED);
		cont.setBackground(Color.BLACK);
		south.add(cont);
		cont.addMouseListener(this);
		this.add(south,BorderLayout.SOUTH);
		this.setBounds(0,0,300,200);

		this.setVisible(true);
}

	public void mouseClicked(MouseEvent e) {
		if (e.getSource().equals(cont)){
			this.setVisible(false);
		}
	}

	public void mouseEntered(MouseEvent e){

	}

	public void mouseExited(MouseEvent e){

	}

	public void mousePressed(MouseEvent e){

	}

	public void mouseReleased(MouseEvent e){

	}
}

The MainMenuWindow class wasn't changed. I guess that's everything you need. Thank you very much, I really appreciate your help!  

Oh and StartRockWindow class also has this code which goes before the private void build() method:

import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class StartRockWindow extends JFrame implements MouseListener{

	private JButton next, exit;
	private JComboBox choiceField;
	public String x = new String();
	public String correct;

	public StartRockWindow() throws Exception{
		super("Start Rock");
		build();
	}


----------



## Cromewell

I'm seeing a few things now that I have all the code in Eclipse.

I know you aren't finished yet but your exit button doesn't really exit, it's just hiding the StartRockWindow and not reshowing the main window. There's a couple other things, the main one being instead of loading the choice into X during your build method you need to check what was picked when they click the next button otherwise it will always think they picked the first option.

As for the exception, you must not have 20 questions yet. You have a for loop in StartRockWindow (it's on line 35 for me, but I don't remember if I added/removed lines above it). It looks like for (int i = 0; i < 20; i++){ ... for now, change the 20 to the number of questions/answer sets you have. For the future, if you know it's 1 question per line, you could read the file for how many you have and loop that many times to initialize it. I would suggest building a question class instead of maintaining all those string arrays as well.


----------



## neilofbodom

Cheers! I managed to get rid of that exception and I solved the issue with the X and choice thing.

How do I exit the program then? I don't of any other way of exiting than what I wrote ie using .setVisible(false)

By the way, I am getting a problem when clicking on the next and exit buttons on the StartRockWindow. They are not responding. 

An update of the code:
//the code before this remained the same

private void build() throws Exception{
		FileReader f = new FileReader("RockQuestions.txt");
  		BufferedReader br = new BufferedReader(f);
		String question = br.readLine();

		FileReader f1 = new FileReader("RockAnswers.txt");
		BufferedReader br1 = new BufferedReader(f1);

		FileReader f2 = new FileReader("RockCorrectAnswers.txt");
		BufferedReader br2 = new BufferedReader(f2);
		correct = br2.readLine();

		for (int i = 0; i < 2; i++){
			String q[] = new String[20];
			String a[] = new String[60];
			String []choices = new String [3];

			this.setLayout(new BorderLayout());

			JPanel north = new JPanel(new FlowLayout(FlowLayout.CENTER));
			JLabel title = new JLabel("Rock Section");
			title.setFont(new Font("Comic Sans",Font.BOLD,18));
			north.add(title);
			this.add(north,BorderLayout.NORTH);

			JPanel center = new JPanel(new GridLayout(1,1));

			for (int j = 0; j < 3; j++){
				choices[j] = br1.readLine();
				System.out.println(choices[j]);
			}

			switch (i){
				case 0: q[0] = question;
						a[0] = choices[0];
						a[1] = choices[1];
						a[2] = choices[2];
						break;
				case 1: q[0] = question;
						a[3] = choices[0];
						a[4] = choices[1];
						a[5] = choices[2];
						break;
			}

			JPanel question1LabelPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
			JLabel question1 = new JLabel ("Question "+(i+1)+": "+q_);
			question1LabelPanel.add(question1);

			JPanel choicePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));


			choiceField = new JComboBox(choices);
			question1LabelPanel.add(choiceField);
			choicePanel.add(question1LabelPanel);
			choiceField.addMouseListener(this);

			center.add(question1LabelPanel);
			center.add(choicePanel);
			this.add(center,BorderLayout.WEST);

			JPanel south = new JPanel(new FlowLayout(FlowLayout.RIGHT));
			next = new JButton("NEXT");
			next.setForeground(Color.WHITE);
			next.setBackground(Color.BLACK);

			exit = new JButton("EXIT");
			exit.setForeground(Color.WHITE);
			exit.setBackground(Color.BLACK);
			south.add(next);
			south.add(exit);
			next.addMouseListener(this);
			exit.addMouseListener(this);
			this.add(south,BorderLayout.SOUTH);

			north.setBackground(Color.BLACK);
			center.setBackground(Color.BLACK);
			south.setBackground(Color.BLACK);
			question1LabelPanel.setBackground(Color.BLACK);
			choicePanel.setBackground(Color.BLACK);
			this.setBounds(0,0,500,300);
			this.setResizable(false);


			this.setVisible(true);
		}


	}

	public void mouseClicked(MouseEvent e) {
		if (e.getSource().equals(exit)){
			this.setVisible(false);
		} else if (e.getSource().equals(next)){
			x = choiceField.getSelectedItem().toString();
			if (x.equals(correct)){
				CorrectAnswerWindow ca = new CorrectAnswerWindow();
				ca.setVisible(true);
			} else {
				WrongAnswerWindow wa = new WrongAnswerWindow();
				wa.setVisible(true);
			}

		}
	}

	public void mouseEntered(MouseEvent e){

	}

	public void mouseExited(MouseEvent e){

	}

	public void mousePressed(MouseEvent e){

	}

	public void mouseReleased(MouseEvent e){

	}

}

Thanks Cromewell, you have been great help! _


----------



## Cromewell

The most correct way would be to use Window Listeners (http://docs.oracle.com/javase/tutorial/uiswing/events/windowlistener.html).

For now hiding the window will work, just make sure you show the old window so you can close it with the X or Alt-F4 or with a System.exit() button (not the cleanest way to close but it will end it) or you might have the process stuck running forever.

I'll update your code and step through it when I get a chance later tonight.


----------



## neilofbodom

Cromewell said:


> The most correct way would be to use Window Listeners (http://docs.oracle.com/javase/tutorial/uiswing/events/windowlistener.html).
> 
> For now hiding the window will work, just make sure you show the old window so you can close it with the X or Alt-F4 or with a System.exit() button (not the cleanest way to close but it will end it) or you might have the process stuck running forever.
> 
> I'll update your code and step through it when I get a chance later tonight.



I'll have a look at the Window Listeners. Sounds interesting.

Just to let you know, when I have just 1 question the program works perfectly but when I tried with 2 questions the buttons did not respond and the new question wasn't displayed on the window; the first question just stays there.

Thank you very much, Cromewell! I really appreciate it, you don't know how thankful I am for your generous help.


----------



## Cromewell

You are getting some weird behaviour from your UI controls. I added some dummy questions and answers to try and see what you were seeing.







Part of the problem is


		Code:
	

switch (i){
case 0: q[0] = question;
a[0] = choices[0];
a[1] = choices[1];
a[2] = choices[2];
break;
case 1: q[0] = question;
a[3] = choices[0];
a[4] = choices[1];
a[5] = choices[2];
break;
}


Just before the end of build, why are you setting the form to invisible? Removing that line makes the button respond (I get the you're wrong window popping up) but the questions and answers aren't matching up.

Trying to manage all the quesions at once which is causing you problems. Try writing a method which loads up the questions so that you can call it after the user answers a question. You can also use the method to load the first question and call it from the constructor.

edit:
Actually, I'm going to write up a quick class to show you a different way to read and store your questions. You'll need a helper to write the files but when done it will let you do things like have more than 3 possible answers.


----------



## Cromewell

So, I made a question class which looks like this:


		Code:
	

import java.io.Serializable;
import java.util.ArrayList;

public class Question implements Serializable { 
	private static final long serialVersionUID = 123456789;
	private String questionText;
	private ArrayList<String> answers;
	private String correctAnswer;
	
	public Question(String q, ArrayList<String> a, String correctA){
		questionText = q;
		answers = a;
		correctAnswer = correctA;
	}
	
	public String getQuestionText(){
		return questionText;
	}
	
	public String getCorrectAnswer(){
		return correctAnswer;
	}
	
	public String[] getAnswersArray(){
		return answers.toArray(new String[answers.size()]);
	}
	
	public ArrayList<String> getAnswers(){
		return answers;
	}
}

Because the class is serializable I can simply make some questions and write them to disk like this:


		Code:
	

//make up some questions
ArrayList<String> ans = new ArrayList<String>();
ArrayList<String> ans2 = new ArrayList<String>();
ArrayList<String> ans3 = new ArrayList<String>();
	
ans.add("England");
ans.add("USA");
ans.add("Ireland");
ans.add("France");
		
Question q1 = new Question("Where was the band Led Zepplin from?", ans, "England");

ans2.add("November Rain");
ans2.add("Sweet Child o' Mine");
ans2.add("Paradise City");
ans2.add("Welcome to the Jungle");
ans2.add("Patience");
ans2.add("Live and Let Die");
		
Question q2 = new Question("What was Guns n' Roses first single?", ans2, "Welcome to the Jungle");

ans3.add("Bon Scott");
ans3.add("Malcolm Young");
ans3.add("Angus Young");

Question q3 = new Question("Who was AC/DC's original lead singer?", ans3, "Bon Scott");

FileOutputStream fos = null; //create an output stream to write the objects to a file
ObjectOutputStream out = null;
try
{
	fos = new FileOutputStream("RockQuestions"); //RockQuestions can be any file name, I didn't include an extension but you could make it whatever you want
	out = new ObjectOutputStream(fos);
	out.writeObject(q1);
	out.writeObject(q2);
	out.writeObject(q3);
	out.close();
}
catch(IOException ex)
{
	ex.printStackTrace();
}

In this case, the defualt object writer from the Serializable interface will do what I want it to do but if you have a more complex object with special rules that need to be saved/read you can override the default writeObject and readObject methods. (http://docs.oracle.com/javase/1.4.2/docs/api/java/io/Serializable.html).

When it comes time to read the questions in, it's just as easy:


		Code:
	

FileInputStream fis = null;
ObjectInputStream in = null;
try
{
	fis = new FileInputStream("RockQuestions");
	in = new ObjectInputStream(fis);

	while (true){ //I couldn't find/remember how to check eof with the object reader so I'm relying on the eof exception being thrown to break out of here...
		questions.add((Question) in.readObject()); //need to cast the read object to the correct type
	}
}
catch(EOFException e){
	System.out.println("Reached EOF"); //this occurs when the entire file has been read
}
catch(IOException ex)
{
	ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
	ex.printStackTrace();
}
finally {
	if (in != null){ 
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	if (fis != null){
		try {
			fis.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

I've rewritten your StartRockWindow class to work with the changes, but I'm not going to give that to you, better to try it yourself


----------



## neilofbodom

I haven't had time to work on it so far as I've been busy the past couple of days. I'll have a proper look at what you told me in the weekend hopefully 

Thank you very much!


----------



## trewyn15

I have an assignment for class that I need help with, I'm pretty bad at Java but I have an idea of how to do it to an extent.  Can you guys read this and see if you can help me get a start?  No I don't want you to do my assignment for me, if you can write the full code and explain to me why it works that'd be awesome, but I'm more-so looking for someone to help me start off. 

Here it is:



> The assignment is to implement a text-based graphics program using composition,
> inheritance relationships and polymorphic behaviors (similar to the one we did in class
> together) to the one the author does in chapter 9 of the textbook.
> 
> We wish to produce a “shapes” taxonomy that would allow for a hierarchy of graphical
> objects; such as Points, Lines, Circles, Rectangles, Cylinders and Cubes to be “drawn”.
> In order to keep things simple, our drawing for this assignment will only amount to
> sending text out to the console (hence the term “Text Graphics” for our assignment).
> 
> Arrange these as classes in a hierarchy and associate drawing behavior with each class
> that is sensible to draw.  (The Shapes class, for instance, would be an abstract class since there’s no reasonable way to draw a generic shape.)  The drawing behavior for this
> assignment need only consist of text output to the console that states where the shape is and how it would draw itself (just as we did in the example from class).
> 
> In your implementation be sure to use both inheritance and composition where
> appropriate.  Remember, inheritance is called an “IS-A” relationship and composition is
> called a “HAS-A” relationship.  This rule-of-thumb design principle works for most
> simple taxonomies (such as this one).
> 
> You’ll also need to use polymorphism in your implementation (i.e. when implementing
> the draw() method) so that each shape draws itself appropriately when sent the
> draw() message.



Any help is appreciated, thanks guys!


----------



## Cromewell

I think the write up gives you a pretty good starting point. Start by making your shape class. Give it properties and methods that all shapes should have (such as the suggested draw, perhaps color is a good property that's common to all shapes).

Once that's done move on to one of the specific shapes. Make sure each shape has everything it needs so that you could draw it if you had to. A sphere might just have a center x/y and radius.

Don't worry about all the buzz words like polymorphism and what not. They will take care of themselves so long as you extend your shape object to make the sub-shapes.

Hopefully that helps a bit. I think all I really did was rehash the wording of your assignment


----------



## trewyn15

Cromewell said:


> I think the write up gives you a pretty good starting point. Start by making your shape class. Give it properties and methods that all shapes should have (such as the suggested draw, perhaps color is a good property that's common to all shapes).
> 
> Once that's done move on to one of the specific shapes. Make sure each shape has everything it needs so that you could draw it if you had to. A sphere might just have a center x/y and radius.
> 
> Don't worry about all the buzz words like polymorphism and what not. They will take care of themselves so long as you extend your shape object to make the sub-shapes.
> 
> Hopefully that helps a bit. I think all I really did was rehash the wording of your assignment



thanks for the rewording haha, i'm only in my second year of 'beginners java' I don't really understand how to go about this as far as code goes, this is the first time we've really worked with things that could product an image and the whole hierarchy thing confuses me.


----------



## Cromewell

Don't get hung up on how you would actually draw it, at this point it's unimportant.

The heirarchy is simple enough. The choice of words is probably the hardest thing to get around.

You start with


		Code:
	

public class shape {
 //methods and class member variables here.
}

and then your heirarchy is built by doing this:


		Code:
	

public class circle extends shape {
 //methods and class member variables here.
}

It's a lot easier than it sounds just the buzz can easily obscure what you need to do if you are new to the concepts.


----------



## trewyn15

okay, i think i'm kind of understanding where you're going with this, i'm not sure if i got this right...

I'm working on another way of this, i will post it when i'm done, so you can let me know if you think i should change anything



> public class shape
> {	// instance variable
> public String toString()
> {
> return name + " shapes";
> }
> 
> public static void main(String[] s)
> {	// create some objects...
> points = new Point("Point");
> lines = new Line("Line");
> circles = new Circle ("Circle");
> rectangles = new Rectangle("Rectangle");
> cylinders = new Cylinder("Cylinder");
> cubes = new Cube("Cube");
> shape = new points();
> 
> }
> }


----------



## trewyn15

starting to get it a little better, still having some compiling errors.



		Code:
	

import java.util.*;

class Line extends Shape {
	private Point start, end;
	private double width;
	protected String name;
	
	Line(String name, Point x, Point y, double w)
	{
		this.name = name;
		start = x;
		end = y;
		width = w;
	}
	
	public String toString() {
		return name + " starts at " + start + " to " + end + " of width = " + width;
	}
}
class fancyLine extends Line{
	private String drawType;
	
	fancyLine(String n, Point a, Point b, double w, String type)
	{
		super(n,a,b,w);
		drawType = type;
	}
	
	public String toString()
	{
		return super.toString() + " and is a " + drawType;
	}
}

class Point extends Shape{ //possibly extends line
	public int x, y, z;
	
	Point(int x, int y) {
	
		this.x = x;
		this.y = y;
	}
	
	Point(Point p) {
		this(p.x, p.y);
		
	}
	
	Point(int x, int y, int z){
		this.x = x;
		this.y = y;
		this.z = z;
	}
	
	public String toString()
	{
		return "(" + x + "," + y +")";
	}
	
}

class Circle extends Shape{ //possibly extend line
	protected double radius;
	protected double center;
	protected double name;
	protected double area;
	
	Circle(String name, Point p, double r) {
		center = p;
		radius = r;
		area = (3.14 * (radius * radius));
		this.name = name;
	}
	
	Circle(String n, Circle x) {
		this.center = center;
		this.radius = radius;
		area = (3.14 * (radius * radius));
		n = name;
	}
	
	public double getArea()
	{
		return Math.PI * Math.pow(radius, 2);
	}
	
	public String toString()
	{
		return name + " originates at " + center + " extends for a radius of " + radius + "the original circles has an area of " + area;
	}
}

class Cylinder extends Circle{
	private int height;
	private Point cylCenter;
	private double cylRadius;
	
	Cylinder(String n, Point x, double r, int h){
		super(n, x, r);
		height = h;
		cylCenter = x;
		cylRadius = r;
		name = n;
	}
	
	Cylinder(String n, Circle x, int h){
		super(n, x, r);
		height = h;
		cylCenter = x;
		cylRadius = r;
		name = n;
	}
		
		public String toString()
		{
			return name + " originates at " + cylCenter + " with a radius of " + cylRadius + " with a height of " + height;
		}
	}	
	
	class Rectangle extends Shape {
		protected Point one, two, three, four;
		protected int height;
		protected String name;
		
	Rectangle(String n, Point start, Point width, Point top){
		name = n;
		one = start;
		two = width;
		three = top;
		
		height = getValy(three) - getValy(one);
		
	}
	
	int getValx (Point x) {
		return x.x;
	}
	
	int getValy (Point y) {
		return y.y;
	}
	
	public String toString()
	{
		return name + " originates at " + one + " its second point is " + two + " and has a height of " + height;
	}
}

class Cube extends Rectangle {
	private int depth;
	
	Cube(String n, Point start, Point width, Point top, int depth) {
		super(n, start, width, top);
		this.depth = depth;
	}
}

abstract class Shape {
	static ArrayList<Shape> container = new ArrayList<Shape>();
	
	public static void main(String args[]) {
		//define the points
		Point origin = new Point (0,0);
		Point twoTwo = new Point (2,2);
		Point twoZero = new Point (2,0);
		Point fourFour = new Point (4,4);
		Point fiveFive = new Point (5,5);	
		Point sixSix = new Point (6,6);
		Point eightEight = new Point (8,8);
		Point zeroZeroFive = new Point (0,0,5);
		Line lineOne = new Line("Line One", origin, twoTwo, 2.1);
		container.add(lineOne); //line
		Line lineTwo = new fancyLine("Line Two", origin, twoTwo, 2.1, "Fancy");
		container.add(lineTwo); //fancy line
		Circle circleOne = new Circle("Circle One", twoTwo, 3.1);
		container.add(circleOne); //circle
		Cylinder cylOne = new Cylinder("Cylinder One", circleOne, 5);
		container.add(cylOne); //cylinder
		Cylinder cylTwo = new Cylinder("Cylinder Two", twoTwo, 3.1, 5);
		container.add(cylTwo); //cylinder method two
		Rectangle recOne = new Rectangle("Rectangle One", origin, twoZero, twoTwo);
		container.add(recOne); //rectangle
		Cube cubeOne = new Cube("Cube One", origin, twoZero, twoTwo, 2);
		container.add(cubeOne); //cube
		
		for (Shape a : container)
			System.out.println(a + " ");
	}
}


----------



## Cromewell

Yeah, that's basically it. Don't forget that your instructions require the draw method to be declared in shape and then you implement it in your specific shapes. You pretty much have it done already but you called it toString instead of draw  It mentions something about how you did it in class, obviously I don't know what that looked like but mimicing it is probably a good idea


----------



## trewyn15

Thanks for the help, I'm back with some more personal problems haha

We have a take home final and I don't understand what the following questions mean, I think some of it is the way he words it and the other part is my lack of knowledge of java in general.  Here are the questions, hopefully you can help 

1.
Show, by way of example and descriptions, how inheritance works to allow “specializing” an existing class to extend method behavior by “piggybacking” on existing code, rather than having to copy and paste it into the new class.

2.
Show, by way of example and descriptions, how composition works in Java to allow a “subobject” to be stored as an instance variable inside another object.  Also, show in your example how the subobject’s data are accessed.  Write getter and setter methods for your class.


----------



## Troncoso

trewyn15 said:


> Thanks for the help, I'm back with some more personal problems haha
> 
> We have a take home final and I don't understand what the following questions mean, I think some of it is the way he words it and the other part is my lack of knowledge of java in general.  Here are the questions, hopefully you can help
> 
> 1.
> Show, by way of example and descriptions, how inheritance works to allow “specializing” an existing class to extend method behavior by “piggybacking” on existing code, rather than having to copy and paste it into the new class.
> 
> 2.
> Show, by way of example and descriptions, how composition works in Java to allow a “subobject” to be stored as an instance variable inside another object.  Also, show in your example how the subobject’s data are accessed.  Write getter and setter methods for your class.



1. is asking you to explain how inheritance allows you to create classes for a more specific purpose, but based on more general classes. Like in the Scientific species tree thing.

order > family > genus > species

Each step further gets more detailed and more specific about the type of living things in that category. In this case, you would write an Order class that had characteristics of anything in that Order. Then you would create a Family class that extends Order, but also include characteristics of creatures only in that family, and so on.

That's the best I can explain it.

The second, I'm not so sure on.


----------



## trewyn15

Troncoso said:


> 1. is asking you to explain how inheritance allows you to create classes for a more specific purpose, but based on more general classes. Like in the Scientific species tree thing.
> 
> order > family > genus > species
> 
> Each step further gets more detailed and more specific about the type of living things in that category. In this case, you would write an Order class that had characteristics of anything in that Order. Then you would create a Family class that extends Order, but also include characteristics of creatures only in that family, and so on.
> 
> That's the best I can explain it.
> 
> The second, I'm not so sure on.



so how would i change this to do what he asks?  this is just a 3 level hierarchy of inheritance, i just don't understand what he wants us to do further



		Code:
	

import java.util.ArrayList;

public class Speaker
{  //instance variable
	protected String name;
	public String toString()
	{
		return name + " beats";
	}
	
	public static void main(String[] s)
	{  //creates the types of speakers
		Component alpine = new Sub("Alpine");
		//add those speakers to a container
		ArrayList<Speaker> speakers = new ArrayList<Speaker>();
		speakers.add(alpine);
		//print the above speakers to the console
		for (Speaker a : speakers)
			System.out,print(a + " ");
	}
}

abstract class Component extends Speaker

class Sub extends Component
{
	Sub(String s)
	{ name = s;
	}
	//print representation
	public String toString()
	{
		return name + " makes a bass noise";
	}
}


----------



## Troncoso

trewyn15 said:


> so how would i change this to do what he asks?  this is just a 3 level hierarchy of inheritance, i just don't understand what he wants us to do further
> 
> 
> 
> Code:
> 
> 
> import java.util.ArrayList;
> 
> public class Speaker
> {  //instance variable
> protected String name;
> public String toString()
> {
> return name + " beats";
> }
> 
> public static void main(String[] s)
> {  //creates the types of speakers
> Component alpine = new Sub("Alpine");
> //add those speakers to a container
> ArrayList<Speaker> speakers = new ArrayList<Speaker>();
> speakers.add(alpine);
> //print the above speakers to the console
> for (Speaker a : speakers)
> System.out,print(a + " ");
> }
> }
> 
> abstract class Component extends Speaker
> 
> class Sub extends Component
> {
> Sub(String s)
> { name = s;
> }
> //print representation
> public String toString()
> {
> return name + " makes a bass noise";
> }
> }



You have your example, now you need to explain how your code is specializing each level in the hierarchy through re-using code, as opposed to hard coding all 3 classes.

It is against the rules for us to just give you the answer, but I can keep trying to explain it until you understand.


----------



## trewyn15

i think i have figure that one out, i am having an issue with this code tho, i'm not sure if it's complete for what the question is.

3.	Show, by way of example and descriptions, how composition works in Java to allow a “subobject” to be stored as an instance variable inside another object.  Also, show in your example how the subobject’s data are accessed.  Write getter and setter methods for your class.



		Code:
	

class Fruit {
	private in age = 0;
	private String ripeness = ripe;
	public void setRipeness(String ripeness){
		this.ripeness = ripeness;}
	public void getAge() {
		return age}  

}

class Apple {
	private Fruit b = new Fruit(fruit);
	
}


thanks for the help so far!


----------



## Troncoso

Okay, I'm stuck on how to proceed with this issue in an efficient manner. (This is not school work, by the way). But, what I want to do, is take a 7 digit phone number, and list all the possible letter combinations that it can make (based on the dial pad of a regular phone). So, each number corresponds to 3 possible letters:

2 - abc
3 - def
4 - ghi
5 - jkl
6 - mno
7 - prs
8 - tuv
9 - wxy

(I know that the Q and the Z are missing)

So, say I get the number 734-5735, then the first String I could make would be PDGJPDJ.
I'm assuming no number has a 0 or 1.

So, I have this code:



		Code:
	

// numbers is a Character[] ArrayList
public void fillLetters() {
        Character[] n2 = {'a', 'b', 'c'};
        numbers.add(n2);
    
        Character[] n3 = {'d', 'e', 'f'};
        numbers.add(n3);
        
        Character[] n4 = {'g', 'h', 'i'};
        numbers.add(n4);
        
        Character[] n5 = {'j', 'k', 'l'};
        numbers.add(n5);
        
        Character[] n6 = {'m', 'n', 'o'};
        numbers.add(n6);
        
        Character[] n7 = {'p', 'r', 's'};
        numbers.add(n7);
        
        Character[] n8 = {'t', 'u', 'v'};
        numbers.add(n8);
        
        Character[] n9 = {'w', 'x', 'y'};
        numbers.add(n9);
    }
    
    public void writeToFile(int[] nums) {
        int number = 0, letter = 0;
        
        // This is just a place holder. I imagine this format will work 
        // If I can find a way to properly increment through each number and letter
        while (true) {
            for (int i = 0; i < nums.length; i++) {
                pStream.print((char) (numbers.get(i - 2)[letter] - 32));
                System.out.print((char) (numbers.get(i - 2)[letter] - 32));
            }
            pStream.println();
            System.out.println();
        }
    }


All it does so far is print the first String. I can't think of how to make it loop in a way that it will print all 3^7 possible combinations. Any suggestions?

Also, I want it printing to a text file, but I don't feel like opening it every time I run it, so that's what the println's are for.


----------



## NyxCharon

Troncoso said:


> Okay, I'm stuck on how to proceed with this issue in an efficient manner. (This is not school work, by the way). But, what I want to do, is take a 7 digit phone number, and list all the possible letter combinations that it can make (based on the dial pad of a regular phone).



We just did a problem like this in my CS class, but I can not for the life of me remember how we did it. I do remember two being used arrays, and it was recursive. I'll see if I can find the example posted online.


----------



## Troncoso

NyxCharon said:


> We just did a problem like this in my CS class, but I can not for the life of me remember how we did it. I do remember two being used arrays, and it was recursive. I'll see if I can find the example posted online.



Can you clarify what you mean by "two being used arrays". And thanks in advance if you can find it.


----------



## NyxCharon

Troncoso said:


> Can you clarify what you mean by "two being used arrays". And thanks in advance if you can find it.



meant to say, two arrays being used. 

anyways, you're going to have to mod it for your own use obviously, but it might be of some use to you.


		Code:
	

import java.util.*;

public class Permutation {

	public ArrayList<String> getPerms(String s) {

		ArrayList<String> list = new ArrayList<String>();
		if (s.length() == 1)
			list.add(s);
		else {
			for (int i = 0; i < s.length(); i++) {
				char x = s.charAt(i);
				String y = "";
				for (int j = 0; j < s.length(); j++) {
					if (i != j)
						y += s.charAt(j);
				}
				ArrayList<String> results = getPerms(y);
				for (String sf : results) {
					list.add(x + sf);
				}

			}
		}
		return list;

	}

	public static void main(String[] ar) {
		for (String s : new Permutation().getPerms("abcdefg")) {
			System.out.println(s);
		}
	}
}


----------



## Troncoso

NyxCharon said:


> meant to say, two arrays being used.
> 
> anyways, you're going to have to mod it for your own use obviously, but it might be of some use to you.
> 
> 
> Code:
> 
> 
> import java.util.*;
> 
> public class Permutation {
> 
> public ArrayList<String> getPerms(String s) {
> 
> ArrayList<String> list = new ArrayList<String>();
> if (s.length() == 1)
> list.add(s);
> else {
> for (int i = 0; i < s.length(); i++) {
> char x = s.charAt(i);
> String y = "";
> for (int j = 0; j < s.length(); j++) {
> if (i != j)
> y += s.charAt(j);
> }
> ArrayList<String> results = getPerms(y);
> for (String sf : results) {
> list.add(x + sf);
> }
> 
> }
> }
> return list;
> 
> }
> 
> public static void main(String[] ar) {
> for (String s : new Permutation().getPerms("abcdefg")) {
> System.out.println(s);
> }
> }
> }



So this is pretty much taking a string of characters and returning every possible order you could put them in?
Not exactly what I'm doing, but I could definitely see that as an approach to my problem.


----------



## Cromewell

You are missing some letters (Q and Z), but that may be intentional.

My first thought was I would probably approach this with a jagged array. The index of first level is the number pressed - 1 (0 indexed) and then you just need to figure out the recursion to loop through each segment to get all combinations.

The array would be like:


		Code:
	

Character keypad = {{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}}

And the recursion (you could probably do it with some loops and some cleverness), I'll leave to you


----------



## Troncoso

Cromewell said:


> You are missing some letters (Q and Z), but that may be intentional.
> 
> My first thought was I would probably approach this with a jagged array. The index of first level is the number pressed - 1 (0 indexed) and then you just need to figure out the recursion to loop through each segment to get all combinations.
> 
> The array would be like:
> 
> 
> Code:
> 
> 
> Character keypad = {{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}}
> 
> And the recursion (you could probably do it with some loops and some cleverness), I'll leave to you



Yeah, I mentioned that they were intentionally left out. The recursion is what's throwing me off. I understand it, but it's a strange subject and I find it hard to work with, especially with something like this.


----------



## Cromewell

Troncoso said:


> Yeah, I mentioned that they were intentionally left out. The recursion is what's throwing me off. I understand it, but it's a strange subject and I find it hard to work with, especially with something like this.



Sorry I missed that in your original post. I have an idea of how to make it work but I need to get my dev machine running, hopefully I'll post back shortly.


----------



## Troncoso

Cromewell said:


> Sorry I missed that in your original post. I have an idea of how to make it work but I need to get my dev machine running, hopefully I'll post back shortly.



That would be really cool. Anything and everything around this is no issue so far, but I can't continue until I've done this much. haha.


----------



## Cromewell

I keep getting hung up on the wrong approach, everytime I try to change it I end up with a longer batch of code that is the same junk I got rid of. I know exactly what I need to do but for some reason I can't put it into code correctly.

I'm going to have to come back to this or I might go crazy. Sometimes sleeping on it helps a lot. You come back and are like 'what was I thinking this is easy.'


----------



## Troncoso

Cromewell said:


> I keep getting hung up on the wrong approach, everytime I try to change it I end up with a longer batch of code that is the same junk I got rid of. I know exactly what I need to do but for some reason I can't put it into code correctly.
> 
> I'm going to have to come back to this or I might go crazy. Sometimes sleeping on it helps a lot. You come back and are like 'what was I thinking this is easy.'



I've tried that a couple times. Haha. But it's still throws me for a loop.


----------



## NyxCharon

Is this what you're looking for?


		Code:
	

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author NyxCharon
 */
public class Telephone 
{
    private static final String[][] maps = 
    {{"0"},{"1"},
    {"A","B","C"}, 
    {"D","E","F"}, 
    {"G","H","I"},
    {"J","K","L"}, 
    {"M","N","O"}, 
    {"P","R","S"},
    {"T","U","V"}, 
    {"X","Y","W"}};
   

  

    public static List getConditions(String number) 
    {
        if (number.startsWith("0") || number.startsWith("1")) {
            return new ArrayList();
        }

        List list = new ArrayList();

        int[] arr = new int[number.length()];
        for (int j = 0; j < arr.length; j++) {
            arr[j] = Integer.parseInt(String.valueOf(number.charAt(j)));
        }
        combine("", arr, 0, list);
        return list;
    }

    public static void combine(String a, int[] number, int current,List list) 
    {
        for (int k = 0; k < maps[number[current]].length; k++) 
        {
            if (current == number.length - 1) 
                 list.add(a + maps[number[current]][k]);
            else 
                combine(a + maps[number[current]][k], number, current + 1,list);
        }
    }
    public static void main(String[] args)
    {
        List l=getConditions("4456789");
        for(int i=0;i<l.size();i++)
            System.out.println(l.get(i));
    }
}


----------



## Cromewell

Yeah that's like what I was trying to do. For some reason I kept making a bunch of for loops even through I knew it was wrong. And if you add typing to your list it wont generate compiler warnings


----------



## Troncoso

NyxCharon said:


> Is this what you're looking for?
> 
> 
> Code:
> 
> 
> import java.util.ArrayList;
> import java.util.List;
> 
> /**
> *
> * @author NyxCharon
> */
> public class Telephone
> {
> private static final String[][] maps =
> {{"0"},{"1"},
> {"A","B","C"},
> {"D","E","F"},
> {"G","H","I"},
> {"J","K","L"},
> {"M","N","O"},
> {"P","R","S"},
> {"T","U","V"},
> {"X","Y","W"}};
> 
> 
> 
> 
> public static List getConditions(String number)
> {
> if (number.startsWith("0") || number.startsWith("1")) {
> return new ArrayList();
> }
> 
> List list = new ArrayList();
> 
> int[] arr = new int[number.length()];
> for (int j = 0; j < arr.length; j++) {
> arr[j] = Integer.parseInt(String.valueOf(number.charAt(j)));
> }
> combine("", arr, 0, list);
> return list;
> }
> 
> public static void combine(String a, int[] number, int current,List list)
> {
> for (int k = 0; k < maps[number[current]].length; k++)
> {
> if (current == number.length - 1)
> list.add(a + maps[number[current]][k]);
> else
> combine(a + maps[number[current]][k], number, current + 1,list);
> }
> }
> public static void main(String[] args)
> {
> List l=getConditions("4456789");
> for(int i=0;i<l.size();i++)
> System.out.println(l.get(i));
> }
> }



I love you and I hate you. Haha. That's exactly what I need. But, gah. That freaking recursion. I just can't get a handle on it enough to implement it.
Like, I understand what it is and how to use it. But I have a hard time envisioning how it's going to produce the results I want.

Though, I didn't need the 0 or 1 check at the beginning. It's assumed that those will never be entered. But, that's a simple fix. I really appreciate this. I've been racking my brain for a couple days now.


----------



## Dan-987

Struggling Programming Student - Advice/support needed.

Hi Guys,

Havent really used this forum much, just wanted to bring up a personal problem thats been hanging over me. Basically I have fallen majorly behind on my programming course. I know some programming basics like classes, objects, variables, methods, loops. However due to some personal issues fell behind, the class are now on Inheritance and GUI's.

I have exams on this in about 8 weeks time, do you reckon it would be possible for someone with no/very little programming knowledge to catch up in about 6-7 weeks. If I do about 10-15 hours a week?

Some support/backing from people who know what they are talking about, or been in a similar position please respond asap. Advice and comments would really help me out.

Many thanks,
Dan


----------



## Troncoso

Dan-987 said:


> Struggling Programming Student - Advice/support needed.
> 
> Hi Guys,
> 
> Havent really used this forum much, just wanted to bring up a personal problem thats been hanging over me. Basically I have fallen majorly behind on my programming course. I know some programming basics like classes, objects, variables, methods, loops. However due to some personal issues fell behind, the class are now on Inheritance and GUI's.
> 
> I have exams on this in about 8 weeks time, do you reckon it would be possible for someone with no/very little programming knowledge to catch up in about 6-7 weeks. If I do about 10-15 hours a week?
> 
> Some support/backing from people who know what they are talking about, or been in a similar position please respond asap. Advice and comments would really help me out.
> 
> Many thanks,
> Dan



Your original thread was fine. This thread is for specific Java programming help.


----------



## massahwahl

I apologize if its already been asked, but if I were interested in learning how to code java are there any sites you guys recommend?


----------



## Troncoso

massahwahl said:


> I apologize if its already been asked, but if I were interested in learning how to code java are there any sites you guys recommend?



thenewboston.com

That links to thenewboston's beginner Java tutorials. On the site, you will also find advanced and game oriented tutorials. Not to mention several for other languages.


----------



## zombine210

Troncoso said:


> thenewboston.com
> 
> That links to thenewboston's beginner Java tutorials. On the site, you will also find advanced and game oriented tutorials. Not to mention several for other languages.



thenewboston videos are ok to review material you already know, but useless beyond that. the guy is not a very good teacher, he uses unconventional identifier names, rarely uses correct terminology, and is overall mediocre. i did watch about 40+ of his videos, so i know.


----------



## Troncoso

zombine210 said:


> thenewboston videos are ok to review material you already know, but useless beyond that. the guy is not a very good teacher, he uses unconventional identifier names, rarely uses correct terminology, and is overall mediocre. i did watch about 40+ of his videos, so i know.



Yeah, I've watched his videos too, and I learned a lot from them. 
Yeah, he's not very conventional, but he knows his stuff and he explains it well. I guess it's just a matter of opinion, but a lot of people appreciate what he does and learns well from it.


----------



## Troncoso

I'm playing with threads. This program is suppose to add/subtract a random number until the total is exactly 1000. Though, because of the nature of threads, the output is in correct, and sometimes it stops on something besides 1000. How would I fix that?

Source code:



		Code:
	

import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;

import java.util.Random;
import java.util.Scanner;

public class Threads {

    public static void main(String[] args) { 
       new Threads().go();
    }
    
    int number;
    
    public Threads() {
        number = 0;
    }
    
    public void go() {
        ExecutorService ex = Executors.newCachedThreadPool();
        Calc calc1 = new Calc(1);
        Calc calc2 = new Calc(2);
        Calc calc3 = new Calc(3);
        
        System.out.println ("This program adds and subtracts randomly.");
        System.out.println ("It ends when it calculates 1000.");
        System.out.println ("Press enter to start.\n");
        new Scanner(System.in).nextLine();
       
        while (number != 1000) {
            ex.execute(calc1);
            ex.execute(calc2);
            ex.execute(calc3);        
        }
        
        ex.shutdown();
    }
    
    private class Calc implements Runnable{
        int name;
        
        public Calc(int name) {
            this.name = name;
        }
                
        public synchronized void run() {
            Random rand = new Random (System.currentTimeMillis());
            int num = rand.nextInt(99) + 1;
            if (Threads.this.number < 1000) {
                Threads.this.number += num;
                System.out.printf ("Player %d adds %d to get %d\n", name, num, Threads.this.number);
            }
            else if (Threads.this.number > 1000) {
                Threads.this.number -= num;
                System.out.printf ("Player %d subtracts %d to get %d\n", name, num, Threads.this.number);
            }
        }
    }
}


----------



## NyxCharon

Troncoso said:


> I'm playing with threads. This program is suppose to add/subtract a random number until the total is exactly 1000. Though, because of the nature of threads, the output is in correct, and sometimes it stops on something besides 1000. How would I fix that?



It's the nature of threads, sometimes a thread gets interrupted and uses a old value instead of the "real" value, It's called the race condition. 

You need to implement a lock object to fix it. 
An example for a bank account class:


		Code:
	

balancelock.lock();
try
{
//code for the thread to do
}
finally
{
balancelock.unlock();
}


obviously, some stuff is missing there, but you should get the idea. You HAVE to have the finally, because if a exception gets thrown, you won't ever unlock the object and the program, well will lock. So look up the lock class and some examples. :good:


----------



## Troncoso

NyxCharon said:


> It's the nature of threads, sometimes a thread gets interrupted and uses a old value instead of the "real" value, It's called the race condition.
> 
> You need to implement a lock object to fix it.
> An example for a bank account class:
> 
> 
> Code:
> 
> 
> balancelock.lock();
> try
> {
> //code for the thread to do
> }
> finally
> {
> balancelock.unlock();
> }
> 
> 
> obviously, some stuff is missing there, but you should get the idea. You HAVE to have the finally, because if a exception gets thrown, you won't ever unlock the object and the program, well will lock. So look up the lock class and some examples. :good:



Damn you....I knew there was a reason my professor went into restraint locks and whatnot before talking about threads. Haha. I should have thought about that.

Edit: It turned out, all I needed to do, was to put Thread.sleep(10), between the thread executions.


----------



## NyxCharon

Troncoso said:


> Edit: It turned out, all I needed to do, was to put Thread.sleep(10), between the thread executions.



That's not really the proper way to do it, to be honest. It might seem to fix it, and you might not notice the problem, but it's probably still there. A lock is the proper way to do it. The general rule I was told was that if you manipulate the same object/var/whatever, use a lock. 

Also, I hope you at least catch for a interrupted exception with that sleep call.


----------



## Troncoso

NyxCharon said:


> That's not really the proper way to do it, to be honest. It might seem to fix it, and you might not notice the problem, but it's probably still there. A lock is the proper way to do it. The general rule I was told was that if you manipulate the same object/var/whatever, use a lock.
> 
> Also, I hope you at least catch for a interrupted exception with that sleep call.



In most situations, yeah, that won't help. But, here, I've already got the synchronized lock...thing, which about does the right job. Putting the thread to sleep just sorts out any remaining conflict. 
And yeah, I caught the exception. 

If the program was doing any more than literally what it does, I'd need to go further into it. But for the sake of getting this project out of my Easter Break, it gets the job done.


----------



## ayan

I've been learning C# for the past almost 4 years. Never wrote a single line of Java code. Is it worth it to learn to code in Java? I mean, C# seems better documented, and Microsoft's visual studio is just divine! 
What do you need Java for, and there's no way of doing it with other language (or doing it with other languages is much harder)


----------



## Cromewell

ayan said:


> I've been learning C# for the past almost 4 years. Never wrote a single line of Java code. Is it worth it to learn to code in Java? I mean, C# seems better documented, and Microsoft's visual studio is just divine!
> What do you need Java for, and there's no way of doing it with other language (or doing it with other languages is much harder)



Java is documented pretty well....granted the generated docs look like html from 1993. http://docs.oracle.com/javase/6/docs/api/

Java is useful for all sorts of things, it's just as easy as anything .NET and as far as IDEs go Eclipse is pretty good.

The original advantage of Java was if you wrote it correctly you never needed to recompile it. You could take your class file and run it on any system that had the Java VM.


----------



## ayan

Cromewell said:


> Java is documented pretty well....granted the generated docs look like html from 1993. http://docs.oracle.com/javase/6/docs/api/
> 
> Java is useful for all sorts of things, it's just as easy as anything .NET and as far as IDEs go Eclipse is pretty good.
> 
> The original advantage of Java was if you wrote it correctly you never needed to recompile it. You could take your class file and run it on any system that had the Java VM.



By "never needed to recompile" don't you mean that mechanism that i'm currently learning in c++, that lets me compile just once header files? 



		Code:
	

#ifndef
#define HEADERFILE_H_

//function deffinitions and stuff

#endif


----------



## Cromewell

If you build a C++ application in windows the executable you have will not run in linux. If I build some java code in windows, I can copy that file to linux and it is runnable.

A header file is different.


----------



## Troncoso

Hey again. I'm wondering, how could you step through a recursive method in Java? By that, I mean, each time a level of recursion finishes, I want the program to stop until I click the next button or what ever button I choose. 
In doing that, wouldn't I effectively have to remove the recursive aspect?


----------



## NyxCharon

Troncoso said:


> Hey again. I'm wondering, how could you step through a recursive method in Java? By that, I mean, each time a level of recursion finishes, I want the program to stop until I click the next button or what ever button I choose.
> In doing that, wouldn't I effectively have to remove the recursive aspect?



Use a IDE with a debug function. I use netbeans for instance, and can see the values of everything, step by step.


----------



## Troncoso

NyxCharon said:


> Use a IDE with a debug function. I use netbeans for instance, and can see the values of everything, step by step.



I know I can do that, but I want it to be part of the program. You see, I have a method for the "find the fake coin" riddle. It splits the pile of coins into separate piles and weighs them against each other. Because the fake coin is lighter, it's pile will be lighter. So it isolates that pile and splits it into 3 again. And it does this until there are just three coins left.

I want the program to increment at one weighing at a time, so the user can see  each one and see where the lighter pile is.

Maybe I'm asking the wrong question to accomplish this. Haha.


----------



## Ankur

Hello guys here is the code for addition program.

calWS.java


		Code:
	

package mypack;

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.ejb.Stateless;

/**
 *
 * @author user
 */
@WebService(serviceName = "calWS")
@Stateless()
public class calWS {
    /**
     * Web service operation
     */
    @WebMethod(operationName = "additionoperation")
    public String additionoperation(@WebParam(name = "num1") String num1, @WebParam(name = "num2") String num2) {
        //TODO write your implementation code here:
        try{
            int x=Integer.parseInt(num1); 
            int y=Integer.parseInt(num2); 
            int z=x+y;
            return z+"";
        }
        catch(Exception e)
        {
          return e.getMessage();  
        }
        
    }
}

index.jsp


		Code:
	

<%-- 
    Document   : index
    Created on : 18 Apr, 2013, 3:28:12 PM
    Author     : Ankur
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form name="ArithmaticOp" action="add.jsp">
            <table border="0">
                <thead>
                    <tr>
                        <th colspan="2">Enter 2 numbers:</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>a=</td>
                        <td><input type="text" id="num1" name="num1" value="0" size="10"/></td>
                    </tr>
                    <tr>
                        <td>b=</td>
                        <td><input type="text" id="num2" name="num2" value="0" size="10"/></td>
                    </tr>
                    <tr>
                        
                        <td colspan="2"><input type="submit" value="Get Result" name="result"/></td>
                    </tr>
                </tbody>
            </table>
        </form>
      </body>
</html>


add.jsp


		Code:
	

<%-- 
    Document   : add
    Created on : 18 Apr, 2013, 3:32:42 PM
    Author     : Ankur
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>    <%-- start web service invocation --%><hr/>
    <%
    try {
	mypack.calWS_Service service = new mypack.calWS_Service();
	mypack.calWS port = service.getCalWSPort();
	 // TODO initialize WS operation arguments here
	java.lang.String num1 =request.getParameter("num1");
	java.lang.String num2 = request.getParameter("num2");
	// TODO process result here
	java.lang.String result = port.additionoperation(num1, num2);
	out.println("Result = "+result);
    } catch (Exception ex) {
	// TODO handle custom exceptions here
    }
    %>
    <%-- end web service invocation --%><hr/>

    </body>
</html>


i am getting a problem at mypack.calWS_Service service = new mypack.calWS_Service();
it says


> PWC6197: An error occurred at line: 16 in the jsp file: /add.jsp
> PWC6199: Generated servlet error:
> cannot find symbol
> symbol:   class calWS_Service
> location: package mypack
> 
> PWC6197: An error occurred at line: 16 in the jsp file: /add.jsp
> PWC6199: Generated servlet error:
> cannot find symbol
> symbol:   class calWS_Service
> location: package mypack


I am not understanding the problem, am beginner in this, please can someone tell me whats going wrong here? How to write the symbol in it?? without changing the whole program?


----------



## Cromewell

I think you are missing the import, <%@ page import="package1.myClass1,package2.myClass2,....,packageN.myClassN" %> is the gist of how it's done. I haven't written jsp though so that's just what I think is wrong based on the error and the search results I got back.


----------

