Unknown issue for a Monty Hall problem Java program - java

At the end of the program, when it prints out what was behind your door, it gets the default string instead of the mutated one, but the mutated one was called and worked perfectly fine with the previous method. Why?
Also, the answer to what is behind your chosen door always seems to be the bad prize (goat). Is This just a coincidence?
If you spot any other errors in my program please comment below.
This is class 1
package montehallproblem;
import java.util.Random;
public class GameInfo {
private boolean reset;
private String D1;
private String D2;
private String D3;
private String res1;
private String res2;
private int choice;
public GameInfo(){
res1 ="new car";
res2 ="goat";
choice = 404;
reset = false;
// NOTE: If un-mutated, the Door Strings will default to this result every time
D1 = res1;
D2 = res2;
D3 = res2;
}
public void manualSetChoicesAndDoors(String one, String two, int d1, int d2, int d3){
setResult1(one);
setResult2(two);
//NOTE: This allows the OLC to utilize the previously typed prize strings;
if(d1==1){
setDoor1(res1);
}else if(d1==2){
setDoor1(res2);
}else if(d2==1){
setDoor2(res1);
}else if(d2==2){
setDoor2(res2);
}else if(d3==1){
setDoor3(res1);
}else if(d3==2){
setDoor3(res2);
}
}
public void setDoor1(String x){
D1 = x;
}
public void setDoor2(String x){
D2 = x;
}
public void setDoor3(String x){
D3 = x;
}
public void setResult1(String x){
res1 = x;
}
public void setResult2(String x){
res2 = x;
}
public void setChoice(int x){
choice = x;
}
public void setReset(boolean x){
reset = x;
}
public String getDoor1(){
return D1;
}
public String getDoor2(){
return D2;
}
public String getDoor3(){
return D3;
}
public String getResult1(){
return res1;
}
public String getResult2(){
return res2;
}
public int getChoice(){
return choice;
}
public void generatePrizeDoor(){
if(reset){
Random rand = new Random();
int prize = rand.nextInt(3);
//NOTE: this determines which door has the best prize behind it (res1)
switch(prize){
case 1:
setDoor1(getResult1());
setDoor2(getResult2());
setDoor3(getResult2());
break;
case 2:
setDoor1(getResult2());
setDoor2(getResult1());
setDoor1(getResult2());
break;
case 3:
setDoor1(getResult2());
setDoor1(getResult2());
setDoor1(getResult1());
System.out.println("a new game generates...");
}
}
}
public void revealBadDoor(){
//NOTE: This reveals one of the doors with the bad prize in it;
//NOTE: Appends "used" to door string so that it can be detected later
if(getDoor1().contains(getResult2()) && getChoice() != 1){
System.out.println("Monty reveals door one contains a "+getResult2());
setDoor1(getDoor1()+"used");
}else if(getDoor2().contains(getResult2()) && getChoice() != 2){
System.out.println("Monty reveals door two contains a "+getResult2());
setDoor2(getDoor2()+"used");
}else if(getDoor3().contains(getResult2()) && getChoice() != 3){
System.out.println("Monty reveals door one contains a "+getResult2());
setDoor3(getDoor3()+"used");
}
}
public void switchDoorChoice(String x){
//NOTE: This changes your door choice to the door string that doesnt contain "used"
if(x.contains("yes")){
switch(getChoice()){
case 1:
if(getDoor2().contains("used")){
setChoice(3);
}else if(getDoor3().contains("used")){
setChoice(2);
}
break;
case 2:
if(getDoor3().contains("used")){
setChoice(1);
}else if(getDoor1().contains("used")){
setChoice(3);
}
break;
case 3:
if(getDoor2().contains("used")){
setChoice(1);
}else if(getDoor1().contains("used")){
setChoice(2);
}
System.out.println("you choose to switch to door "+getChoice());
}
}else if(x.contains("no"))
System.out.println("You choose to stay with door "+getChoice());
}
}
public void revealPlayerDoor(){
switch(getChoice()){
case 1:
System.out.println("Monty reveals your door contains "+getDoor1());
break;
case 2:
System.out.println("Monty reveals your door contains "+getDoor2());
break;
case 3:
System.out.println("Monty reveals your door contains "+getDoor3());
}
}
}

Related

How would I write a toString and reduce duplicate outputs?

