Java Thread

Cromewell

Administrator
Staff member
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.
 
Last edited:

salvage-this

Active Member
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

Active Member
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

Active Member
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

Administrator
Staff member
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

VIP Member
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.
 

NyxCharon

Active Member
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. :D
I can post my final code for either if anyone was interested for any reason.
 

Cromewell

Administrator
Staff member
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

Administrator
Staff member
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

Active Member
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

Administrator
Staff member
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)
}
 

Dropkickmurphys

New Member
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.
 
Last edited:

Dropkickmurphys

New Member
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? :)
 

Cromewell

Administrator
Staff member
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

Administrator
Staff member
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

Administrator
Staff member
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

Active Member
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
 
Last edited:
Top