Ask your own question, for FREE!
Computer Science 8 Online
OpenStudy (anonymous):

How do I make a variable usable throughout an entire program including all of the methods?

OpenStudy (anonymous):

For instance, I am coding a jeopardy game and I want to initialize the score in the main method to zero and have made all separate methods for the questions, so if the score starts at 0, after each correct answer, I want to add ex, 200 points so that at the end, the variable stores the cumulative score.

OpenStudy (woodrow73):

What you're looking for is a 'global variable' -- often times, global variables are used when you create multiple classes. In order to make a global variable, you declare it inside of the class, but outside of any method. The one thing you really need to learn for this is what static means.. and how static can't interact with non-static. Though for now, this is probably what you're looking for ``` import javax.swing.JOptionPane; public class HelloWorld { private static int score; public static void main(String[] args) { String play = ""; do{ score = 0; boolean outOfRange = false; boolean notInt = false; int difficulty; do{ if(notInt || outOfRange) JOptionPane.showMessageDialog(null, "Invalid Input. Enter 1-3 inclusive."); notInt = false; outOfRange = false; difficulty = 0; try{ difficulty = Integer.parseInt(JOptionPane.showInputDialog("" + "Topic: static keyword\n1, 2, or 3 point question?")); }catch(NumberFormatException e) { notInt = true; } if(difficulty < 1 || difficulty > 3) outOfRange = true; }while(notInt || outOfRange); askAboutStatic(difficulty); //this isn't necessary - but points out the //askAboutStatic() method is in this class play = JOptionPane.showInputDialog("You got a score of " + String.valueOf(score) + " on the 1 question quiz." + "\nPlay again? enter \'yes\' or \'no\'"); }while(play.equalsIgnoreCase("yes")); System.exit(0); } public static void askAboutStatic(int difficulty) { String ans = ""; switch(difficulty) { case 1: ans = JOptionPane.showInputDialog("Can static variables interact " + "with non-static methods? enter \'y\' or \'n\'."); score = ans.charAt(0) == 'y' ? 0 : 100; //answer == 'n' break; case 2: ans = JOptionPane.showInputDialog("What is an instance of a class? \n" + "1. an object of the class which has attributes and data; aka fields " + "and methods.\n2. A variable that contains information\nenter \'1\' " + "for option 1, \'2\' for option 2 or \'3\' for all of the above."); score = ans.charAt(0) == '3' ? 200 : 0; //answer == '3' break; case 3: ans = JOptionPane.showInputDialog("How is an instance of a class " + "created?\n1. By creating a variable of the class name, and setting" + " it equal to an instance of that class via the new keyword; and pare" + "nthesis to signal the constructor.\n2. By giving it a main method, and" + " writing code."); score = ans.charAt(0) == '1' ? 300 : 0; break; default: JOptionPane.showMessageDialog(null, "This code will never be reached."); break; } } } ```

OpenStudy (maitre_kaio):

I strongly disagree with the previous answer. If you use an object-oriented language like Java, you should stick to object-oriented concepts. Coding with static methods is a very bad practice which is only useful when coding method libraries. To answer your specific problem, here is how you should code it: - create a Game class with a 'score' instance variable. - add required methods to the Game class, to test if the answer is correct and increase score.

OpenStudy (woodrow73):

yup ^ that's the right way to do it. But I'm just saying when I was at that stage in my development I had no idea how to do that; so I first learned methods by making them static, so I could access it from the main method without constructors ect.

OpenStudy (lyrae):

There is no such thing as a 'global' variable in Java. All java variables are either local or fields of a class which also means there's no global variable scope. You can however (ab)use static members in such a way but I strongly discourage you from doing so; java globals was left out of the design for a reason - you just don't do it. The recommended solution is either as described by @maitre_kaio or by using dependency injection ``` class Scores { public int p1 = 0; public int p2 = 0; .... } public class Game { private final Scores sc; public Game(Scores sc) { this.sc = sc; } private void game() { Scores sc = new Scores(); q1(sc); } private static void q1(Scores sc) { sc.p1 += 5; } ... public static void main(String[] args) { Game game = new Game(new Scores); } } ``` (this can of course be extended using other access modifiers and getters/setters). If you learn something you should learn it the correct way from the start!

OpenStudy (woodrow73):

Good point about the scope.. I didn't know other languages had genuine 'global variables'. I don't see anything inherently wrong with using static methods in a small program such as this, but by learning OOP concepts such as constructors, objects, fields, methods, you'll be much more suitably equipped to make more organized, maintainable, complex programs in the future.. *prepares to hear reasons for not using static methods in such a way*

OpenStudy (lyrae):

You can probably argue that for hours lol but there are a bunch of other people whom already done that. Here's a good summary: http://stackoverflow.com/questions/7026507/why-are-static-variables-considered-evil

OpenStudy (woodrow73):

I love the way you phrased it haha. From my java textbook; some classes can contain all static methods for the use of utility functions... naturally you could just make methods to do the same functions, but it can be more organized that way. 95% of the time I don't use static, because I'm program in an OOP style, but I argue that just because the language offers OOP abilities doesn't imply that they should always be used... in a case, where say the program doesn't use any instances of any classes.

OpenStudy (woodrow73):

I see an interesting point that there is no garbage collection on statics; definitely something to keep in mind.

OpenStudy (anonymous):

``` public static void Science() { System.out.println("A chemical bond that occurs when atoms share electrons. " ); String guess = In.getString(); if (guess.equalsIgnoreCase("what is a covalent bond?")) { score = score + 200; System.out.println("Right!"); } else if (guess.equalsIgnoreCase("pass")) { score = score + 0; System.out.println("Pass"); } else { score = score - 200; System.out.println("Wrong!"); } } ```

OpenStudy (anonymous):

Thanks for all the help everyone! So I pasted a method above for a jeopardy game that I'm coding and right now, it works fine except when a user enters What is a covalent bond? for instance, it will be recognized as wrong. I want the case to be ignored and also any extra/different spacing to be ignored, but what I have above is not doing that (the equalsIgnoreCase) so I must have coded it incorrectly, and I'm not sure about how to get it to ignore extra spaces.

OpenStudy (woodrow73):

The program should recognize "What is a covalent bond?" as true with your given if statement: ``` if (guess.equalsIgnoreCase("what is a covalent bond?")) ```

OpenStudy (woodrow73):

one thing you can do, is to scan the user-entered String as to whether it includes 'covalentbond' or 'covalent bond' anywhere in it (ignoring case)..

OpenStudy (woodrow73):

and if it does, count it as a right answer

OpenStudy (anonymous):

yes, you're right, What is a covalent bond works, but what would I need to change to make it so that it ignores cases anywhere in the statement because then if I do what is a Covalent BOnd, it will say "Wrong" and also, do you know of how I could check for extra spaces as well?

OpenStudy (harsha19111999):

The variable which is used through out the program is a global variable. Though the word "global" is not used anywhere. So to initialize a global variable, you should do at the starting of the program. It should not be initialized within any method or class. If it is done so, it becomes a local variable

OpenStudy (harsha19111999):

Make sure that you give the spacing properly as Woodrow told

OpenStudy (harsha19111999):

"what is a Covalent BOnd" this should actually work

OpenStudy (harsha19111999):

I don't know about spacing...Do you know Woodrow?

OpenStudy (woodrow73):

inputting *"WhAt is A coValenT bond?" will (should) return true for ``` if (guess.equalsIgnoreCase("what is a covalent bond?")) ``` And if I don't fully answer your question about spaces, let me know.. firstly, doing ``` guess.trim(); ``` will remove all leading & trailing spaces in the String. You could loop though the entire String and make an algorithm that deletes multiple spaces if connected, but I'll provide a different solution below vv at that point you can divide the string into different strings via the StringTokenizer class ``` import java.util.StringTokenizer; import java.util.ArrayList; public class Token { public static void main(String[] args) { ArrayList<String> guessParts = new ArrayList<String>(); String guess = "what is a covalent bond?"; StringTokenizer st = new StringTokenizer(guess); //default uses " " as the delimiter while(st.hasMoreTokens()) { guessParts.add(st.nextToken()); } boolean rightAnswer = false; for(int i = 0; i < guessParts.size(); i++) { if(guessParts.get(i).equalsIgnoreCase("covalentbonds") || guessParts.get(i).equalsIgnoreCase("covalentbond") || guessParts.get(i).equalsIgnoreCase("covalentbond?") || guessParts.get(i).equalsIgnoreCase("covalentbonds?")) { rightAnswer = true; } else if(guessParts.get(i).equalsIgnoreCase("covalent") && i != guessParts.size()-1) { if(guessParts.get(i+1).equalsIgnoreCase("bond?") || guessParts.get(i+1).equalsIgnoreCase("bonds?") || guessParts.get(i+1).equalsIgnoreCase("bond") || guessParts.get(i+1).equalsIgnoreCase("bonds")) { rightAnswer = true; } } } if(rightAnswer) System.out.println("Congrats you got the right answer"); else System.out.println("You're wrong"); } } ``` and test whether 'covalentbond' 'covalentbonds' (|| covalentbond? covalentbonds?)'covalent' followed by 'bonds' or 'bond' 'bonds?' or 'bond?' ever came up (ignoring case).

OpenStudy (woodrow73):

I believe I taught you the ArrayList class a few weeks ago too?

OpenStudy (woodrow73):

And as Harsha said, with equalsIgnoreCase, it doesn't matter where there are caps, (be it in the first word.. the third) it will ignore them, and treat it like every letter in both Strings are lower-case. Here's a summary of the StringTokenizer class: you put the String into it's constructor, by default " " the space character is the delimeter -a delimiter is what separates different parts of the String.. ``` String numberList = "1,2,3,4,5,6,7"; ``` above I used "," the comma as the delimiter, and if you wanted to use that as the delimiter, you would add the delimiter as the 2nd argument it would look like this: ``` StringTokenizer st = new StringTokenizer(numberList, ","); ``` and if you want the delimiters to be counted as tokens, you specify that in the third argument: ``` StringTokenizer st = new StringTokenizer(numberList, ",", true); ``` and to read off the tokens, it's best to put it in a while loop that iterates (loops) until there is nothing left to read off.. the StringTokenizer's hasMoreTokens() is a great method to do just that - it returns true when there is more to read, and false if there's nothing left to read, and to actually read in a token, you use it's nextToken() method.

OpenStudy (woodrow73):

I guess he's offline for now

OpenStudy (harsha19111999):

LOL :D

OpenStudy (woodrow73):

haha

OpenStudy (anonymous):

Lol I'm back

OpenStudy (anonymous):

Ok yeah oops so the equalsIgnoreCase does work, I was just forgetting the question mark which is why it showed up as wrong and thanks @woodrow73 I will try out the String delimiter and get back to you

OpenStudy (woodrow73):

Allright man, good luck! There's also an alternative to StringTokenizer class - It's the String class's split method.

OpenStudy (anonymous):

Great news, I've got everything working to ignore spaces, now I am just trying to figure out how I could use a 2-d array to store the game # and score for each game (if I were to loop the game so that until a user terminates it, it keeps playing

OpenStudy (woodrow73):

Well, in an array you'd be able to tell what game number a score is based off it's index.. ie; the first element (element aka index aka which column the number is in the array) - thus eliminating the need for it to be 2-d. Also, if you don't know how many elements you'll be adding to an array ahead of time, it's usually easier to use an arraylist - since for each element you add you can use it's add() method

OpenStudy (anonymous):

my game loops over and over until the user elects to quit, so how would I get that stored in an array list?

OpenStudy (woodrow73):

1) make the ArrayList object, 2) at the end of each game, add the int to the arraylist object 3) after the user chooses not to play anymore, loop through the arraylist using it's size() method to spit out the data. http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

OpenStudy (woodrow73):

If you're using an int in an arraylist - keep in mind that you put an object inside the <>, though int isn't an object itself.. but you can use the Integer object which will act the same as an int.. so ``` ArrayLIst<Integer> al = new ArrayList<Integer>(); ```

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!