So, I've created a simple app for moving a bug along a wire. The code works well (for the most part) though, I am having a few issues.
When reaching the end of the wire, the program terminates all well and good but I'm getting a double output that it's fallen off the wire when it reaches the end.
I am supposed to be writing a toString for this, but am having a bit of a hard time grasping why and how I should go about doing this.
If someone could assist with this, I'd greatly appreciate it.
import java.util.Scanner;
public class ClassPracticeMain {
public static void main(String [] args) {
Scanner input = new Scanner(System.in);
int userInput;
Bug bug1 = new Bug();
bug1.setInitialPosition();
bug1.setInitialDirection();
System.out.println("Your starting position is " + bug1.initialPosition
+ " and you are facing " + bug1.getCurrentDirection()
);
while (bug1.getExit(1) != 0) {
System.out.println("Which way would you like to move? 1 for left/ 2 for right or 0 for exit");
userInput = input.nextInt();
bug1.move(userInput);
bug1.getCurrentDirection();
bug1.getCurrentPosition();
System.out.println("You are now at " + bug1.currentPosition + " and you are facing " + bug1.getCurrentDirection());
bug1.getExit(userInput);
}
}
}
public class Bug {
final int WIRELEFTEND=-15;
final int WIRERIGHTEND=15;
int initialPosition=0, currentPosition=0, direction,exit=1;
String currentDirection;
String left = "left";
String right = "right";
public int setInitialPosition(){
return initialPosition;
}
public int setInitialDirection(){
direction=1;
return direction;
}
public int getCurrentPosition(){
return currentPosition;
}
public String getCurrentDirection(){
if (direction== 1){
currentDirection=left;
} else if (direction == 2){
currentDirection=right;
}
return currentDirection;
}
public int move(int move){
if(move==1 && direction==1){
currentPosition=currentPosition-1;
return currentPosition;
} else if (move==1 && direction==2){
direction=1;
return currentPosition;
} else if (move==2 && direction==1){
direction=2;
return currentPosition;
} else if (move==2 && direction ==2){
currentPosition=currentPosition+1;
return currentPosition;
}
return 0;
}
public int getExit(int exit){
if(currentPosition<(WIRELEFTEND)||currentPosition>WIRERIGHTEND){
System.out.println("You've fallen off the wire... Oh no!");
exit=0;
} else{
exit=exit;
}
return 1;
}
}
You probably want to write
public int getExitStatus(){
if(currentPosition<(WIRELEFTEND)||currentPosition>WIRERIGHTEND){
System.out.println("You've fallen off the wire... Oh no!");
return 0;
}
return 1;
}
instead of your current getExist(int) function. It always returns 1, and setting the exit argument doesn't do anything.

Using .split to process user input

