简体   繁体   中英

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.

  1. I want to give the user the option to name their dog.
  2. 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.

  1. Separate your logic from your Main method class.
  2. 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.

  1. some text is given
  2. options are given
  3. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM