Need help with an assignment

first of all, who has heard of the game called zuul? It is a very boring text based game I am currently having the pleasure of improving.
Basically, you are in a room, that is connected to a bunch of other rooms and depending on the room you are in, you have different exists and different items in the room.
The goal is to navigate through the collection of Rooms and there is no real win condition, It is more for learning then for actually playing.
You navigate by a series of commands such as: go (direction)( as in "direction of exit", NSEW), quit, a few other odd bits.
ex: go south, quit, go west etc
The game has several classes: Game, Command, CommandWords, Item, Parser, Room.
Obviously Game is the main central head conch, (it is not the super class.)
Game makes use of Item, Room, Parser, and Command.
Item is the class that deals with the number of items in the Room.
Room is the class that deals with the rooms the player will navigate to and from.
Command reads in the commands such as "go-(direction)" or "quit".
Parser makes everybody understand each other by using both Command and CommandWords.
CommandWords is a list of commands such as "go", "quit" etc.
The problem I am having right now is to allow a player to move through the rooms while holding a certain item. The item has to come from the rooms and the player should be able to drop it.
So I have to add two new commands: take and drop. The problem is that I have been asked to do this without creating a new class. Otherwise I would have just created class Player and be done with it. So I am trying to figure out whose responsibility should it be to take care of the take and drop command. I have done some preliminary work in class Game, it is the take(Command command) and drop() methods.
I have also a few questions concerning other aspects of the project, I have listed their locations here:
1. The take() method in class Game, the for-each loop, a complier error with ArrayList
2. class Parser, a general question about the string tokenzier
If you want to see how the game is suppose to run, just comment out the bodies of take() and drop(). Not the declaration. Everything else works.
I shall now provide the code to all classes. I wish there were an option to upload a zip file, then you don't have to read through all the codes and copy&paste all the codes. The complier I am using is BlueJ. And the SDK version is 1.6. With the exception of class Game, everything else can be assumed to be error free.
Thank you for your time,
Davy
class Game
import java.util.*;
*  This class is the main class of the "World of Zuul" application.
*  "World of Zuul" is a very simple, text based adventure game.  Users
*  can walk around some scenery. That's all. It should really be extended
*  to make it more interesting!
*  To play this game, create an instance of this class and call the "play"
*  method.
*  This main class creates and initialises all the others: it creates all
*  rooms, creates the parser and starts the game.  It also evaluates and
*  executes the commands that the parser returns.
* @author  Michael Kolling and David J. Barnes
* @version 2006.03.30
public class Game
    private Parser parser;
    private Room currentRoom;
    private Room previousRoom;
    private Stack<Room> previousRooms;
     * Create the game and initialise its internal map.
    public Game()
        createRooms();
        parser = new Parser();
     * Create all the rooms and link their exits together.
    private void createRooms()
        Room outside, theatre, pub, lab, office;
        // create the rooms
        outside = new Room("outside the main entrance of the university");
        theatre = new Room("in a lecture theatre");
        pub = new Room("in the campus pub");
        lab = new Room("in a computing lab");
        office = new Room("in the computing admin office");
        // create some items
        Item desk, chair, beer, podium, tree;
        desk = new Item("desk", "student desk",10);
        chair = new Item("chair", "student chair",5);
        beer = new Item("beer", "glass of beer", 0.5);
        podium = new Item("podium", "lecture podium", 100);
        tree = new Item("tree", "a tree", 500.5);
        // put items in some of the rooms
        outside.addItem(tree);
        theatre.addItem(desk);
        theatre.addItem(chair);
        theatre.addItem(podium);
        pub.addItem(beer);
        pub.addItem(beer);
        office.addItem(desk);
        lab.addItem(chair);
        lab.addItem(beer);
        // initialise room exits
        outside.setExit("east", theatre);
        outside.setExit("south", lab);
        outside.setExit("west", pub);
        theatre.setExit("west", outside);
        pub.setExit("east", outside);
        lab.setExit("north", outside);
        lab.setExit("east", office);
        office.setExit("west", lab);
        currentRoom = outside;  // start game outside
        previousRooms = new Stack<Room>(); // no rooms on the stack
        previousRoom = null;
     *  Main play routine.  Loops until end of play.
    public void play()
        printWelcome();
        // Enter the main command loop.  Here we repeatedly read commands and
        // execute them until the game is over.
        boolean finished = false;
        while (! finished) {
            Command command = parser.getCommand();
            finished = processCommand(command);
        System.out.println("Thank you for playing.  Good bye.");
     * Print out the opening message for the player.
    private void printWelcome()
        System.out.println();
        System.out.println("Welcome to the World of Zuul!");
        System.out.println("World of Zuul is a new, incredibly boring adventure game.");
        System.out.println("Type 'help' if you need help.");
        System.out.println();
        System.out.println(currentRoom.getLongDescription());
     * Given a command, process (that is: execute) the command.
     * @param command The command to be processed.
     * @return true If the command ends the game, false otherwise.
    private boolean processCommand(Command command)
        boolean wantToQuit = false;
        if(command.isUnknown()) {
            System.out.println("I don't know what you mean...");
            return false;
        String commandWord = command.getCommandWord();
        if (commandWord.equals("help")) {
            printHelp();
        else if (commandWord.equals("go")) {
            goRoom(command);
        else if (commandWord.equals("look")) {
            look(command);
        else if (commandWord.equals("eat")) {
            eat(command);
        else if (commandWord.equals("back")) {
            back(command);
        else if (commandWord.equals("stackBack")) {
            stackBack(command);
        else if (commandWord.equals("take")){
            take(command);
        else if (commandWord.equals("drop")) {
            drop(command);
        else if (commandWord.equals("quit")) {
            wantToQuit = quit(command);
        // else command not recognised.
        return wantToQuit;
    // implementations of user commands:
     * Print out some help information.
     * Here we print some stupid, cryptic message and a list of the
     * command words.
    private void printHelp()
        System.out.println("You are lost. You are alone. You wander");
        System.out.println("around at the university.");
        System.out.println();
        System.out.println("Your command words are:");
        System.out.println(parser.getCommands());
     * Try to go to one direction. If there is an exit, enter the new
     * room, otherwise print an error message.
     * @param command The command entered.
    private void goRoom(Command command)
        if(!command.hasSecondWord()) {
            // if there is no second word, we don't know where to go...
            System.out.println("Go where?");
            return;
        String direction = command.getSecondWord();
        // Try to leave current room.
        Room nextRoom = currentRoom.getExit(direction);
        if (nextRoom == null) {
            System.out.println("There is no door!");
        else {
            previousRooms.push(currentRoom);
            previousRoom = currentRoom;
            currentRoom = nextRoom;
            System.out.println(currentRoom.getLongDescription());
     * "Look" was entered.
     * @param command The command entered.
    private void look(Command command)
        if(command.hasSecondWord()) {
            System.out.println("Look what?");
            return;
        System.out.println(currentRoom.getLongDescription());
     * "Eat" was entered.
     * @param command The command entered.
    private void eat(Command command)
        if(command.hasSecondWord()) {
            System.out.println("Eat what?");
            return;
        System.out.println("You have eaten and are no longer hungry!");
     * "Back" was entered.
     * @param command The command entered.
    private void back(Command command)
        if(command.hasSecondWord()) {
            System.out.println("Back what?");
            return;
        if (previousRoom==null) {
            System.out.println("Can't go back.");
            return;
        // push current room on stack (for stackBack)
        previousRooms.push(currentRoom);
        // swap current and previous rooms (for back)
        Room temp = currentRoom;
        currentRoom = previousRoom;
        previousRoom = temp;
        // You could replace the previous three lines with the following
        // which use the stack to get the previous room
        // but note that this makes "back" dependent on "stackBack".
        // (If you do it this way you no longer need "temp".
        // currentRoom = previousRoom;
        // previousRoom = previousRooms.peek();
        System.out.println("You have gone back:");
        System.out.println(currentRoom.getLongDescription());
     * "StackBack" was entered.
     * @param command The command entered.
    private void stackBack(Command command)
        if(command.hasSecondWord()) {
            System.out.println("StackBack what?");
            return;
        if (previousRooms.isEmpty()) {
            System.out.println("Can't go StackBack.");
            return;
        // set previous room (for "back")
        previousRoom = currentRoom;
        // set new current room (using stack)
        currentRoom = previousRooms.pop();
        System.out.println("You have gone StackBack:");
        System.out.println(currentRoom.getLongDescription());
     * allows a player to take something from the room
     * @param command
    private void take(Command command){
    String a;
    a=command.getSecondWord();
    for (Item i:currentRoom.items()) { //a for each loop, since the room's items are kept in a list, but this gives a                                           //compiler error, it doesn't work because items is an ArrayList, but I need a way to pick up the item. I thought that if //given the item's name, I could run a check through the room's ArrayList of items via a for-each loop
        if (a==i.getName()) {
        removeItem (i);
        return;
     * allows a player to drop an item in the room
     * @param command
    private void drop(Command command) {
        if(command.hasSecondWord()) {
            System.out.println("drop what?");
            return;
        //add item method is suppose to be used here
     * "Quit" was entered. Check the rest of the command to see
     * whether we really quit the game.
     * @param command The command entered.
     * @return true, if this command quits the game, false otherwise.
    private boolean quit(Command command)
        if(command.hasSecondWord()) {
            System.out.println("Quit what?");
            return false;
        else {
            return true;  // signal that we want to quit
}class Room
import java.util.*;
* Class Room - a room in an adventure game.
* This class is part of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game. 
* A "Room" represents one location in the scenery of the game.  It is
* connected to other rooms via exits.  For each existing exit, the room
* stores a reference to the neighboring room.
* @author  Michael Kolling and David J. Barnes
* @version 2006.03.30
* @author L.S. Marshall
* @version 1.03 October 25, 2007
public class Room
    private String description;
    private HashMap<String, Room> exits;        // stores exits of this room.
    // The items in the room
    private ArrayList<Item> items;
     * Create a room described "description". Initially, it has
     * no exits. "description" is something like "a kitchen" or
     * "an open court yard".
     * @param description The room's description.
    public Room(String description)
        this.description = description;
        exits = new HashMap<String, Room>();
        items = new ArrayList<Item>();
     * Define an exit from this room.
     * @param direction The direction of the exit.
     * @param neighbor  The room to which the exit leads.
    public void setExit(String direction, Room neighbor)
        exits.put(direction, neighbor);
     * Gives a short description of the room.
     * @return The short description of the room
     * (the one that was defined in the constructor).
    public String getShortDescription()
        return description;
     * Return a description of the items in the room
     * (Note that this could be combined with getLongDescription, but
     * this way shows better cohesion, and could avoid code duplication
     * for future enhancements.)
     * @return A description of the items in this room
    public String getItemsDescription()
        String s = new String();
        if (items.size()==0)
            s += "There are no items in this room.\n";
        else {
            s += "The item(s) in the room are:\n";
            for (Item item : items ) {
               s += item.getInfo() + "\n";
        return s;
     * Return a description of the room in the form:
     *     You are in the kitchen.
     *     Exits: north west
     *     and information on the items in the room
     * @return A long description of this room
    public String getLongDescription()
        String s = "You are " + description + ".\n" + getExitString() + "\n";
        s += getItemsDescription();
        return s;
     * Return a string describing the room's exits, for example
     * "Exits: north west".
     * @return Details of the room's exits.
    private String getExitString()
        String returnString = "Exits:";
        Set<String> keys = exits.keySet();
        for(String exit : keys) {
            returnString += " " + exit;
        return returnString;
     * Return the room that is reached if we go from this room in direction
     * "direction". If there is no room in that direction, return null.
     * @param direction The exit's direction.
     * @return The room in the given direction.
    public Room getExit(String direction)
        return exits.get(direction);
     * Adds the given item to the room.
     * @param item The item to be added
    public void addItem(Item item)
        items.add(item);
     * Removes an item if the person picks it up
     * @param item the item to be removed
    public void removeItem (Item item)
        items.remove(item);
}class Item
* This represents an item in a room in zuul.
* @author L.S. Marshall
* @version 1.00 October 9, 2007
public class Item
    // The description of the item
    private String description;
    // The weight of the item
    private double weight;
    private String name;
     * Constructor for objects of class Item
     * @param desc description of the item
     * @param weight the weight of the item
    public Item(String name, String desc, double weight)
        description = desc;
        this.weight = weight;
        this.name=name;
     * Returns a string representing this item
     * @return string representing this item
    public String getInfo()
        return ("Item: " + description + ", weighs " + weight + ".");
     * returns the name of the string
     * @ return the name in a string
    public String getName()
        return ( name );
}class Command
* This class is part of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game. 
* This class holds information about a command that was issued by the user.
* A command currently consists of two strings: a command word and a second
* word (for example, if the command was "take map", then the two strings
* obviously are "take" and "map").
* The way this is used is: Commands are already checked for being valid
* command words. If the user entered an invalid command (a word that is not
* known) then the command word is <null>.
* If the command had only one word, then the second word is <null>.
* @author  Michael Kolling and David J. Barnes
* @version 2006.03.30
public class Command
    private String commandWord;
    private String secondWord;
     * Create a command object. First and second word must be supplied, but
     * either one (or both) can be null.
     * @param firstWord The first word of the command. Null if the command
     *                  was not recognised.
     * @param secondWord The second word of the command.
    public Command(String firstWord, String secondWord)
        commandWord = firstWord;
        this.secondWord = secondWord;
     * Return the command word (the first word) of this command. If the
     * command was not understood, the result is null.
     * @return The command word.
    public String getCommandWord()
        return commandWord;
     * @return The second word of this command. Returns null if there was no
     * second word.
    public String getSecondWord()
        return secondWord;
     * @return true if this command was not understood.
    public boolean isUnknown()
        return (commandWord == null);
     * @return true if the command has a second word.
    public boolean hasSecondWord()
        return (secondWord != null);
}class Parser
import java.util.Scanner;
import java.util.StringTokenizer;
//I read the documentation for String Tokenizer, and I have a few questions relating to a pet project of mine. The //project is to build a boolean algebra simplifer. I would give it a boolean expression and it will simplify it for me.
//Which is very similar to what this class does. The documentation mentioned a delimiter for separating the tokens.
//yet I see none here, is the delimiter at default, the space between the words? and if I were to set manually //delimiters, how do I do that?
//Once I read in the string, should it be Parser's job to execute the boolean simplification part? According the RDD,
//it shouldn't, but doing so would keep everything in fewer classes and therefore easier to manage, wouldn't it?
* This class is part of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game. 
* This parser reads user input and tries to interpret it as an "Adventure"
* command. Every time it is called it reads a line from the terminal and
* tries to interpret the line as a two word command. It returns the command
* as an object of class Command.
* The parser has a set of known command words. It checks user input against
* the known commands, and if the input is not one of the known commands, it
* returns a command object that is marked as an unknown command.
* @author  Michael Kolling and David J. Barnes
* @version 2006.03.30
* @author L.S. Marshall
* @version 1.01 October 9, 2007
public class Parser
    private CommandWords commands;  // holds all valid command words
    private Scanner reader;         // source of command input
     * Create a parser to read from the terminal window.
    public Parser()
        commands = new CommandWords();
        reader = new Scanner(System.in);
     * Command returns the command typed by the user.
     * @return The next command from the user.
    public Command getCommand()
        String inputLine;   // will hold the full input line
        String word1 = null;
        String word2 = null;
        System.out.print("> ");     // print prompt
        inputLine = reader.nextLine();
        // Find up to two words on the line.
        Scanner tokenizer = new Scanner(inputLine);
        if(tokenizer.hasNext()) {
            word1 = tokenizer.next();      // get first word
            if(tokenizer.hasNext()) {
                word2 = tokenizer.next();      // get second word
                // note: we just ignore the rest of the input line.
        // Now check whether this word is known. If so, create a command
        // with it. If not, create a "null" command (for unknown command).
        if(commands.isCommand(word1)) {
            return new Command(word1, word2);
        else {
            return new Command(null, word2);
     * Returns a list of valid command words.
     * @string list of valid command words
    public String getCommands()
        return commands.getCommandList();
}class CommandWords
* This class is part of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game.
* This class holds an enumeration of all command words known to the game.
* It is used to recognise commands as they are typed in.
* @author  Michael Kolling and David J. Barnes
* @version 2006.03.30
* @author L.S. Marshall
* @version 1.01 October 9, 2007
public class CommandWords
    // a constant array that holds all valid command words
    private static final String[] validCommands = {
        "go", "quit", "help", "look", "eat", "back", "stackBack",
        "take", "drop",
     * Constructor - initialise the command words.
    public CommandWords()
        // nothing to do at the moment...
     * Check whether a given String is a valid command word.
     * @param aString the command word
     * @return true if it is, false if it isn't.
    public boolean isCommand(String aString)
        for(int i = 0; i < validCommands.length; i++) {
            if(validCommands.equals(aString))
return true;
// if we get here, the string was not found in the commands
return false;
* Return a string containing all valid commands.
* @return string of all valid commands
public String getCommandList()
String s="";
for(String command: validCommands) {
s += command + " ";
return s;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

right, sorry, that was thoughtless of me.
class Parser
import java.util.Scanner;
import java.util.StringTokenizer;
//I read the documentation for String Tokenizer, and I have a few questions relating to a pet project of mine. The //project is to build a boolean algebra simplifer. I would give it a boolean expression and it will simplify it for me.
//Which is very similar to what this class does. The documentation mentioned a delimiter for separating the tokens.
//yet I see none here, is the delimiter at default, the space between the words? and if I were to set manually //delimiters, how do I do that?
//Once I read in the string, should it be Parser's job to execute the boolean simplification part? According the RDD,
//it shouldn't, but doing so would keep everything in fewer classes and therefore easier to manage, wouldn't it?
* This class is part of the "World of Zuul" application.
* "World of Zuul" is a very simple, text based adventure game. 
* This parser reads user input and tries to interpret it as an "Adventure"
* command. Every time it is called it reads a line from the terminal and
* tries to interpret the line as a two word command. It returns the command
* as an object of class Command.
* The parser has a set of known command words. It checks user input against
* the known commands, and if the input is not one of the known commands, it
* returns a command object that is marked as an unknown command.
* @author  Michael Kolling and David J. Barnes
* @version 2006.03.30
* @author L.S. Marshall
* @version 1.01 October 9, 2007
public class Parser
    private CommandWords commands;  // holds all valid command words
    private Scanner reader;         // source of command input
     * Create a parser to read from the terminal window.
    public Parser()
        commands = new CommandWords();
        reader = new Scanner(System.in);
     * Command returns the command typed by the user.
     * @return The next command from the user.
    public Command getCommand()
        String inputLine;   // will hold the full input line
        String word1 = null;
        String word2 = null;
        System.out.print("> ");     // print prompt
        inputLine = reader.nextLine();
        // Find up to two words on the line.
        Scanner tokenizer = new Scanner(inputLine);
        if(tokenizer.hasNext()) {
            word1 = tokenizer.next();      // get first word
            if(tokenizer.hasNext()) {
                word2 = tokenizer.next();      // get second word
                // note: we just ignore the rest of the input line.
        // Now check whether this word is known. If so, create a command
        // with it. If not, create a "null" command (for unknown command).
        if(commands.isCommand(word1)) {
            return new Command(word1, word2);
        else {
            return new Command(null, word2);
     * Returns a list of valid command words.
     * @string list of valid command words
    public String getCommands()
        return commands.getCommandList();
}

Similar Messages

  • Need help with this assignment!!!!

    Please help me with this. I am having some troubles. below is the specification of this assignment:
    In geometry the ratio of the circumference of a circle to its diameter is known as �. The value of � can be estimated from an infinite series of the form:
    � / 4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) + ...
    There is another novel approach to calculate �. Imagine that you have a dart board that is 2 units square. It inscribes a circle of unit radius. The center of the circle coincides with the center of the square. Now imagine that you throw darts at that dart board randomly. Then the ratio of the number of darts that fall within the circle to the total number of darts thrown is the same as the ratio of the area of the circle to the area of the square dart board. The area of a circle with unit radius is just � square unit. The area of the dart board is 4 square units. The ratio of the area of the circle to the area of the square is � / 4.
    To simuluate the throwing of darts we will use a random number generator. The Math class has a random() method that can be used. This method returns random numbers between 0.0 (inclusive) to 1.0 (exclusive). There is an even better random number generator that is provided the Random class. We will first create a Random object called randomGen. This random number generator needs a seed to get started. We will read the time from the System clock and use that as our seed.
    Random randomGen = new Random ( System.currentTimeMillis() );
    Imagine that the square dart board has a coordinate system attached to it. The upper right corner has coordinates ( 1.0, 1.0) and the lower left corner has coordinates ( -1.0, -1.0 ). It has sides that are 2 units long and its center (as well as the center of the inscribed circle) is at the origin.
    A random point inside the dart board can be specified by its x and y coordinates. These values are generated using the random number generator. There is a method nextDouble() that will return a double between 0.0 (inclusive) and 1.0 (exclusive). But we need random numbers between -1.0 and +1.0. The way we achieve that is:
    double xPos = (randomGen.nextDouble()) * 2 - 1.0;
    double yPos = (randomGen.nextDouble()) * 2 - 1.0;
    To determine if a point is inside the circle its distance from the center of the circle must be less than the radius of the circle. The distance of a point with coordinates ( xPos, yPos ) from the center is Math.sqrt ( xPos * xPos + yPos * yPos ). The radius of the circle is 1 unit.
    The class that you will be writing will be called CalculatePI. It will have the following structure:
    import java.util.*;
    public class CalculatePI
    public static boolean isInside ( double xPos, double yPos )
    public static double computePI ( int numThrows )
    public static void main ( String[] args )
    In your method main() you want to experiment and see if the accuracy of PI increases with the number of throws on the dartboard. You will compare your result with the value given by Math.PI. The quantity Difference in the output is your calculated value of PI minus Math.PI. Use the following number of throws to run your experiment - 100, 1000, 10,000, and 100,000. You will call the method computePI() with these numbers as input parameters. Your output will be of the following form:
    Computation of PI using Random Numbers
    Number of throws = 100, Computed PI = ..., Difference = ...
    Number of throws = 1000, Computed PI = ..., Difference = ...
    Number of throws = 10000, Computed PI = ..., Difference = ...
    Number of throws = 100000, Computed PI = ..., Difference = ...
    * Difference = Computed PI - Math.PI
    In the method computePI() you will simulate the throw of a dart by generating random numbers for the x and y coordinates. You will call the method isInside() to determine if the point is inside the circle or not. This you will do as many times as specified by the number of throws. You will keep a count of the number of times a dart landed inside the circle. That figure divided by the total number of throws is the ratio � / 4. The method computePI() will return the computed value of PI.
    and below is what i have so far:
    import java.util.*;
    public class CalculatePI
        public static boolean isInside ( double xPos, double yPos )   
            boolean result;  
            double distance = Math.sqrt( xPos * xPos + yPos * yPos );
            if (distance < 1)               
                result = true;
            return result;
        public static double computePI ( int numThrows )
            Random randomGen = new Random ( System.currentTimeMillis() );       
            double xPos = (randomGen.nextDouble()) * 2 - 1.0;
            double yPos = (randomGen.nextDouble()) * 2 - 1.0;
            boolean isInside = isInside (xPos, yPos);
            int hits = 0;
            double PI = 0;        
            for ( int i = 0; i <= numThrows; i ++ )
                if (isInside)
                    hits = hits + 1;
                    PI = 4 * ( hits / numThrows );
            return PI;
        public static void main ( String[] args )
            Scanner sc = new Scanner (System.in);
            System.out.print ("Enter number of throws:");
            int numThrows = sc.nextInt();
            double Difference = computePI(numThrows) - Math.PI;
            System.out.println ("Number of throws = " + numThrows + ", Computed PI = " + computePI(numThrows) + ", Difference = " + Difference );       
    }when i tried to compile it says "variable result might not have been initialized" Why is this? and please check this program for me too see if theres any syntax or logic errors. Thanks.

    when i tried to compile it says "variable result might not have been
    initialized" Why is this?Because you only assigned it if distance < 1. What is it assigned to if distance >= 1? It isn't.
    Simple fix:
    boolean result = (distance < 1);
    return result;
    or more simply:
    return (distance < 1);
    and please check this program for me too see if theres any syntax or
    logic errors. Thanks.No, not going to do that. That's much more your job, and to ask specific questions about if needed.

  • I need help with an assignment

    I have several issues. I am doing a project for a class and I'm stuck. the message doesn't appear in the textbox.  That's the only problem with this code so far. Next thing I haven't been able to figure out is  that
    I need to add two "do", "do while", "do until", or "for-next" loops. I am stuck. I tried to add a "do" loop for adding up the totals but Visual Basic 2010 Express froze up every time I tried to run the program
    after that. Here is my code:
    Public Class IceCream
        Private Sub totalButton_Click(sender As System.Object, e As System.EventArgs) Handles totalButton.Click
            Dim small As Integer
            Dim medium As Integer
            Dim large As Integer
            Dim total As Decimal = 0
            Dim result As Decimal = 0
            Dim result1 As Decimal = 0
            Dim result2 As Decimal = 0
            ' assign values from user input
            small = Val(chocTextBox.Text)
            medium = Val(strawTextBox.Text)
            large = Val(vaniTextBox.Text)
            ' alert if checkbox unchecked
            If (chocCheckBox.Checked = False AndAlso
                strawCheckBox.Checked = False AndAlso
                vaniCheckBox.Checked = False) Then
                'display error message in dialog for input violation
                MessageBox.Show("what's your flavor?", "flavor error", MessageBoxButtons.OK,
                                MessageBoxIcon.Question)
            End If
            ' calculate prices
            result = small * 2.0
            result1 = medium * 3.0
            result2 = large * 4.0
            total = result + result1 + result2
            ' display total
            totalChocLabel.Text = String.Format("{0:C}", result)
            totalStrawLabel.Text = String.Format("{0:C}", result1)
            totalVaniLabel.Text = String.Format("{0:C}", result2)
            totalLabel.Text = String.Format("{0:C}", total)
            Dim message As String ' displays message
            Dim chocolate As Integer
            Dim strawberry As Integer
            Dim vanilla As Integer
            message = chocCheckBox.Checked & strawCheckBox.Checked & vaniCheckBox.Checked
            Select Case message
                Case chocolate
                    message = "You got Chocolate!"
                Case strawberry
                    message = "You got Strawberry!"
                Case vanilla
                    message = "You got Vanilla!"
                    ' display message in TextBox
                    iceCreamTextBox.Text = (ControlChars.Tab & message & ControlChars.CrLf)
            End Select
        End Sub
    End Class

    BG,
    Knowing that this is homework (and thank you for stating that - many here don't), please understand that the members here are somewhat reluctant to do more than prod you in the right direction. I'm sure that you agree - handing you an answer wouldn't be
    your own work and you'd never learn anything from it.
    I'd like to make some suggestions though:
    At the top of your form's code, put the following:
    Option Strict On
    Option Explicit On
    Option Infer Off
    This will ensure that you're using the "tightest" code possible and that you're not relying on the compiler to figure out what you mean about anything. You'll likely find some compile errors shown (little blue 'squigly' lines beneath variables
    in your code) so you need to work through those until there are none.
    That can be a challenge itself! If you find yourself lost in a sea of 'blue squigglies' (if there's such a term), then bit at at time, post back with one and we'll help you work through it and explain why you got them to start with.
    Don't use the Val() function. It's old and should, in my opinion, be removed from use forever; it's more than deprecated but that aside, it will seem to work when it shouldn't. As an off-the-cuff-example:
    Dim s As String = "111 1st Avenue"
    Dim d as Double = Val(s)
    Did that work?
    Unfortunately, yes it did but what does that tell you? It should have failed - it didn't.
    Use the numeric type's .TryParse method as a test to see if the string can be parsed to that type and, if so, then proceed from there or inform the user that what they entered isn't valid. I could go into this part alone for the next 45 minutes ... and I'll
    come up with an example if you're interested, but my point is: Don't rely on Val() to work like you think it does.
    Once you have all of that sorted out, put a breakpoint in (as already mentioned) and line-by-line, step into each. When the program halts at the end of each, hover your mouse over each variable and look to see what it/they are.
    At some point, you'll have an "ahHA!" moment and you'll have solved your problem!
    I hope that helps. :)
    Still lost in code, just at a little higher level.

  • Beginner needs help with programming assignment

    So I have been working on it and it is reading everything and posting everything to the output file, but it looks like this
    MonthlyRainfall(cm)
    Average: 3.66
    January 7.29, above averageApril3.55, below averageNovember0.15, below average
    When instead it should look like this. Don't know what I need to do to get it to work like this. If I have to much regarding the IF Else statements or I just don't have it laid out right. Any help is appreciated. Thanks.
    Monthly Rainfall (cm)
    Average: 3.66
    January 7.29, above average
    April 3.55, below average
    November 0.15, below average
    Here is the code I have so far:
    package assign4;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.PrintWriter;
    import java.util.Scanner;
    import javax.swing.JOptionPane;
    public class Rainfall2 {/** main method
    * This is where the program starts.
    * @param args
    public static void main(String[] args) throws FileNotFoundException {
    * Title: Assignment 4
    * Description: CS 161 Assignment #4
    * date: October 27th 2008
    final String fileName = "src/assign4/rain2.txt";
    Scanner myFile = new Scanner( new FileReader( fileName ) );
    PrintWriter outFile = new
    PrintWriter ("src/assign4/rainfalloutput.out");
    //declares variables
    String title;
    String subtitle;
    String units;
    String date;
    int month1, month2, month3;
    double rain1, rain2, rain3;
    double average;
    * Read 6 lines from the input file
    title = myFile.next();
    subtitle = myFile.next();
    units = myFile.next();
    month1 = myFile.nextInt();
    rain1 = myFile.nextDouble();
    month2 = myFile.nextInt();
    rain2 = myFile.nextDouble();
    month3 = myFile.nextInt();
    rain3 = myFile.nextDouble();
    myFile.close(); //close the input file
    average = (rain1 + rain2 + rain3) / 3.0; //computes the average rainfall from data points
    outFile.println( title + subtitle + units);
    outFile.printf ("Average: %5.2f %n", average);
    if (month1 == 1)
    outFile.print ("January ");
    else if (month1 == 2)
    outFile.print ("February");
    else if (month1 == 3)
    outFile.print ("March");
    else if (month1 == 4)
    outFile.print ("April");
    else if (month1 == 5)
    outFile.print ("May");
    else if (month1 == 6)
    outFile.print ("June");
    else if (month1 == 7)
    outFile.print ("July");
    else if (month1 == 8)
    outFile.print ("August");
    else if (month1 == 9)
    outFile.print ("September ");
    else if (month1 == 10)
    outFile.print ("October");
    else if (month1 == 11)
    outFile.print ("November");
    else if (month1 == 12)
    outFile.print ("December");
    if (rain1 > average)
    outFile.print ( rain1 + ", above average");
    else
    if (rain1 == average)
    outFile.print ( rain1 + ", average");
    else
    if (rain1 < average)
    outFile.print ( rain1 + ", below average");
    if (month2 == 1)
    outFile.printf ("January");
    else if (month2 == 2)
    outFile.printf ("February");
    else if (month2 == 3)
    outFile.printf ("March");
    else if (month2 == 4)
    outFile.printf ("April");
    else if (month2 == 5)
    outFile.printf ("May");
    else if (month2 == 6)
    outFile.printf ("June");
    else if (month2 == 7)
    outFile.printf ("July");
    else if (month2 == 8)
    outFile.printf ("August");
    else if (month2 == 9)
    outFile.printf ("September");
    else if (month2 == 10)
    outFile.printf ("October");
    else if (month2 == 11)
    outFile.printf ("November");
    else if (month2 == 12)
    outFile.printf ("December");
    if (rain2 > average)
    outFile.printf ( rain2 + ", above average");
    else
    if (rain2 == average)
    outFile.printf ( rain2 + ", average");
    else
    if (rain2 < average)
    outFile.printf ( rain2 + ", below average");
    if (month3 == 1)
    outFile.printf ("January");
    else if (month3 == 2)
    outFile.printf ("February");
    else if (month3 == 3)
    outFile.printf ("March");
    else if (month3 == 4)
    outFile.printf ("April");
    else if (month3 == 5)
    outFile.printf ("May");
    else if (month3 == 6)
    outFile.printf ("June");
    else if (month3 == 7)
    outFile.printf ("July");
    else if (month3 == 8)
    outFile.printf ("August");
    else if (month3 == 9)
    outFile.printf ("September");
    else if (month3 == 10)
    outFile.printf ("October");
    else if (month3 == 11)
    outFile.printf ("November");
    else if (month3 == 12)
    outFile.printf ("December");
    if (rain3 > average)
    outFile.printf ( rain3 + ", above average");
    else
    if (rain3 == average)
    outFile.printf ( rain3 + ", average");
    else
    if (rain3 < average)
    outFile.printf ( rain3 + ", below average");
    outFile.close();
    }

    The printf method does not inlcude a LF/CR. You will have to add it yourself.
    In future when you post code, highlight it and click the CODE button to retain formatting.

  • Need help with java assignment dealing with for loops...

    Hi there. I'm a beginner to java programming and I'm having a lot of difficulty.
    I am trying to do a lab for class right now, and I really don't even know where to begin and to make things worse, someone in my class lost the copies of the class book so I'm extra confused.
    I need to write a method to print a "line" of characters to the screen. The professor said that the method should consume both the character to print (this parameter can be of type char or of type String) and the number of the character to print. The method should use System.out.print().
    e.g. if the method is called printLine, then
    printLine(5,'*');
    printLine(4,'j');
    should print:
    *****jjjj
    I'd really appreciate any help possible! Thank you.

    nevermind. i figured it out.

  • Re: Need help with this assignment. Please see my code and give me tips/advice.

    And your question is?
    My comment so far is:
    You need to be specific in your questions and use code tags.

    And your question is?
    My comment so far is:
    You need to be specific in your questions and use
    code tags.My comment so far is:
    Start coding...

  • I need help with Vector assignment

    So I am not asking you to do the work unless you really feel giving :)
    This is my task for class..."Redo the programing example Election results so that the names of the candidates and the total votes are stored in Vector objects"
    How do I store them in a vector object. An example would be nice but if you can't help then please keep comments to yourself unless they are constructive.

    public static int binSearch(String[] cNames, String name)
             int first, last;
             int mid = 0;
             boolean found;
             first = 0;
             last = cNames.length - 1;
             found = false;
             while (first <= last && !found)
                mid = (first + last) / 2;
                if (cNames[mid].equals(name))
                   found = true;
                else if (cNames[mid].compareTo(name) > 0)
                   last = mid - 1;
                else
                   first = mid + 1;
             if (found)
                return mid;
             else
                return -1;
           public static void processVotes(Scanner inp,
                                        String[] cNames,
                                        int[][] vbRegion)
             String candName;
             int region;
             int noOfVotes;
             int loc;
             while (inp.hasNext())
                candName = inp.next();
                region = inp.nextInt();
                noOfVotes = inp.nextInt();
                loc =  binSearch(cNames, candName);
                if (loc != -1)
                   vbRegion[loc][region - 1] =
                          vbRegion[loc][region - 1] + noOfVotes;
           public static void addRegionsVote(int[][] vbRegion,
                                          int[] tVotes)
             int i, j;
             for (i = 0; i < tVotes.length; i++)
                for (j = 0; j < vbRegion[0].length; j++)
                   tVotes[i] = tVotes[i] + vbRegion[i][j];
           public static void printHeading()
             System.out.println("  ---------------Election Results"
                             + "--------------\n");
             System.out.println("Candidate           "
                             + "       Votes");
             System.out.println("Name       Region1 Region2 "
                             + "Region3 Region4  Total");
             System.out.println("----       ------- ------- "
                             + "------- -------  -----");
           public static void printResults(String[] cNames,
                                        int[][] vbRegion,
                                        int[] tVotes)
             int i, j;
             int largestVotes = 0;
             int winLoc = 0;
             int sumVotes = 0;
             for (i = 0; i < tVotes.length; i++)
                if (largestVotes < tVotes)
    largestVotes = tVotes[i];
    winLoc = i;
    sumVotes = sumVotes + tVotes[i];
    System.out.printf("%-11s ", cNames[i]);
    for (j = 0; j < vbRegion[0].length; j++)
    System.out.printf("%6d ", vbRegion[i][j]);
    System.out.printf("%5d%n", tVotes[i]);
    System.out.println("\n\nWinner: " + cNames[winLoc]
    + ", Votes Received: "
    + tVotes[winLoc]);
    System.out.println("Total votes polled: " + sumVotes);

  • I need help with a assignment im doing....i would really appreciate it

    im new to java programming, so im learning the basics of programing...
    my assigment is that i have to replace a word from a sentence to a different word
    i.e
    have a happy happy christmas
    i have to change happy to horrible
    the output sentence should look like this
    have a horrible happy christmas
    how do i change happy to horrible?
    and + the concept of how i wrote it...am i goign the right direction or no
    this is how i written my program.....any suggestions would do, iw oudl aprreciate it
    import java.util.*;
    public class LastName
         public static void main (String[] args)
         String name;
         int space1 ;
         int length;
         String newname;
         int space2;
         int space3;
         int space4;
         Scanner keyboard = new Scanner (System.in);
         // prompt the user
         System.out.print ("Enter Sentence: ");
         name = keyboard.nextLine ();
         space1 = name.indexOf ( " ");
         length = name.length();
         newname = name.substring (0,18);
         space2 = newname.indexOf (" ");
         System.out.print ("Enter Sentence: ");
         System.out.println (newname);
    }

    Have a look at the replaceFirst(...) method from the String class:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html

  • Need help with calculator project for an assignment...

    Hi all, I please need help with my calculator project that I have to do for an assignment.
    Here is the project's specifications that I need to do"
    """Create a console calculator applicaion that:
    * Takes one command line argument: your name and surname. When the
    program starts, display the date and time with a welcome message for the
    user.
    * Display all the available options to the user. Your calculator must include
    the arithmetic operations as well as at least five scientific operations of the
    Math class.
    -Your program must also have the ability to round a number and
    truncate it.
    -When you multiply by 2, you should not use the '*' operator to perform the
    operation.
    -Your program must also be able to reverse the sign of a number.
    * Include sufficient error checking in your program to ensure that the user
    only enters valid input. Make use of the String; Character, and other
    wrapper classes to help you.
    * Your program must be able to do conversions between decimal, octal and
    hex numbers.
    * Make use of a menu. You should give the user the option to end the
    program when entering a certain option.
    * When the program exits, display a message for the user, stating the
    current time, and calculate and display how long the user used your
    program.
    * Make use of helper classes where possible.
    * Use the SDK to run your program."""
    When the program starts, it asks the user for his/her name and surname. I got the program to ask the user again and again for his/her name and surname
    when he/she doesn't insert anything or just press 'enter', but if the user enters a number for the name and surname part, the program continues.
    Now my question is this: How can I restrict the user to only enter 'letters' (and spaces of course) but allow NO numbers for his/her surname??
    Here is the programs code that I've written so far:
    {code}
    import java.io.*;
    import java.util.*;
    import java.text.*;
    public class Project {
         private static String nameSurname = "";     
         private static String num1 = null;
         private static String num2 = null;
         private static String choice1 = null;
         private static double answer = 0;
         private static String more;
         public double Add() {
              answer = (Double.parseDouble(num1) + Double.parseDouble(num2));
              return answer;
         public double Subtract() {
              answer = (Double.parseDouble(num1) - Double.parseDouble(num2));
              return answer;
         public double Multiply() {
              answer = (Double.parseDouble(num1) * Double.parseDouble(num2));
              return answer;
         public double Divide() {
              answer = (Double.parseDouble(num1) / Double.parseDouble(num2));
              return answer;
         public double Modulus() {
              answer = (Double.parseDouble(num1) % Double.parseDouble(num2));
              return answer;
         public double maximumValue() {
              answer = (Math.max(Double.parseDouble(num1), Double.parseDouble(num2)));
              return answer;
         public double minimumValue() {
              answer = (Math.min(Double.parseDouble(num1), Double.parseDouble(num2)));
              return answer;
         public double absoluteNumber1() {
              answer = (Math.abs(Double.parseDouble(num1)));
              return answer;
         public double absoluteNumber2() {
              answer = (Math.abs(Double.parseDouble(num2)));
              return answer;
         public double Squareroot1() {
              answer = (Math.sqrt(Double.parseDouble(num1)));
              return answer;
         public double Squareroot2() {
              answer = (Math.sqrt(Double.parseDouble(num2)));
              return answer;
         public static String octalEquivalent1() {
              int iNum1 = Integer.parseInt(num1);
    String octal1 = Integer.toOctalString(iNum1);
    return octal1;
         public static String octalEquivalent2() {
              int iNum2 = Integer.parseInt(num2);
              String octal2 = Integer.toOctalString(iNum2);
              return octal2;
         public static String hexadecimalEquivalent1() {
              int iNum1 = Integer.parseInt(num1);
              String hex1 = Integer.toHexString(iNum1);
              return hex1;
         public static String hexadecimalEquivalent2() {
              int iNum2 = Integer.parseInt(num2);
              String hex2 = Integer.toHexString(iNum2);
              return hex2;
         public double Round1() {
              answer = Math.round(Double.parseDouble(num1));
              return answer;
         public double Round2() {
              answer = Math.round(Double.parseDouble(num2));
              return answer;
              SimpleDateFormat format1 = new SimpleDateFormat("EEEE, dd MMMM yyyy");
         Date now = new Date();
         SimpleDateFormat format2 = new SimpleDateFormat("hh:mm a");
         static Date timeIn = new Date();
         public static long programRuntime() {
              Date timeInD = timeIn;
              long timeOutD = System.currentTimeMillis();
              long msec = timeOutD - timeInD.getTime();
              float timeHours = msec / 1000;
                   return (long) timeHours;
         DecimalFormat decimals = new DecimalFormat("#0.00");
         public String insertNameAndSurname() throws IOException{
              boolean inputCorrect = false;
                   while (inputCorrect == false) {
                        while (nameSurname == null || nameSurname.length() == 0) {
                             for (int i = 0; i < nameSurname.length(); i++) {
                             if ((nameSurname.charAt(i) > 'a') && (nameSurname.charAt(i) < 'Z')){
                                       inputCorrect = true;
                        else{
                        inputCorrect = false;
                        break;
                        try {
                             BufferedReader inStream = new BufferedReader (new InputStreamReader(System.in));
                             System.out.print("Please enter your name and surname: ");
                             nameSurname = inStream.readLine();
                             inputCorrect = true;
                        }catch (IOException ex) {
                             System.out.println("You did not enter your name and surname, " + nameSurname + " is not a name, please enter your name and surname :");
                             inputCorrect = false;
                        System.out.println("\nA warm welcome " + nameSurname + " ,todays date is: " + format1.format(now));
                        System.out.println("and the time is now exactly " + format2.format(timeIn) + ".");
                        return nameSurname;
              public String inputNumber1() throws IOException {
              boolean inputCorrect = false;
                   while (inputCorrect == false) {
                        try {
                             BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
                             System.out.print("\nPlease enter a number you want to do a calculation with and hit <ENTER>: ");
                             num1 = br.readLine();
                             double number1 = Double.parseDouble(num1);
                             System.out.println("\nThe number you have entered is: " + number1);
                             inputCorrect = true;
                        } catch (NumberFormatException nfe) {
                             System.out.println("\nYou did not enter a valid number: " + "\""+ num1 + "\" is not a number!!");
                             inputCorrect = false;
                        return num1;
         public String calculatorChoice() throws IOException {
              System.out.println("Please select an option of what you would like to do with this number from the menu below and hit <ENTER>: ");
              System.out.println("\n*********************************************");
              System.out.println("---------------------------------------------");
              System.out.println("Please select an option from the list below: ");
              System.out.println("---------------------------------------------");
              System.out.println("1 - Add");
              System.out.println("2 - Subtract");
              System.out.println("3 - Multiply");
              System.out.println("4 - Divide (remainder included)");
              System.out.println("5 - Maximum and minimum value of two numbers");
              System.out.println("6 - Squareroot");
              System.out.println("7 - Absolute value of numbers");
              System.out.println("8 - Octal and Hexadecimal equivalent of numbers");
              System.out.println("9 - Round numbers");
              System.out.println("0 - Exit program");
              System.out.println("**********************************************");
              boolean inputCorrect = false;
                   while (inputCorrect == false) {
                        try {
                             BufferedReader inStream = new BufferedReader (new InputStreamReader(System.in));
                             System.out.print("Please enter your option and hit <ENTER>: ");
                             choice1 = inStream.readLine();
                             int c1 = Integer.parseInt(choice1);
                             System.out.println("\nYou have entered choice number: " + c1);
                             inputCorrect = true;
                        } catch (NumberFormatException nfe) {
                             System.out.println("You did not enter a valid choice number: " + "\""+ choice1 + "\" is not in the list!!");
                             inputCorrect = false;
                        return choice1;
         public String inputNumber2() throws IOException {
              boolean inputCorrect = false;
                   while (inputCorrect == false) {
                        try {
                             BufferedReader br2 = new BufferedReader (new InputStreamReader(System.in));
                             System.out.print("\nPlease enter another number you want to do the calculation with and hit <ENTER>: ");
                             num2 = br2.readLine();
                             double n2 = Double.parseDouble(num2);
                             System.out.println("\nThe second number you have entered is: " + n2);
                             System.out.println("\nYour numbers are: " + num1 + " and " + num2);
                             inputCorrect = true;
                        } catch (NumberFormatException nfe) {
                             System.out.println("You did not enter a valid number: " + "\""+ num2 + "\" is not a number!!");
                             inputCorrect = false;
                        return num2;
         public int Calculator() {
              int choice2 = (int) Double.parseDouble(choice1);
              switch (choice2) {
                        case 1 :
                             Add();
                             System.out.print("The answer of " + num1 + " + " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 2 :
                             Subtract();
                             System.out.print("The answer of " + num1 + " - " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 3 :
                             Multiply();
                             System.out.print("The answer of " + num1 + " * " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 4 :
                             Divide();
                             System.out.print("The answer of " + num1 + " / " + num2 + " is: " + decimals.format(answer));
                             Modulus();
                             System.out.print(" and the remainder is " + decimals.format(answer));
                             break;
                        case 5 :
                             maximumValue();
                             System.out.println("The maximum number between the numbers " + num1 + " and " + num2 + " is: " + decimals.format(answer));
                             minimumValue();
                             System.out.println("The minimum number between the numbers " + num1 + " and " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 6 :
                             Squareroot1();
                             System.out.println("The squareroot of value " + num1 + " is: " + decimals.format(answer));
                             Squareroot2();
                             System.out.println("The squareroot of value " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 7 :
                             absoluteNumber1();
                             System.out.println("The absolute number of " + num1 + " is: " + decimals.format(answer));
                             absoluteNumber2();
                             System.out.println("The absolute number of " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 8 :
                             octalEquivalent1();
                             System.out.println("The octal equivalent of " + num1 + " is: " + octalEquivalent1());
                             octalEquivalent2();
                             System.out.println("The octal equivalent of " + num2 + " is: " + octalEquivalent2());
                             hexadecimalEquivalent1();
                             System.out.println("\nThe hexadecimal equivalent of " + num1 + " is: " + hexadecimalEquivalent1());
                             hexadecimalEquivalent2();
                             System.out.println("The hexadecimal equivalent of " + num2 + " is: " + hexadecimalEquivalent2());
                             break;
                        case 9 :
                             Round1();
                             System.out.println("The rounded number of " + num1 + " is: " + decimals.format(answer));
                             Round2();
                             System.out.println("The rounded number of " + num2 + " is: " + decimals.format(answer));
                             break;
                        case 0 :
                             if (choice2 == 0) {
                                  System.exit(1);
                             break;
                   return choice2;
              public String anotherCalculation() throws IOException {
                   boolean inputCorrect = false;
                   while (inputCorrect == false) {
                             try {                              
                                  BufferedReader br3 = new BufferedReader (new InputStreamReader(System.in));
                                  System.out.print("\nWould you like to do another calculation? Y/N ");
                                  more = br3.readLine();
                                  String s1 = "y";
                                  String s2 = "Y";
                                  if (more.equals(s1) || more.equals(s2)) {
                                       inputCorrect = true;
                                       while (inputCorrect = true){
                                            inputNumber1();
                                            System.out.println("");
                                            calculatorChoice();
                                            System.out.println("");
                                            inputNumber2();
                                            System.out.println("");
                                            Calculator();
                                            System.out.println("");
                                            anotherCalculation();
                                            System.out.println("");
                                            inputCorrect = true;
                                  } else {
                                       System.out.println("\n" + nameSurname + " thank you for using this program, you have used this program for: " + decimals.format(programRuntime()) + " seconds");
                                       System.out.println("the program will now exit, Goodbye.");
                                       System.exit(0);
                             } catch (IOException ex){
                                  System.out.println("You did not enter a valid answer: " + "\""+ more + "\" is not in the list!!");
                                  inputCorrect = false;
              return more;
         public static void main(String[] args) throws IOException {
              Project p1 = new Project();
              p1.insertNameAndSurname();
              System.out.println("");
              p1.inputNumber1();
              System.out.println("");
              p1.calculatorChoice();
              System.out.println("");
              p1.inputNumber2();
              System.out.println("");
              p1.Calculator();
                   System.out.println("");
                   p1.anotherCalculation();
                   System.out.println("");
    {code}
    *Can you please run my code for yourself and have a look at how this program is constructed*
    *and give me ANY feedback on how I can better this code(program) or if I've done anything wrong from your point of view.*
    Your help will be much appreciated.
    Thanks in advance

    Smirre wrote:
    Now my question is this: How can I restrict the user to only enter 'letters' (and spaces of course) but allow NO numbers for his/her surname??You cannot restrict the user. It is a sad fact in programming that the worst bug always sits in front of the Computer.
    What you could do is checking the input string for numbers. If it contains numbers, just reprompt for the Name.
    AND you might want to ask yourself why the heck a calculator needs to know the users Name.

  • Im DROWNING! need help with a simple java assignment! plz someone help me!

    i need help with my java assignment, with validating a sin number. easy for must who know java. im drowning... please help!

    You will need to store each digit of the social insurance number in a field of its own. To validate the entry you will:
    1. Multiply the 2nd, 4th, 6th and 8th digit by 2.
    2. If the product of any of the four multiplications result in a value greater than 9, add the two resulting digits together to yield a single-digit response. For example 6 * 2 = 12, so you would add the 1 and the 2 to get a result of 3.
    3. Add these four calculated values together, along with the 1st, 3rd, 5th, and 7th digits of the original number.
    4. Subtract this sum from the next highest multiple of 10.
    5. The difference should be equal to the 9th digit, which is considered the check digit.
    Example of validating S.I.N. 765932546
    1st digit 7
    2nd digit (6*2 =12 1+2=) 3
    3rd digit 5
    4th digit (9*2 = 18 1+8 =) 9
    5th digit 3
    6th digit (2*2 = 4) 4
    7th digit 5
    8th digit (4*2 = 8) 8
    Total 44 next multiple of 10 is 50
    50-44 = 6 which is the 9th digit
    Therefore the S.I.N. 765932546 is Valid
    ********* SIN Validation *********
    Welcome - Please enter the first number: 120406780
    Second digit value multiplied by 2 4
    Fourth digit value multiplied by 2 8
    Sixth digit value multiplied by 2 12
    Eighth digit value multiplied by 2 16
    Value derived from 6th digit 3
    Value derived from 8th digit 7
    The total is 30
    Calculated digit is 10
    Check digit must be zero because calculated value is 10
    The SIN 120406780 is Valid
    this is my assignemtn this is what i have! i dont know where to start! please help me!
    /*     File:     sinnumber.java
         Author:     Ashley
         Date:     October 2006
         Purpose: Lab1
    import java.util.Scanner;
    public class Lab1
              public static void main(String[] args)
                   Scanner input = new Scanner(System.in);
                   int sin = 0;
                   int number0, number1, number2, number3, number4, number5, number6, number7, number8;
                   int count = 0;
                   int second, fourth, sixth, eighth;
                   System.out.print("\t\n**********************************");
                   System.out.print("\t\n**********SIN Validation**********");
                   System.out.print("\t\n**********************************");
                   System.out.println("\t\nPlease enter the First sin number: ");
                   sin = input.nextInt();
                   count = int.length(sin);     
                   if (count > 8 || count < 8)
                   System.out.print("Valid: ");
         }

  • Need help with a simple process with FTP Adapter and File Adapter

    I am trying out a simple BPEL process that gets a file in opaque mode from a FTP server using a FTP adapter and writes it to the local file system using a File Adapter. However, the file written is always empty (zero bytes). I then tried out the FTPDebatching sample using the same FTP server JNDI name and this work fine surprisingly. I also verified by looking at the FTP server logs that my process actually does hit the FTP server and seems to list the files based on the filtering condition - but it does not issue any GET or RETR commands to actually get the files. I am suspecting that the problem could be in the Receive, Assign or Invoke activities, but I am not able identify what it is.
    I can provide additional info such as the contents of my bpel and wsdl files if needed.
    Would appreciate if someone can help me with this at the earliest.
    Thanks
    Jay

    persiandude wrote:
    Topic: Need help with if, else, and which statements and loops.
    How would I display 60 < temp. <= 85 in java
    System.out.println("60 < temp. <= 85 in java");
    another question is how do I ask a question like want to try again (y/n) after a output and asking that everytime I type in yes after a output and terminate when saying No.Sun's [basic Java tutorial|http://java.sun.com/docs/books/tutorial/]
    Sun's [New To Java Center|http://java.sun.com/learning/new2java/index.html].Includes an overview of what Java is, instructions for setting up Java, an intro to programming (that includes links to the above tutorial or to parts of it), quizzes, a list of resources, and info on certification and courses.
    [http://javaalmanac.com|http://javaalmanac.com]. A couple dozen code examples that supplement [The Java Developers Almanac|http://www.amazon.com/exec/obidos/tg/detail/-/0201752808?v=glance].
    jGuru. A general Java resource site. Includes FAQs, forums, courses, more.
    JavaRanch. To quote the tagline on their homepage: "a friendly place for Java greenhorns." FAQs, forums (moderated, I believe), sample code, all kinds of goodies for newbies. From what I've heard, they live up to the "friendly" claim.
    Bruce Eckel's [Thinking in Java|http://mindview.net/Books/DownloadSites] (Available online.)
    Joshua Bloch's [Effective Java|http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683/ref=pd_bbs_1?ie=UTF8&s=books&qid=1214349768&sr=8-1]
    Bert Bates and Kathy Sierra's [Head First Java|http://www.amazon.com/exec/obidos/tg/detail/-/0596004656?v=glance].
    James Gosling's [The Java Programming Language|http://www.bookpool.com/sm/0321349806].

  • Need Help with my Imessage

    i need help with my imessage i am using a Iphone 4 ios 6.1.3 but when i go to settings>message>send and reecieve. i only get the options Apple ID: and You can be reached by iMessage at: my current email and add another email. my question is how do i get it to where imessage uses my cell phone number instead of my Email i have looked all over the web and no luck......

    The hidden text should be sent for you automatically by the phone. From personal experience, this is automatic, but something has obviously tripped up somewhere on your phone.
    It appears from reading the documentation, I would first try signing out of your Apple ID by going to Settings > Messages > Send and Receive then press your Apple ID, and press Sign Out. Then sign back in. This should hopefully trigger a re-activation of your mobile number. Your mobile number should be assigned to your Apple ID on first sign-in so hopefully this signing in and out should trigger an automatic re-activation.
    Failing that, others have posted a reset of the phone, as does the support page I quoted. It appears this could be a last resort as a reset can be a bit of a pain (although if you Back your phone up via iTunes, you should be able to restore it to how it is currently). I would try the signing in and out method. Hopefully, fingers crossed, it should kick your phone back into action.

  • Need help with connecting file inputs to arrays

    In this assignment I have a program that will do the following: display a list of names inputed by the user in reverse order, display any names that begin with M or m, and display any names with 5 or more letters. This is all done with arrays.
    That was the fun part. The next part requires me to take the names from a Notepad file, them through the arrays and then output them to a second Notepad file.
    Here is the original program: (view in full screen so that the code doesn't get jumbled)
    import java.io.*;       //Imports the Java library
    class progB                    //Defines class
        public static void main (String[] arguments) throws IOException
            BufferedReader keyboard;                                  //<-
            InputStreamReader reader;                                 //  Allows the program to
            reader = new InputStreamReader (System.in);               //  read the the keyboard
            keyboard = new BufferedReader (reader);                  //<-
            String name;                 //Assigns the name variable which will be parsed into...
            int newnames;               //...the integer variable for the amount of names.
            int order = 0;              //The integer variable that will be used to set the array size
            String[] array;             //Dynamic array (empty)
            System.out.println (" How many names do you want to input?");   //This will get the number that will later define the array
            name = keyboard.readLine ();
            newnames = Integer.parseInt (name);                                         // Converts the String into the Integer variable
            array = new String [newnames];                                               //This defines the size of the array
            DataInput Imp = new DataInputStream (System.in);       //Allows data to be input into the array
            String temp;                                       
            int length;                                                                  //Defines the length of the array for a loop later on
                for (order = 0 ; order < newnames ; order++)                                //<-
                {                                                                           //  Takes the inputed names and
                    System.out.println (" Please input name ");                            //  gives them a number according to
                    temp = keyboard.readLine ();                                           //  the order they were inputed in
                    array [order] = temp;                                                  //<-
                for (order = newnames - 1 ; order >= 0 ; order--)                                //<-
                {                                                                                //  Outputs the names in the reverse 
                    System.out.print (" \n ");                                                   //  order that they were inputed
                    System.out.println (" Name " + order + " is " + array [order]);             //<-
                for (order = 0 ; order < newnames ; order++)                                  //<-
                    if (array [order].startsWith ("M") || array [order].startsWith ("m"))     //  Finds and outputs any and all
                    {                                                                         //  names that begin with M or m
                        System.out.print (" \n ");                                            //
                        System.out.println (array [order] + (" starts with M or m"));         //
                    }                                                                         //<-
                for (order = 0 ; order < newnames ; order++)                                            //<-
                    length = array [order].length ();                                                   //
                    if (length >= 5)                                                                    //  Finds and outputs names
                    {                                                                                  //  with 5 or more letters
                        System.out.print (" \n ");                                                      //
                        System.out.println ("Name " + array [order] + " have 5 or more letters ");      //<-
    }The notepad file contains the following names:
    jim
    laruie
    tim
    timothy
    manny
    joseph
    matty
    amanda
    I have tried various methods but the one thing that really gets me is the fact that i can't find a way to connect the names to the arrays. Opening the file with FileInputStream is easy enough but using the names and then outputing them is quite hard. (unless i'm thinking too hard and there really is a simple method)

    By "connect", do you just mean you want to put the names into an array?
    array[0] = "jim"
    array[1] = "laruie"
    and so on?
    That shouldn't be difficult at all, provided you know how to open a file for reading, and how to read a line of text from it. You can just read the line of text, put it in the array position you want, until the file is exhausted. Then open a file for writing, loop through the array, and write a line.
    What part of all that do you need help with?

  • Need help in my assignment, Java programing?

    Need help in my assignment, Java programing?
    It is said that there is only one natural number n such that n-1 is a square and
    n + 1 is a cube, that is, n - 1 = x2 and n + 1 = y3 for some natural numbers x and y. Please implement a program in Java.
    plz help!!
    and this is my code
    but I don't no how to finsh it with the right condition!
    plz heelp!!
    and I don't know if it right or wrong!
    PLZ help me!!
    import javax.swing.JOptionPane;
    public class eiman {
    public static void main( String [] args){
    String a,b;
    double n,x,y,z;
    boolean q= true;
    boolean w= false;
    a=JOptionPane.showInputDialog("Please enter a number for n");
    n=Double.parseDouble(a);
    System.out.println(n);
    x=Math.sqrt(n-1);
    y=Math.cbrt(n+1);
    }

    OK I'll bite.
    I assume that this is some kind of assignment.
    What is the program supposed to do?
    1. Figure out the value of N
    2. Given an N determine if it is the correct value
    I would expect #1, but then again this seem to be a strange programming assignment to me.
    // additions followI see by the simulpostings that it is indeed #1.
    So I will give the tried and true advice at the risk of copyright infringement.
    get out a paper and pencil and think about how you would figure this out by hand.
    The structure of a program will emerge from the mists.
    Now that I think about it that advice must be in public domain by now.
    Edited by: johndjr on Oct 14, 2008 3:31 PM
    added additional info

  • Need help with a small application

    Hi all, I please need help with a small application that I need to do for a homework assignment.
    Here is what I need to do:
    "Write an application that creates a frame with one button.
    Every time the button is clicked, the button must be changed
    to a random color."
    I already coded a part of the application, but I don't know what to do further.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ColourButton extends JFrame {
         JButton button = new JButton("Change Colour");
         public ColourButton() {
              super ("Colour Button");
              setSize(250, 150);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel panel = new JPanel();
              panel.add(button);
              add(panel);
              setVisible(true);
         public static void main(String[] args) {
              ColourButton cb = new ColourButton();
    }The thing is I'm not sure what Event Listener I have to implement and use as well as how to get the button to change to a random color everytime the button is clicked.
    Can anyone please help me with this.
    Thanks.

    The listener:
    Read this: [http://java.sun.com/docs/books/tutorial/uiswing/components/button.html]
    The random color:
    [Google this|http://www.google.com/search?q=color+random+java]

Maybe you are looking for