I am creating a text-adventure game in Java in which the user enters commands such as 'H' for help or 'N' to move North. In certain cases, the user will need to enter something such as 'T key' to take a key that is in that room. So because of this I need to use the split method to split the command and the item that the user wants to take. I'm getting really stuck in the return part as in some cases the string returned will only be the command if they enter one letter and in other cases it will be both the command and item. All help is appreciated!
This is my code in the main class:
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
public class GameEngine {
private Scanner userInput = new Scanner(System.in);
private Player player1 = new Player("playerName", 0);
private int currentLocation = player1.currentRoom;
private boolean stillPlaying = true; //When this is true, the game continues to run
private Item[] items = {
new Item ("map","a layout of your house", 10 ),
//new Item ("battery", "a double A battery", 5),
new Item ("battery", "a double A battery", 5),
new Item ("flashlight", "a small silver flashlight", 10),
new Item ("key", "this unlocks some door in your house", 15),
};
//Locations {roomName, description, item}
private Locale[] locales = {
new Locale("bedroom","You see the outline of a bed with your childhood stuffed bear on it.",items[0]),
new Locale("hallway","A carpeted floor and long pictured walls lie ahead of you.",null),
new Locale("kitchen","The shining surface of your stove reflects the pale moonlight coming in the window over the sink.",items[1]),
new Locale("bathroom","You find yourself standing in front of a mirror, looking back at yourself.",items[2]),
new Locale("living room","You stub your toe on the sofa in the room, almost falling right into the TV.",null),
new Locale("dining room","You bump the china cabinet which holds your expensive dishes and silverware.",items[3]),
new Locale("office","The blinking light from the monitor on your desk can be seen in the dark",null),
new Locale("library","The smell of old books surrounds you.",null),
new Locale("basement","You reach the top of some stairs and upon descending down, you find the large metal generator.",null),
};
//Matrix for rooms
private int[][] roomMap = {
// N,E,S,W
{6,1,-1,-1}, //Bedroom (room 0)
{4,2,3,0}, //Hallway (room 1)
{-1,-1,5,1}, //Kitchen (room 2)
{1,-1,-1,-1}, //Bathroom (room 3)
{-1,7,1,-1}, //Living Room (room 4)
{2,-1,-1,-1}, //Dining Room (room 5)
{-1,-1,0,-1}, //Office (room 6)
{8,-1,-1,4}, //Library (room 7)
{-1,-1,7,-1} //Basement (room 8)
};
private BreadcrumbTrail trail = new BreadcrumbTrail();
//Move method
private String[] dirNames = {"North", "East", "South", "West"};
//Welcome Message
public void displayIntro(){
System.out.println("\tWelcome to Power Outage!");
System.out.println("=================================================");
System.out.print("\tLet's start by creating your character.\n\n\tWhat is your name? ");
//Will read what name is entered and return it
player1.playerName = userInput.nextLine();
System.out.println("\n\tHello, " +player1.playerName+ ". Let's start the game! \n\n\tPress any key to begin.");
System.out.print("=================================================");
//Will move to next line when key is pressed
userInput.nextLine();
System.out.println("\tYou wake up in your bedroom. \n\n\tThe power has gone out and it is completely dark.");
System.out.println("\n\tYou must find your way to the basement to start the generator.");
}
private void displayMoveInfo(){
System.out.println("\n\tMove in any direction by typing, 'N', 'S', 'E', or 'W'.");
System.out.println("\n\tTake an item from a room by pressing 'T'.");
System.out.println("\n\tTo go back to the room you were just in type 'B'.");
System.out.println("\n\tType 'H' at any time for help and 'Q' to quit the game. Good luck!");
System.out.println("\n\tPress any key.");
}
private void move(int dir) {
int dest = roomMap[currentLocation][dir];
if (dest >= 0 && dest != 8) {
System.out.println("=================================================");
System.out.println("\tYou have moved " + dirNames[dir]);
currentLocation = dest;
System.out.println("\n\tYou are in the "+locales[currentLocation].roomName+".");
System.out.println("\n\t"+locales[currentLocation].description);
Locale locale = locales[currentLocation];
itemPresent();
//Drop breadcrumb at current location
trail.dropCrumb(currentLocation);
}
//If the player reaches the basement and wins
else if (dest == 8){
System.out.println("\tCongratulations!! You have found the basement and turned on the generator! \n\n\tYou have won the game!");
System.out.println("\n\tTHANKS FOR PLAYING!!!!!!");
System.out.println("\n\tCopyright 2016 \n\n");
stillPlaying = false;
}
//If dest == -1
else {
System.out.println("\tThere is no exit that way, please try again.");
}
}//End of Move
private void itemPresent(){
Locale locale = locales[currentLocation];
if(locale.item != null){
System.out.println("\n\tThere is a " + locale.item + " in this room.");
}
else{
System.out.println("\n\tThere is no item in this room.");
}
}
public Command getCommandFromResponse(String response) throws IllegalArgumentException{
String[] split = response.split(" ");
if(split.length < 1){
throw new IllegalArgumentException("Invalid command.");
}
Command command = new Command(split[0]);
if(split.length >= 2) {
command.setItem(split[1]);
}
return command;
}
//All possible responses to keys pressed
public void processInput(){
displayMoveInfo();
Command userCommand = getCommandFromResponse(userInput.nextLine());
while(stillPlaying){
if(player1.currentRoom != 8 && !"Q".equalsIgnoreCase(userCommand.getCommand()) ){
//Map
if(userCommand.command.equalsIgnoreCase("M")){
//only print if the player has the map
//String[] inventory = player1.inventory;
int mapFoundAt = -1;
if(player1.inventory != null){
for(int i=0; i < player1.inventory.size(); i++){
Item checkItem;
checkItem = player1.inventory.get(i);
if(checkItem.itemName.equals("map")){
mapFoundAt = i;
break;
}
}
if(mapFoundAt >=0 ){
System.out.println("Here is your map: \n\n\t\t\tbasement\n\noffice\t living room\tlibrary\n\nbedroom\t hallway\tkitchen\n\n\t bathroom \tdining room");
}
else{
System.out.println("\tYou do not have the map in your inventory.");
}
}
else{
System.out.println("\tYou don't have any items in your inventory.");
}
break;
}//End of Map
//Take
else if(userCommand.command.equalsIgnoreCase("T")){
Locale locale = locales[currentLocation];
if(userCommand.command.equalsIgnoreCase("T")){
}
if(locale.item != null){
//-User must enter item name with the command
System.out.println("Enter the command and item you would like to take.");
userCommand = getCommandFromResponse(userInput.nextLine());
if(userCommand.command.equals(locale.item.itemName)){
//-add the item to the player's inventory
player1.inventory.add(locale.item);
System.out.println("\tA " + locale.item + " was added to your inventory");
if(locale.item.itemName.equals("map")){
System.out.println("\n\tTo view the map press 'M'.");
}
//-remove the item from the current location
locale.item = null;
System.out.println("\n\tYou can view your inventory by pressing 'I' or drop an item by pressing 'D'.");
//-Add the item's worth to the score and set the items worth to zero to prevent double scoring
player1.score += locale.item.value;
System.out.println(locale.item.value + " points have been added to your score.");
System.out.println("\n\tThis is your current score: "+player1.score);
}
else{
System.out.println("That item is not at this location.");
}
}
else{
System.out.println("There is no item to pick up here");
}
}//End of Take
//Help
else if(userCommand.command.equalsIgnoreCase("H")){
displayMoveInfo();
break;
}
//Inventory
else if(userCommand.command.equalsIgnoreCase("I")){
if(player1.inventory != null){
System.out.println("\tThese are the items in your inventory: "+player1.inventory+".");
}
else{
System.out.println("\tYou currently have no items in your inventory.");
System.out.println("\tTo pick up an item in a room, press 'T'.");
}
break;
}
//Drop
else if(userCommand.command.equalsIgnoreCase("D")){
//Show the list of items in the player's inventory with numbers associated with them
if(player1.inventory.size() != 0){
System.out.println("\tThese are the items available to drop: " +player1.inventory);
}
else if(player1.inventory.size() == 0){
System.out.println("\tYou have no items in your inventory to drop.");
break;
}
System.out.println("\tEnter the name of the item you would like to drop.");
String itemToDrop = userInput.nextLine();
Locale locale = locales[currentLocation];
if(locale.item == null){
for(int i=0; i < player1.inventory.size(); i++){
Item checkItem;
checkItem = player1.inventory.get(i);
if(checkItem.itemName.equalsIgnoreCase(itemToDrop)){
//Remove item entered from a player's inventory
System.out.println("\tYou have dropped the " +checkItem.itemName+ ".");
player1.inventory.remove(i);
//Place the item at the player's current location so it can be picked up again
locale.item = checkItem;
//Subtract five points from the player's score
player1.score -= 5;
System.out.println("\tFive points have been subtracted from your score.");
System.out.println("\n\tThis is your current score: "+player1.score);
}
else if(i==player1.inventory.size() && checkItem.itemName != itemToDrop){
System.out.println("\tThat is not an item in your inventory.");
break;
}
}
}
else{
System.out.println("\tThere is already an item at this location, you can't drop an item.");
}
break;
}//End of Drop
//Backtrack
else if(userCommand.command.equalsIgnoreCase("B")){
//Pick up breadcrumb
trail.pickupCrumb();
if(trail.hasMoreCrumbs() == false){
//Move to previous crumb
currentLocation = trail.currentCrumb();
System.out.println("\n\tYou are in the "+locales[currentLocation].roomName+".");
System.out.println("\n\t"+locales[currentLocation].description);
itemPresent();
}
//When the trail is empty, drop the last breadcrumb, don't move the player again
else{
trail.dropCrumb(currentLocation);
System.out.println("\tYou are at the beginning of your breadcrumb trail, you can't backtrack any more.");
}
break;
}//End of Backtrack
//North
else if(userCommand.command.equalsIgnoreCase("N")){
move(0);
break;
}
//East
else if(userCommand.command.equalsIgnoreCase("E")){
move(1);
break;
}
//South
else if(userCommand.command.equalsIgnoreCase("S")){
move(2);
break;
}
//West
else if(userCommand.command.equalsIgnoreCase("W")){
move(3);
break;
}
//If any key is pressed other than those above
else{
System.out.println("\tInvalid command!");
break;
}
}//End of Quit if statement
else if(userCommand.command.equalsIgnoreCase("Q")){
System.out.println("Thanks for playing!\n\n");
stillPlaying = false;
}
}//End of while
}//End of pressedKey method
public void play(){
displayIntro();
System.out.println("=================================================");
System.out.println("\tYou are in the bedroom.");
Locale locale = locales[currentLocation];
itemPresent();
trail.dropCrumb(currentLocation);
//This makes the game continue to loop
while(stillPlaying){
System.out.println("=================================================");
System.out.println("\tMove in any direction.");
processInput();
} //End of while
}
public static void main(String[] args) {
GameEngine game = new GameEngine();
game.play();
} //End of main
} //End of class
This is my Player Class:
import java.util.ArrayList;
public class Player {
//Player class must have name, location, inventory, and score
public String playerName;
public ArrayList<Item> inventory;
public int score;
public int currentRoom;
public Player(String playerName, int currentRoom){
this.playerName = playerName;
this.inventory = new ArrayList<Item>();
this.score = 0;
this.currentRoom = currentRoom;
}
}
This is the Command class:
class Command{
String command;
String item;
public Command(String comm){
command = comm;
}
public Command(String comm, String item){
this.command = comm;
this.item = item;
}
public void setCommand(String command){
this.command = command;
}
public void setItem(String item){
this.item = item;
}
public String getCommand(){
return this.command;
}
public String getItem(){
return this.item;
}
public String toString(){
return this.command + ":" + this.item;
}
}
This is my Locale class:
public class Locale {
//Locale must have name, description, and Item
public static int roomNumber;
public String roomName;
public String description;
public Item item;
public Locale(String roomName, String description, Item item){
this.roomName = roomName;
this.description = description;
this.item = item;
}
}
This is my Item class:
public class Item {
//item must have a name and a description (both strings)
public String itemName;
public String itemDes;
public boolean isDiscovered;
public int value;
public Item (String itemName, String itemDes, int value){
this.itemName = itemName;
this.itemDes = itemDes;
this.isDiscovered = false;
this.value = value;
}
public String toString(){
return itemName + "(" + itemDes + ")";
}
}
This is my BreadcrumbTrail class:
public class BreadcrumbTrail {
//dropCrumb (push)
//pickupCrumb (pop)
//currentCrumb (peek)
//hasMoreCrumbs (empty)
//Drop a new breadcrumb whenever the player arrives at a local
class Node{
int data;
Node link;
Node(int s, Node l){
this.data = s; //element stored at the node
this.link = l; //link to another node
}
}//End of Node class
private Node currentCrumb;
//Constructor
public BreadcrumbTrail(){
this.currentCrumb = null;
}
//pop
public void pickupCrumb(){
this.currentCrumb = this.currentCrumb.link;
}
//push
public void dropCrumb(int s){
Node newNode = new Node(s, this.currentCrumb);
this.currentCrumb = newNode;
}
//top or peek
public int currentCrumb(){
return this.currentCrumb.data;
}
//isEmpty
public boolean hasMoreCrumbs(){
return this.currentCrumb == null;
}
}
In the pressedkey method now the if else statements obviously don't work as I now need to change the part in front of .equals.
All previous answers are decent. However, I think you are better off validating the user input and if the user enters the incorrect number of objects, throw an exception to indicate invalid input instead of just logging it. It makes the code more manageable, reads better, and give you an opportunity to deal with invalid input properly:
public Command getCommandFromResponse(String response) throws IllegalArgumentException{
String[] split = response.split(" ");
if(split.length < 1){
throw new IllegalArgumentException("Invalid command.");
}
if(split.length < 2){
throw new IllegalArgumentException("You must enter an item.");
}
return new Command(split[0], split[1]);
}
class Command{
String command;
String item;
public Command(){
command = null;
item = null;
}
public Command(String comm, String item){
this.command = comm;
this.item = item;
}
public void setCommand(String command){
this.command = command;
}
public void setItem(String item){
this.item = item;
}
public String getCommand(){
return this.command;
}
public String getItem(){
return this.item;
}
public String toString(){
return this.command + ":" + this.item;
}
}
Create a class like this:
class UserInput {
private String command;
private String item;
public UserInput() {
command = "";
item = "";
}
public void setCommand(String command) {
this.command = command;
}
public void setItem(String item) {
this.item = item;
}
}
And return an instance of it.
String response = userInput.nextLine();
String[] split = response.split(" ");
UserInput input = new UserInput();
if (split.length > 0) {
input.setCommand(split[0]);
if (split.length == 2) {
input.setItem(split[1]);
}
return input;
}
System.out.println("Invalid command");
return null;
Scanner userInput = new Scanner(System.in);
String response = userInput.nextLine();
String command = null;
String item = null;
String[] split = response.split(" ");
if (split.length == 1) {
command = split[0];
} else if (split.length == 2) {
command = split[0];
item = split[1];
} else {
System.out.println("Invalid command");
}
System.out.println(command + "/" + item);
userInput.close();
if user input contains only command, then don't run the loop. Move your
if(split.length == 0){
String command = split[0];
return command;
}
before the loop.
String response = userInput.nextLine();
String[] split = response.split(" ");
if(split.length == 0){
String command = split[0];
return command;
}
for(int i=0; i < split.length; i++){
//use simple java class to store the result
if(split.length == 1){
String item = split[1];
return item;
}
else{
System.out.println("Invalid command");
}
}

