Resetting an object to zero? - java

Hi guys I know this is a weird question but can an object return to being zero? I'm asking because I have a huge design flaw with a basic GUI that i'm running where if I answer what I wanted on a menu it would continue to use the same old answer.
To get around that I would ask again on the lower part but then I ran into a worse problem..it kept on asking. I feel trapped tbh and I can't find anyway inside my programming book to reset or get around this.
Object[] menuPossibilities = {"Create a New Account", "Deposit", "Withdraw", "Display Balance", "Exit"};
Object menuValues = JOptionPane.showInputDialog(null, "Please pick an option from this menu: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
while (!menuValues.equals("Exit")){
Bank newBank = new Bank();
// Bank newBank1 = new Bank();
// Bank newBank2 = new Bank(); Do the same thing as below but switch out
// bank1 and bank2 as a substitute.
ArrayList<BankAccount> bankList = newBank.getBankAccounts();
if (menuValues.equals("Create a New Account")){
newBank.openAccount();
}
else if (menuValues.equals("Deposit")){
newBank.deposit();
}
else if (menuValues.equals("Withdraw")){
newBank.withdraw();
}
else if (menuValues.equals("Display Balace")){
newBank.deposit();
}
else if (menuValues.equals("Exit")){
System.out.println("Thank you for using our service.");
}
Object menuValuesTWO = JOptionPane.showInputDialog(null, "Since you did not pick 5 please pick another option: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
}
The above is the code I have in case I wasn't very clear. But basically If I take out the menuvalueTWO and hit the create bank account then it'll loop back around and say "So wanna make another bank account?".

Object menuValuesTWO = JOptionPane.showInputDialog(null, "Since you did not pick 5 please pick another option: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
should be
menuValues = JOptionPane.showInputDialog(null, "Since you did not pick 5 please pick another option: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
I can't validate the change as I cannot run your code. But as #Stephen C suggested you must use the same object that you are looping on.

... can an object return to being zero?
Not unless some method explicitly sets it to zero.
In cases like this the problem is typically something else; for example, that you are actually looking at different objects.
In your example, it looks like you have made some mistakes in the way that you have modeled and/or implemented operations like openAccount, deposit and withdraw. I would expect:
openAccount() should return the BankAcount it created, and also add it to the Bank's bank account list.
deposit() should be an operation on a BankAccount and should take a parameter saying how much to deposit.
withdraw() should be an operation on a BankAccount and should take a parameter saying how much to withdraw.
And so on.
(Alternatively, if deposit and withdraw are operations on the Bank object, then they need another parameter - an account number? - to say which account to operate on.)

Related

When ever a question mark is imputed by a user it will display a string

Okay so basically iv been working on my school assignment which happens to be creating a very simple ChatterBot with java using Eclipse. So far iv gotten it to ask a series of questions if the user input contained a certain word, but i also need make it so when ever a "?" is entered (no matter at what point, it will probs make sense when you look at the code) it will display the string " i will be asking the questions", so far iv only got it to work only for the first time a user makes an input, then it goes to the next question and if you type a "?" nothing happens and the program ends.
okay so i see someone asked what the assignment is about to get a better idea on how to go about it, im really bad a explaining things but ill give it a try. For my assignment i need to create a 'Chatter Bot' and iv decided to go with a bot that asks you a few questions then gives you a fun fact (because i need to add at least 10 variables) so far iv got it to ask a question and take in the user input and if the sentence they just typed contains a key word it will take that key word and run the next set of question while taking in user input and looking for the next key word for example it will first ask you to pick a subject like for example science, then it will ask you to pick a section of that subject like Biology, then it will state a fact and ask if you already knew that and you type yes or no, and according to that it will print out a string (key words they can chose from are typed in brackets)
Im sure there was a better way to explain all that but im really bad at them :/ sorry.
import javax.swing.JOptionPane;
public class ChatterBot {
public static void main(String args[]) {
String input = "";
String maths = "";
String science = "";
String chemFact = "";
String bioFact = "";
String zooFact = "";
String algFact = "";
String yes = "";
String no = "";
input = JOptionPane
.showInputDialog("Pick one of the subjects listed to learn a fun fact (english, science, maths) ");
if (input.contains("science")) {
science = JOptionPane.showInputDialog(
"What kind of science fact woukd you like to know about? (chem, Biology, Zoology)");
}
else if (input.contains("maths")) {
maths = JOptionPane.showInputDialog(
"What kind of maths fact would you like to know about? (algebra, fractions, division) ");
}
if (maths.contains("algebra")) {
algFact = JOptionPane.showInputDialog(
"\"Did you know a mathematician who specializes in algebra is called an algebraist? (yes or no)\"");
}
if (algFact.contains("yes")) {
System.out.println("Well good for you");
} else if (algFact.contains("no")) {
System.out.println("You learn something new everyday :)");
}
if (science.contains("chem")) {
chemFact = JOptionPane.showInputDialog(
"Did you know If you pour a handful of salt into a full glass of water the water level will actually go down rather than overflowing the glass? (yes or no)");
}
if (chemFact.contains("yes")) {
System.out.println("Well good for you");
} else if (chemFact.contains("no")) {
System.out.println("You learn something new everyday :)");
}
else if (science.contains("biology")) {
bioFact = JOptionPane.showInputDialog("Did you know The brain itself cannot feel pain? (yes or no)");
}
if (bioFact.contains("yes")) {
System.out.println("Well good for you");
} else if (bioFact.contains("no")) {
System.out.println("You learn something new everyday :)");
}
else if (science.contains("zoology")) {
zooFact = JOptionPane
.showInputDialog("Did you know butterflies have taste receptors on their feet? (yes or no)");
}
if (zooFact.contains("yes")) {
System.out.println("Well good for you");
} else if (zooFact.contains("no")) {
System.out.println("You learn something new everyday :)");
}
if (input.contains("?")) {
System.out.println("I will be asking the questions");
}
}
}
Try something like below in your code
input = JOptionPane
.showInputDialog("Pick one of the subjects listed to learn a fun fact (english, science, maths) ");
if (input.contains("science")) {
science = JOptionPane.showInputDialog(
"What kind of science fact woukd you like to know about? (chem, Biology, Zoology)");
inputContainsQuestionMark(science);
}
else if (input.contains("maths")) {
maths = JOptionPane.showInputDialog(
"What kind of maths fact would you like to know about? (algebra, fractions, division) ");
inputContainsQuestionMark(maths);
}
if (maths.contains("algebra")) {
algFact = JOptionPane.showInputDialog(
"\"Did you know a mathematician who specializes in algebra is called an algebraist? (yes or no)\"");
inputContainsQuestionMark(algFact);
}
if (algFact.contains("yes")) {
System.out.println("Well good for you");
inputContainsQuestionMark(algFact);
} else if (algFact.contains("no")) {
System.out.println("You learn something new everyday :)");
inputContainsQuestionMark(algFact);
}
if (science.contains("chem")) {
chemFact = JOptionPane.showInputDialog(
"Did you know If you pour a handful of salt into a full glass of water the water level will actually go down rather than overflowing the glass? (yes or no)");
inputContainsQuestionMark(chemFact);
}
if (chemFact.contains("yes")) {
System.out.println("Well good for you");
inputContainsQuestionMark(chemFact);
} else if (chemFact.contains("no")) {
System.out.println("You learn something new everyday :)");
inputContainsQuestionMark(chemFact);
}
else if (science.contains("biology")) {
bioFact = JOptionPane.showInputDialog("Did you know The brain itself cannot feel pain? (yes or no)");
inputContainsQuestionMark(bioFact);
}
if (bioFact.contains("yes")) {
System.out.println("Well good for you");
inputContainsQuestionMark(bioFact);
} else if (bioFact.contains("no")) {
System.out.println("You learn something new everyday :)");
inputContainsQuestionMark(bioFact);
}
else if (science.contains("zoology")) {
zooFact = JOptionPane
.showInputDialog("Did you know butterflies have taste receptors on their feet? (yes or no)");
inputContainsQuestionMark(zooFact);
}
if (zooFact.contains("yes")) {
System.out.println("Well good for you");
inputContainsQuestionMark(zooFact);
} else if (zooFact.contains("no")) {
System.out.println("You learn something new everyday :)");
inputContainsQuestionMark(zooFact);
}
inputContainsQuestionMark(input);
}
private static void inputContainsQuestionMark(String science) {
if (science.contains("?")) {
System.out.println("I will be asking the questions");
}
}

User input from scanner method to array of 5 indexes also gives user ability to delete any index

User input from scanner method to array of 5 indexes also gives user ability to delete any index matching with string from one of the index.
ALL I want to achieve in this is in this while loop I would like to settle city (option 1), which means creating one as you can probably see from my code. This is where user will type any name they like no restrictions. once they settle the city loops starts again. However it does remember that user created a city earlier. I can have upto 5 cities. There is cost associate with settling new city. I know how to do those conditionals. I am just not sure about this string array.
ArrayList or Array class is not allowed.
where as, option 2 I can demolish any of the city i have created by giving user lists of city they have made earlier. I have to keep minimum of at least one city.
IF you are wondering then this is based on Civilization game.
Please ask for clarification as this may not be
straight forward. thanks
while (playing) {
System.out.println("\nPlease make your selection!");
System.out.println("\n1. Settle a City"
+ "\n2. Demolish a City"
+ "\n3. Build Militia"
+ "\n4. Research Technology"
+ "\n5. Attack Enemy City"
+ "\n6. End Turn\n");
String gameChoice = userinput.nextLine();
if (gameChoice.equals("1")) {
System.out.println("\nWhat would you like to"
+ " name your city?");
String cityname = userinput.nextLine();
cityname = cityNames[0];
} else if (gameChoice.equals("2")) {
System.out.println("What city would you like to demolish?");
for (int i = 0; i < 5 ; i++) {
System.out.print(cityNames[i]);
System.out.print("");
}
} else if (gameChoice.equals("3")) {
System.out.println("You have military points");
} else if (gameChoice.equals("4")) {
System.out.println("You have Research Technology points");
} else if (gameChoice.equals("5")) {
System.out.println("You have zero points");
} else {
System.out.println(" Thanks for playing ");
}
playing = false;
}
First, here:
String cityname = userinput.nextLine();
cityname = cityNames[0];
You are assigning cityname to user input and then you are assigning it to something in cityNames array, that doesn't make sense, maybe you pasted wrong or something, but just in case, this should be the other way around, like this:
cityNames[0] = cityname;
You have playing = false at the end so the loop is gonna just end when user types the city name, you need to either remove this playing = false or use continue; after cityNames[0] = cityName;, that's gonna go to the next iteration of a loop, without going all the way down to playing = false.

Not returning what's intended

I am having trouble printing out the first and last name scanned in (fname1, lname1). I have to create 6 objects and these are two that I can't seem to even start with. Also, if I enter anything except "yes" or "y", it will not loop back to the radiobuttons I inserted above the snippet. How do I fix this?
This is what prints out in the output window:
[,0,0,0x0,invalid,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=java.awt.Dimension[width=350,height=200]]
public class Cabin_Selector
{
public static void main(String[] args)
{
JFrame cabin_selection = new JFrame("Select Your Cabin"); //Prompts the user
cabin_selection.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Close the Frame when exiting
Project2_JoshuaLucas selection = new Project2_JoshuaLucas("", "", "", "", "", "", "", 0.00); //Call the constructor for the Project2_JoshuaLucas class
cabin_selection.getContentPane().add(selection); //put the object in the current pane of the jframe
cabin_selection.pack(); //size the frame
cabin_selection.setVisible(true); //make the frame visible
} //end main method
} //end class
if (source == cabin1)
{
cabin1.setBackground(Color.darkGray);
cabin2.setBackground(Color.gray);
cabin3.setBackground(Color.gray);
cabin4.setBackground(Color.gray);
cabin5.setBackground(Color.gray);
cabin6.setBackground(Color.gray);
cabin7.setBackground(Color.gray);
cabin8.setBackground(Color.gray);
cabin9.setBackground(Color.gray);
cabin10.setBackground(Color.gray);
suite1.setBackground(Color.red);
suite2.setBackground(Color.red);
System.out.println("Your choice is Cabin 11-1, would you like to designate this as your room?");
info1 = scan_in.nextLine();
info1 = info1.toLowerCase();
if ( info1.equals ("yes") || info1.equals ("y"))
{
continues=true;
System.out.println("Please enter the number of people in your cabin (*Maximum number of people is 2*)");
cabin_people = scan_in.nextInt();
scan_in.nextLine();
while(continues)
{
switch (cabin_people)
{
case 1:
System.out.println("There is one passenger within the cabin. (You will pay an EXTRA 45% because of the empty passenger slot)");
continues=false;
onepassenger=true;
break;
case 2:
System.out.println("There are two passenger within this cabin.");
continues=false;
twopassenger=true;
break;
default:
System.out.println("Please try again. Remember, the maximum amount of passengers allowed is 2.");
System.out.println("How many passengers are staying within this cabin?");
cabin_people=scan_in.nextInt();
scan_in.nextLine();
continues=true;
}//Closes the Switch
}//Closes the while(continues) loop
while(onepassenger)
{
System.out.println("Please state your FIRST name: ");
fname1=scan_in.nextLine();
System.out.println();
System.out.println("Please state your LAST name: ");
lname1=scan_in.nextLine();
onepassenger=false;
Project2_JoshuaLucas passenger1 = new Project2_JoshuaLucas (fname1, lname1, "", "", "", "", "", 0.00);
System.out.println(passenger1);
} //Closes while(1passenger)
while(twopassenger)
{
System.out.println("Please state your FIRST name: ");
fname1=scan_in.nextLine();
System.out.println("Please state your LAST name: ");
lname1=scan_in.nextLine();
System.out.println("Please enter the second passenger's FIRST name: ");
fname2=scan_in.nextLine();
System.out.println("Please enter the second passenger's LAST name: ");
lname2=scan_in.nextLine();
System.out.println("Please enter the city you live in: ");
cob=scan_in.nextLine();
twopassenger=false;
} //Closes while(2passenger)
} //Closes yes | y
else
System.out.println("Please select another cabin");
continues=false;
} //Closes source==cabin1
Your displaying the toString() method returned by one of your Swing components -- likely a JPanel since it uses FlowLayout, and the solution is:
Don't pass a Swing component into a System.out.println(...) call,
Instead print out the state of your key non-GUI objects, called "model" objects because they model the behavior and state of your program.
Make sure that these classes have a decent public String toString() method override, so what they print out makes sense.
You ask:
What is a model object?
If you are creating an airplane GUI for instance, you'll likely need to create several classes, some of the GUI component classes, others non. The model classes could include:
Passenger
Airplane
AirplaneSeat
....
These model classes will contain information about themselves, such as a Passenger will have a name, perhaps an age, a passengerNumber id number... The Airplane will have a collection of first class AirplaneSeats and likewise for coach. AirplaneSeat will have a boolean occupied field, and perhaps a Passenger field to tell who occupies what seat. But none of these classes will contain GUI component code, none will extend JPanel or JFrame or such.
Then you'll likely have view classes that do either extend GUI components or contain them, and they will display the state of the model classes above. You tried to print out the toString() of a view class, one that does not override the toString() method.
A side recommendation: you appear to be trying to mix a Swing GUI program with a console program, and you're not going to want to do this. Instead you should have all user interaction and output in the GUI, not in console, except perhaps for simple debugging purposes, but nothing more.

Transfering a non-static variable to static in JAVA?

Only my third week of class (new to programming).
I'm making a text-based story in Java, but I've come to a stump in the process. I have a static variable called "static String dogName;" that I'm trying to change the value of (only once). In the beginning of the game, the user has the option to name their dog. When I try to name the dog, the code skips the naming prompt because of the static String dogName.
I want to give the user the option to name their dog.
If there's a better way to do things in my code, please let me know.
Part of the code may not be complete like the decisions...
public static Scanner keyboard = new Scanner(System.in);
public static int choice;
// dogName is Dogs name forever a hundred times rick & morty
static String dogName;
public static void main(String[] args) {
int karma = 0;
// Dog stuff...
Dog Dandy;
Dandy = new Dog();
// Prologue
System.out.println("You're walking through an alley late at night "
+ ", you see a stray dog. What do you do? ");
System.out.println("[1] Approach");
System.out.println("[2] Attempt to touch");
System.out.println("[3] Give treat");
boolean running = true;
GAME:
while (running) {
choice = keyboard.nextInt();
switch (choice) {
case 1:
System.out.println("The dog became alarmed!");
Dandy.bark();
break;
case 2:
System.out.println("The dog becomes aggressive!");
Dandy.bite();
break;
case 3:
System.out.println("The dog comes in peace");
Dandy.sit();
break;
}
if (choice == 1) {
System.out.println("You stand back in caution. You cannot risk being bitten.");
}
if (choice == 2) {
System.out.print("");
karma--;
}
if (choice == 3) {
System.out.println("You give the dog a treat. It wags its tail in excitement");
karma++;
}
// Chapter 1.1 - Man's best friend
System.out.println("\nThe dog will live a harsh life in the outside world. What would you like to do? "
+ "\n[1] Adopt dog\n[2] Leave dog\n[3] Quit game! You're bored...");
choice = keyboard.nextInt();
switch (choice) {
case 1:
System.out.println("\nYou welcome your new companion");
System.out.println("\nWould you like to give him a name?\n[1] No\n[2] Yes");
choice = keyboard.nextInt();
switch (choice){
case 1:
System.out.println("You see a shiny object beneath his foot, it's a dog collar."
+ "\nYou pick up the dog collar and see the name Todd on it."
+ "\nYes, because you did not choose a name for your dog, we gave him the most basic name ever. "
+ "You're welcome.");
dogName = "Todd"; //RIP doge
karma--;
break;
case 2:
dogName = keyboard.nextLine();
karma++;
}
}
// Good guy player gives his dog a name
// Chapter 1.2 - Home sweet home
System.out.println("\n" + dogName + " crawls up to your leg and lets out a whimper.\n"
+ "Is " + dogName + " just afraid of the dark, or is he hungry?"
+ "\nYou don't know the last time he ate. What will you do?");
System.out.println("\n[1] Go home\n[2] Find a store\n[3] Search the area");
choice = keyboard.nextInt();
if (choice == 1){
System.out.println("\nYou head home with " + dogName + " as fast as you can.\n"
+"On the way back, " + dogName + " seems extremely happy to be with"
+ " his new owner.\nGoing out you had no idea you'd bring home a new friend.");
karma++;
}
if (choice == 2){
System.out.println("");
System.out.println("");
}
if (choice == 3){
}
}
// GAME ENDING
if (karma > 0) {
System.out.println("\nYou ended with " + karma + " karma. Good job!");
}
else if (karma == 0){
System.out.println("\nYou ended with " + karma + " karma. Neither good nor bad, a neutral state.");
}else{
System.out.println("\nYou ended with " + karma + " karma. Bad job!");
}
// CREDITS
System.out.println("\n\t# THANK YOU FOR PLAYING #");
System.out.println("\t# Game created by aliens from outer space #");
}
}
When I try to name the dog, the code skips the naming prompt because of the static String dogName.
No, the problem is unrelated to dogName being static. Instead, the problem is with the way you use the Scanner. When you do keyboard.nextInt() it reads just enough data to be able to return an int. So, if the user types 2 and Enter, the Scanner will read the 2 and return it as an int, leaving the newline character in the input buffer.
Then, when you go to read the dog's name with dogName = keyboard.nextLine(); the newline character that's already present causes it to return an empty string for the dog's name immediately, rather than wait for any user input.
You can fix this by doing another keyboard.nextLine() just before you ask for the dog's name:
case 2:
keyboard.nextLine();
dogName = keyboard.nextLine();
karma++;
The first nextLine() eats up the newline from the previous number that was typed, and the second nextLine() returns a line of text (sans newline) that can be assigned to dogName.
However, there are other problems you will run into with Scanner. If the player types anything other than a number, nextInt() will throw an InputMismatchException. It's possible to work around these problems, but they can end up giving you a headache.
You might be better off using keyboard.nextLine() every time to get a line from the player, and then checking to see if it contains a number and parsing that number.
Also, the convention in Java is to use lower case letters to begin variable names, so your variable Dandy should be named dandy. Others have given some sensible suggestions about splitting your program up into pieces rather than having one monolithic main method.
couple of things.
Separate your logic from your Main method class.
Create a POJO for Dog (I think you already have one) class that takes name in the constructor argument.
public class Dog {
private String dogName;
public Dog(String dogName)
this.dogName = dogName;
}
//getters setters..
}
Instead of putting everything in your main, you'll have to remove the static keyword, and make a new instance of the program, something like this:
public static void main(String[] args) {
Game game = new Game();
game.start();
}
Then the choice and dogName variable doesn't have to be static anymore.
For general remarks: start by splitting up your code into multiple methods, each grouped by functionality, for example, one method for handling the user input, one for printing the options, etc. That way your code will become less of a mess, and allows you to refactor later into different classes more easily.
#DavidConrad's answer covers your actual error, but I thought I'd add more on "what you could do better"
public static Scanner keyboard = new Scanner(System.in);
public static int choice;
// dogName is Dogs name forever a hundred times rick & morty
static String dogName;
Note how all these fields are static? This is only required because you are trying to use them from a static method (that method being main). With only the code you have posted, it would seem you could move those fields into the main method like where you create the Dog.
Also, a tiny pet-peeve of mine, but it's not actually a rule or anything, is "excessive" spacing - (like inbetween choice and dogName). One space is fine. Two is "too" many for my liking. ;)
public static void main(String[] args) {
int karma = 0;
// Dog stuff...
Dog Dandy;
Dandy = new Dog();
Grr, more spaces! But, more importantly is the line about Dog Dandy. Your variable name is capitalized, and it is best practice to name variables in lower-case (such as you did correctly for karma). You should also declare and initialize your Dog in the same line, like so: Dog dandy = new Dog();
With the prologue and chapters, you may consider separating these into a separate class. You may notice a pattern in each chapter.
some text is given
options are given
result of option is displayed
You could greatly improve the overall readability of your code by creating a class which could taken some introText, options, and then show an option depending on the choice made. If that seems over your head, then I wouldn't worry about it though - it's only your third week so I wouldn't expect you to have the differences between classes, methods, and fields down pat quite yet. If this is something you are seriously interested in, you could find all kind of tutorials covering those, it will be greatly beneficial when you truly understand what they can do and how they interact.

Catching value of JOptionPane input dialog with preset choices?

I am using a JOptionPane with input dialog. I am having trouble catching the value of the choice so that I can use it later in my program.
String[] options = {"Selection Sort", "Insertion Sort"};
Object searchType = JOptionPane.showInputDialog(null, null, "Choose a sort type ",
JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
…and this is what it looks like.
edit: I am having trouble catching the option that is chosen by the user.
I have tried:
int selection = JOptionPane.QUESTION_MESSAGE;
and that will compile, however I can't actually use the value.
basically when a person selects one of the two options I want to know which one it is.
edit2: For future reference this works:
Object selection = searchType;
if(selection.equals(options[0]))
{
//something
}
else if(selection.equals(options[1]))
{
//something else
}
I think you should read the JavaDocs a little close...
Returns:
user's input, or null meaning the user canceled the input
This means, if the use selected Okay, that it will return the item the user selected as listed by the options parameter. In your case this will be Selection Sort or Insertion Sort or null if they canceled the dialog
Updated with example
Using this and selecting [Okay] outputs Selection Sort
String[] options = {"Selection Sort", "Insertion Sort"};
Object searchType = JOptionPane.showInputDialog(null, null, "Choose a sort type ",
JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
System.out.println(searchType);
Take a closer look at How to Make Dialogs for more details
You should check the object returned and compare it to the items held in your array.
Either that, or call toString() on it and use the String value returned to decide.

Categories

Resources