Remove User Duplicate From Array String

I am trying to create a program that accepts as many Social Security Numbers as the user wants to input. The only restriction is that the numbers must follow the format XXX-XX-XXXX and not accept duplicated entries. This is what I have so far:
Subclass 2
package SSNServerStorageExpanded;
class SSNArray{
final String[] ssnNumber;
int arrayCount;
public SSNArray(){//defult contructor
ssnNumber = new String[9999];
arrayCount = 0;
}
public SSNArray(int arraySize){
ssnNumber = new String[arraySize];
arrayCount = 0;
}
public String[] getSSNNumber(){
return ssnNumber;
}
public int getArrayCount(){
return arrayCount;
}
public boolean validateSSNNumber(String SSNFormat){
return SSNFormat.matches("\\d{3}-\\d{2}-\\d{4}");
}
public String addSSN(String SSNFormat){
if(validateSSNNumber(SSNFormat)){
return ssnNumber[arrayCount++] = SSNFormat;
}else{
return null;
}
}
#Override
public String toString(){
String str = "\nThe Social Security Number(s) you entered is(are):\n";
for(int x = 0; x < arrayCount; x++){/
str += ssnNumber[x] + "\n";
}return str;
}
}
Subclass 1
package SSNServerStorageExpanded;
public class SSNArrayExpanded extends SSNArray{
public SSNArrayExpanded(){
super();
}
public SSNArrayExpanded(int arraySize){
super(arraySize);
}
#Override
public boolean validateSSNNumber(String SSNFormat){
if(super.validateSSNNumber(SSNFormat)){
boolean duplicate = false;
for(int y = 0; y < arrayCount; y++){
if(ssnNumber[y].equals(ssnNumber[arrayCount])){
System.out.println("No duplicates allowed, please try again");
duplicate = true;
break;
}
}
if(!duplicate){
arrayCount++;
}
}
return true;
}
}
Mainclass
package SSNServerStorageExpanded;
import java.util.Scanner;
public class SSNArrayTestExpanded{
public static void main(String[] args){
SSNArrayExpanded SSNArrayExpandedObject = new SSNArrayExpanded();
Scanner input = new Scanner(System.in);
System.out.println("Initiating SSN Server Storage Expanded");
System.out.println("► Type 'EXIT' at any moment to close the program ◄\n");
boolean run = true;
while(run){
System.out.print("Enter your Social Security Number(XXX-XX-XXXX): ");
String ssnNumber = input.next();
if(ssnNumber.equalsIgnoreCase("EXIT")){
System.out.print(SSNArrayExpandedObject.validateSSNNumber(ssnNumber));
return;
}else if(SSNArrayExpandedObject.validateSSNNumber(ssnNumber)){
SSNArrayExpandedObject.addSSN(ssnNumber);
}else{
System.out.println("!Please use the format XXX-XX-XXXX!");
}
}
}
}
What am I doing wrong with my public boolean validateSSNNumber method under Subclass 1 or are there more errors in my code that I am not aware of?
In your subclass1 can you try this. You need to compare the SSNFormat String entered by user with the array values (you were comparing array values itself). Do not increase the array count here instead do it in addSSN function as you were doing.
#Override
public boolean validateSSNNumber(String SSNFormat){
if(super.validateSSNNumber(SSNFormat)){
boolean duplicate = false;
for(int y = 0; y < arrayCount; y++){
if(ssnNumber[y].equals(SSNFormat)){
System.out.println("No duplicates allowed, please try again");
duplicate = true;
break;
}
}
if(!duplicate){
return true;
}
}
return false;
}
In the SSNArray class use this function for adding SSN number without validating the SSNFormat again.
public String addSSN(String SSNFormat){
return ssnNumber[arrayCount++] = SSNFormat;
}
You can try using a Set, which will easily help you to check for any duplicates and will reduce your iteration over array.
Why cant you go for LinkedHashSet data structure for storing the ssn number.?, provides easy retrieval and duplicate check in an order of O(1).
final LinkedHashSet<String> ssnNumber;
also the code
#Override
public boolean validateSSNNumber(String SSNFormat){
if(super.validateSSNNumber(SSNFormat)){
boolean duplicate = ssnNumber.add(SSNFormat);
if(duplicate){
System.out.println("No duplicates allowed, please try again");
return false;
}
return true;
}
return false
}
Here is your complete Solution, with this you can add N-number of SSN-Number as you want,
import java.util.HashSet;
import java.util.Scanner;
class SSNSet{
final HashSet<String> allSsnNumber = new HashSet<String>();
public HashSet<String> getAllSsnNumber() {
return allSsnNumber;
}
public boolean validateSSNNumber(String SSNFormat){
return SSNFormat.matches("\\d{3}-\\d{2}-\\d{4}");
}
public boolean addSSN(String SSNFormat){
if(validateSSNNumber(SSNFormat)){
boolean flag;
if(allSsnNumber.add(SSNFormat)){
System.out.println("Added Successfully");
flag = true;
}else{
System.out.println("Duplicate Not Allow");
flag = false;
}
return flag;
}else{
System.out.println("!Please use the format XXX-XX-XXXX!");
return false;
}
}
}
public class SSNArrayTestExpanded{
public static void main(String[] args){
SSNSet SSNArrayExpandedObject = new SSNSet();
Scanner input = new Scanner(System.in);
System.out.println("Initiating SSN Server Storage Expanded");
System.out.println(" Type 'EXIT' at any moment to close the program \n");
boolean run = true;
while(run){
System.out.print("Enter your Social Security Number(XXX-XX-XXXX): ");
String ssnNumber = input.next();
if(ssnNumber.equalsIgnoreCase("EXIT")){
break;
/*System.out.print(SSNArrayExpandedObject.validateSSNNumber(ssnNumber));
return;*/
}else{
SSNArrayExpandedObject.addSSN(ssnNumber);
}
}
System.out.println("===============================================");
System.out.println("You have entered SSN Numbers are : ");
System.out.println(SSNArrayExpandedObject.getAllSsnNumber());
System.out.println("===============================================");
System.out.println("Program Ended Successfully");
}
}
and Output is :
Initiating SSN Server Storage Expanded
Type 'EXIT' at any moment to close the program
Enter your Social Security Number(XXX-XX-XXXX): 111-11-1111
Added Successfully
Enter your Social Security Number(XXX-XX-XXXX): 222-22-222
!Please use the format XXX-XX-XXXX!
Enter your Social Security Number(XXX-XX-XXXX): 111-11-1111
Duplicate Not Allow
Enter your Social Security Number(XXX-XX-XXXX): 333-33-333
!Please use the format XXX-XX-XXXX!
Enter your Social Security Number(XXX-XX-XXXX): 333-33-3333
Added Successfully
Enter your Social Security Number(XXX-XX-XXXX): EXIT
===============================================
You have entered SSN Numbers are :
[111-11-1111, 333-33-3333]
===============================================
Program Ended Successfully
public boolean validateSSNNumber(String SSNFormat) {
if (super.validateSSNNumber(SSNFormat)) {
/*
*Hashset add() - Returns true if this set did not already contain
*the specified element.
*If this set already contains the element, the call leaves the set
* unchanged and returns
*/
boolean duplicate = !uniqueSSNNum.add(SSNFormat);
return duplicate;
}
return false;
}
//To use HastSet it's better if you override equals and hashcode
//using the fields that you'll use for comparison equality
// generated using eclipse
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + arrayCount;
result = prime * result + Arrays.hashCode(ssnNumber);
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SSNArray other = (SSNArray) obj;
if (arrayCount != other.arrayCount)
return false;
if (!Arrays.equals(ssnNumber, other.ssnNumber))
return false;
return true;
}

Error: Could not find or load main class vehicle.Vehicle

I am still at HelloWorld when it comes to my lack of Java skills. I cannot understand this to save my life. I am working on writing an override method? And am just starting out with the code provided from my school before I even start trying to complete the rest and I am already getting errors that I cannot even begin to think of how to correct. Any help at all would be greatly appreciated. I just want this error to go away so I can create some new ones :)
Here is the code:
public class Vehicle
public static void main (String [] args)}
{
private boolean moving; // whether or not the vehicle
private double speed;
private char bearing;
('N','E','S', or 'W')
public Vehicle(){ // Vehicle class no-arg constructor
moving = false; // assume not moving
speed = 0.0; // not moving
bearing = 'N'; // assume 'N'orth
System.out.println("Created a vehicle (no-arg)");
}
public Vehicle (double initialSpeed) // Vehicle 1-arg constructor
bearing = 'W';
speed = initialSpeed;
if (speed > 0.0)
{
moving = true;
}
System.out.println("Created a vehicle (1-arg)");
public Vehicle (double initialSpeed, char initialBearing) // Vehicle 2-arg constructor
bearing = initialBearing;
speed = initialSpeed;
if (speed > 0.0){
moving = true;
}
System.out.println("Created a vehicle (2-arg)");
public void start(double initialSpeed, char initialBearing){
moving = true;
if (initialSpeed >= 5.0 && initialSpeed <= 20.0){
speed = initialSpeed; // valid expected range
} else if (initialSpeed >= 0.0 && initialSpeed < 5.0){
speed = 5.0; // minimum
} else if (initialSpeed < 0.0){
speed = 0.0; // assume no movement
moving = false;
} else if (initialSpeed > 20.0){
speed = 20.0; // maximum allowed
}
switch(initialBearing){
case 'N':
bearing = initialBearing;
break;
case 'E':
bearing = initialBearing;
break;
case 'S':
bearing = initialBearing;
break;
case 'W':
bearing = initialBearing;
default:
System.out.println("invalid bearing " +
initialBearing +
" set to N"); // additional user notification
bearing = 'N';
}
public double getSpeed() { // get and return current speed in mph
return speed;
}
public void setSpeed(double newSpeed){ // set new speed in mph
speed = newSpeed;
}
/**
*
* #return
*/
public char getBearing(){
return bearing;
}
public void speedUp(double mphSteps, int numSteps){
int counter = 0;
while (counter < numSteps)
speed += mphSteps;
System.out.println("counter= " + counter + ", " +
this.toString());
counter++;
}
public String toString(){
return "From toString(): speed= " + getSpeed() +
" mph and bearing= " + getBearing();
}
}
public class Car extends Vehicle{
private String color;
private int doors;
private double hp;
public Car(String carColor, int numDoors,
double horsePower, double
startingSpeed)
{
super(startingSpeed);
color = carColor;
doors = numDoors;
hp = horsePower;
System.out.println("Created a car");
}
public String getColor()
{
return color;
}
public int getDoors()
{
return doors;
}
public double getHp()
{
return hp;
}
public String toString()
{
return "From Car toString(): color= " + getColor() +
" doors= " + getDoors() +
" hp= " + getHp() +
" speed= " + getSpeed() +
" mph and bearing= " + getBearing();}
}
public class TestCar2
{
public static void main(String[] args)
{
Car myCar2 = new Car("blue", 4, 300., 10.0);
System.out.println(myCar2.toString());
myCar2.speedUp(5.0, 2);
}
}
Please Please and thank you for helping!
public class Vehicle
public static void main (String [] args)} // this is totally wrong
// This not compile at least
{
Actually parenthesis({}) you are using is totally wrong. Following structure should follow you. I am guessing that you are not using IDE to do coding. I suggest you to use IDE to do code.
public class MyClass{
public static void main(String[] args){
// main method
}
// some other method
}
Firstly You cannot have two public classes in a single file!!
Secondly you braces are completely unmatching.
public class Vehicle
public static void main (String [] args)}
{
Class has it's own scope and main() function has it's own. So change your code to
public class Vehicle {
public static void main (String [] args) { //your code}
}
your multiple arg constructors don't have proper brackets.
public Vehicle (double initialSpeed) // Vehicle 1-arg constructor
bearing = 'W';
speed = initialSpeed;
if (speed > 0.0)
{
moving = true;
}
System.out.println("Created a vehicle (1-arg)");
change it to
public Vehicle (double initialSpeed) { // Vehicle 1-arg constructor
bearing = 'W';
speed = initialSpeed;
if (speed > 0.0)
{
moving = true;
}
System.out.println("Created a vehicle (1-arg)");
}
lastly your switch statement you need to put break in all cases(except default)
change
case 'W':
bearing = initialBearing;
to
case 'W':
bearing = initialBearing;
break;
If you are new to java and learning basics I suggest use an IDE like Eclipse, Netbeans or Intellij IDEA. Google them to find more info.

How do I run a (pseudo)main method with an applet?

I'm a beginner/intermediate java programmer that is attempting to code something that is "out-of-my-league". The program is supposed to judge a boxing/MMA match in real time by pressing keys that correspond to different scoring values. I've figured out that I need a KeyListener, and the only way I've found to use that is with an applet.
The problem I've run into is the only cues I have to print out a score come from keyPresses and keyReleases. I want the score to print EVERY second, along with the time. I'm made a clock function and can print every second using another class with a main method, but I don't know how to do this in the applet.
Here's what I have so far:
import java.applet.Applet;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.*;
public class KeyPressTwo
extends Applet
implements KeyListener{
private long t;
private ArrayList<Integer> keysDown = new ArrayList<Integer>();
private double controlOnlyValue = 1; //Stores the score per second for control only
private double threateningValue = 2.5; //Score for threatening with strikes, i.e. landing sig strikes, or sub attempts
private double damagingValue = 4; //Score for doing significant damage and dominating hea
private static double redTotal = 0; //Stores fighter score
private static double blueTotal = 0;
private static boolean firstRun = true;
private static boolean start = false;
private static boolean releasePressed = false; //Tells KeysReleased method when to wipe keysDown list
private static long roundBeganAt = 0; //System time when the round began 5
private static String redName;
private static String blueName;
public void init(){
this.addKeyListener(this);
//If names aren't hardcoded in, get them when the program is run
if (redName == null){
redName = JOptionPane.showInputDialog("Enter the red corner fighter's name.");
blueName = JOptionPane.showInputDialog("Enter the blue corner fighter's name.");
}
}
public void paint(){
setSize(500,500);
}
#Override
public void keyPressed(KeyEvent e) {
if(!keysDown.contains(e.getKeyCode()))
keysDown.add(e.getKeyCode());
//Starts the timer, don't print anything until started
if(keysDown.contains(KeyEvent.VK_SPACE)){
start = true;
roundBeganAt = System.currentTimeMillis();
}
//If it's been more than 1s
if(nextStep()){
//If space has been pushed
if(start){
if(keysDown.contains(KeyEvent.VK_Z) || keysDown.contains(KeyEvent.VK_NUMPAD1)){
redTotal += controlOnlyValue;
}
if(keysDown.contains(KeyEvent.VK_X) || keysDown.contains(KeyEvent.VK_NUMPAD4)){
redTotal += threateningValue;
}
if(keysDown.contains(KeyEvent.VK_C) || keysDown.contains(KeyEvent.VK_NUMPAD7)){
redTotal += damagingValue;
}
if(keysDown.contains(KeyEvent.VK_COMMA) || keysDown.contains(KeyEvent.VK_NUMPAD3)){
blueTotal += controlOnlyValue;
}
if(keysDown.contains(KeyEvent.VK_M) || keysDown.contains(KeyEvent.VK_NUMPAD6)){
blueTotal += threateningValue;
}
if(keysDown.contains(KeyEvent.VK_N) || keysDown.contains(KeyEvent.VK_NUMPAD9)){
blueTotal += damagingValue;
}
System.out.print("\n" +redName +": " +redTotal +" \t" +blueName +": " +blueTotal +"\t\t" +time());
releasePressed = true;
}
}
}
//Prints time since start (e.g. 2:05)
private static String time() {
String minutes = "";
String seconds = "";
int sRaw; //Gets time directly from system, will go above 60
int s; //Gets time from sRaw, (0 - 59)
sRaw = (int)((System.currentTimeMillis() - roundBeganAt))/1000;
s = sRaw%60;
minutes = Integer.toString(sRaw/60);
if(s < 10)
seconds = "0" +Integer.toString(s);
else seconds = Integer.toString(s);
return minutes +":" +seconds;
}
//Returns true if it's been more than1s since the last time it ran
public boolean nextStep() {
if(firstRun){
t = System.currentTimeMillis();
firstRun = false;
return true;
}
if(System.currentTimeMillis() > t + 1000){
t = System.currentTimeMillis();
return true;
}else
return false;
}
public void printList(){
for(int i : keysDown)
System.out.print(i +" ");
System.out.println();
}
#Override
public void keyReleased(KeyEvent e) {
if(releasePressed){
keysDown.clear();
releasePressed = false;
}
}
#Override
public void keyTyped(KeyEvent e) {
}
}
Maybe something along these lines would work for you:
Thread timerOutputThread = new Thread(new Runnable(){
public boolean running = true;
public void run(){
output();
}
private void output(){
try {
Thread.sleep(1000);
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("PRINT THE SCORE HERE");
if(running){
output();
}
}
});
timerOutputThread.start();
Stick that code wherever you want the Thread timer to be started, and then fill in that spot where it says "PRINT THE SCORE HERE".
I've figured out that I need a KeyListener,.."
Or preferably key bindings.
..and the only way I've found to use that is with an applet.
Where on Earth did you hear that?!? It is definitely wrong. Start using a JFrame for this app. and it will work better because focus will be more reliable.

Categories