Avoid resetting integer variable - java

I'm making a game in Java where you have to take care of a dog. I made my game method call itself so that I won't have to copy and paste the contents in this method several times. The problem is that I don't know how to go around the two integer values I declared, because the integer values are added and subtracted through each choice and calling the method again will change those changed values back to default.
import java.io.File;
import java.util.Scanner;
public class Main {
public static Scanner kybd = new Scanner(System.in);
public static void main(String[] args) {
game();
}
public static void game() {
Integer diet;
diet = 5;
Integer happiness;
happiness = 10;
System.out.println("");
System.out.println("Dog \t Hunger: " + diet
+ "\n \t Happiness: " + happiness);
System.out.println("");
System.out.println("1. Feed \n2. Play \n3. Ignore");
System.out.println("");
System.out.print("> ");
String input = kybd.nextLine();
if (input.equalsIgnoreCase("1")) {
diet++;
game(); // This is supposed to go to the
// beginning with the changed value of diet.
} else if (input.equalsIgnoreCase("2")) {
happiness++;
game(); // This is supposed to go to the
// beginning with the changed value of happiness.
} else if (input.equalsIgnoreCase("3")) {
happiness--;
diet--;
game(); // This is supposed to go to the
// beginning with the changed value of happiness.
} else {
System.out.println("Invalid Input");
game(); // This is supposed to go the beginning
// where you can change your input but
// still has your changed values.
}
if (diet <= 0);
{
System.out.println("Your dog died because it did not eat.");
game(); // This is supposed to go to the beginning
// with the default values.
}
if (diet > 10);
{
System.out.println("Your dog died because it was overfed.");
game(); // This is supposed to go to the
// beginning with the default values.
}
if (happiness <= 0);
{
diet--;
System.out.println("Your dog is no longer happy. He will not eat.");
}
{
if (happiness > 10);
System.out.println("Your dog died because it was too excited.");
game(); // This is supposed to go to the
// beginning with the default values.
}
}
}

If I understand your problem in a right way, the only thing you have to do is declare these two variables as class variables (static or not). So the final code is:
import java.io.File;
import java.util.Scanner;
public class Main {
public static Scanner kybd = new Scanner(System.in);
public static int diet = 5;
public static int happiness = 10;
public static void main(String[] args) {
game();
}
Regards
EDIT FOR DOG DIE
public static die() {
diet=5;
happiness=10;
}
Call this function everytime you that your dog die before call game().

Related

Variable being changed for seemingly no reason in Java

So i just started learning Java yesterday so apologies if this is a bit of a mess.
Basically i am testing the function menuValid() by printing the input from the function questionTime(), my problem is regardless of what my input for the menu is menuValid() will always print '0' as my answer. However the X variable is declared and printed at the same points however x will remain the same and will not be set to '0'.
Here is my code:
import java.util.Scanner;
public class Test {
public static int menu_input;
public static int x;
static void menuError() {
System.out.println("Please pick a valid option.");
questionTime();
}
public static void questionTime() {
Scanner scan = new Scanner(System.in);
try {
int menu_input = scan.nextInt();
x = 25;
if(menu_input>4 && menu_input < 9){
menuError();
}
if(menu_input>9 || menu_input<1){
menuError();
}
else{
System.out.println(menu_input);
menuValid();
}
scan.close();
} catch(Exception e) {
menuError();
}
}
public static void menuValid() {
System.out.println(menu_input);
System.out.println(x);
}
public static void main(String[] args) {
System.out.println("P4CS Mini Applications");
System.out.println("----------------------");
System.out.println("Please Select an option:");
System.out.println("1) Keep Counting Game");
System.out.println("2) Number Conversion Tool");
System.out.println("3) Universal Product Code (UPC) Calculator");
System.out.println("4) Universal Product Code (UPC) Checker");
System.out.println("9) Quit");
System.out.println("Please enter option");
questionTime();
}
}
Here is an example of the output of the code so you can see my issue:
1) Keep Counting Game
2) Number Conversion Tool
3) Universal Product Code (UPC) Calculator
4) Universal Product Code (UPC) Checker
9) Quit
Please enter option
1
1
0
25
You re-declared menu_input inside questionTime (when you did int menu_input = scan.nextInt();), which is different from how you treated x, where you just changed its value (x = 25;). So the menu_item you're setting via the Scanner is not the menu_input class variable you're printing inside menuValid.
You will have to pass menu_input to menuValid() like so -
else{
System.out.println(menu_input);
menuValid(menu_input); // see this line
}
And change menu valid function as below -
public static void menuValid(int menu_input) {
System.out.println(menu_input);
System.out.println(x);
}

Creating Methods that will produce the same result

I'm in a Beginner Java class and I'm confused about using additional methods and using them in another. I think that I have most of my assignment done but I just need help to create the methods. One is to generate the question and the other one is to display the message.
I know that in order to call a method
public static test(num1,num2,num3)
but in my code, how do I make it so that I call the method and still make it loop correctly?
In the assignment instructions that was given to me, In order to do that, I have to write a method named
public static in generateQuestion()
and
public static void displayMessage(boolean isCorrect)
This is my code:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
//Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
//Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
//Question prompt
System.out.println("How much is " +number1+ " times " +number2+ "? ");
answer = input.nextInt();
//If Else While Statements
if(answer == (number1*number2))
{
System.out.println("Good job! You got it right!");
}
else
{
while (answer !=(number1*number2))
{
System.out.println("You got it wrong, try again!");
answer = input.nextInt();
}
}
}
}
You are going to have two methods
public static void generateQuestion()
Which is going to hold the code to generate the random values and output it. It will return void because all it's doing is printing out.
Next you will have
public static void displayMessage(boolean isCorrect)
which will be called if if(answer == (number1*number2)) is true with true as the parameter. Otherwise it will still be called, but the parameter passed in will be false. This method will determine if isCorrect is true or false, and output the appropriate message.
If I got it right, I have a solution that might be a little stupid but will work for your assignment.
If you make generateQuestion that makes two random ints, prints the question and returns their multiple (answer).
And displayMessgae that prints "Good job! You got it right!" if isCorrect is true and "You got it wrong, try again!" else,
you can call generateQuestion, then get an answer (in main), and loop until answer is correct (according to return value of generateQuestion).
Every time you get a new answer (in loop), call displayMessgae(false).
After the loop ended call displayMessgae(true)
This is my working code for this:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static int generateQuestion()
{
Random r = new Random();
int x = r.nextInt(9), y = x = r.nextInt(9);
System.out.println("How much is " + x + " times " + y + "? ");
return x * y;
}
public static void displayMessage(boolean isCorrect)
{
if (isCorrect)
System.out.println("Good job! You got it right!");
else
System.out.println("You got it wrong, try again!");
}
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
int rightAnswer = 0;
rightAnswer = generateQuestion();
while (input.nextInt() != rightAnswer)
displayMessage(false);
displayMessage(true);
}
}
If I understand your question correctly, It's simply a matter of separating the functionality that prints a question and displays the answer into separate methods. See my edited version of your code below
public class Assign6
{
public static void main(String[] args)
{
// Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
// Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
// Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
displayQuestion("How much is " + number1 + " times " + number2 + "?");
answer = input.nextInt();
// If Else While Statements
if (answer == (number1 * number2))
{
displayMessage(Boolean.TRUE);
}
else
{
while (answer != (number1 * number2))
{
displayMessage(Boolean.FALSE);
answer = input.nextInt();
}
}
}
public static void displayQuestion(String q)
{
System.out.println(q);
}
public static void displayMessage(Boolean isCorrect)
{
if (isCorrect)
{
System.out.println("Good job! You got it right!");
}
else
{
System.out.println("You got it wrong, try again!");
}
}
}

Issue with recognizing methods

I'm a new coder and I'm having some trouble with my methods. I made a few but they aren't being detected in the main method. (P.S I havent filled most of the methods yet because I want to remedy the problem first.)
Thanks everyone.
package area;
import java.util.*;
/**
*
* #author domendes
*/
public class Area {
public static void main(String[] args) {
Scanner kbdln = new Scanner(System.in);
System.out.println("Welcome to the area calculating code! Which shape would you like to calculate the area of?");
System.out.println("Press 1 for a Triangle, 2 for a Circle, 3 for a Rectangle, and 0 to quit.");
int request = kbdln.nextInt();
if (request == 1) {
areaTriangle();
} else {
if (request == 2) {
areaCircle();
} else {
if (request == 3) {
areaRectangle();
} else {
if (request < 1) {
System.out.println("Goodbye");
return;
}
}
}
}
}
}
public static void areaTriangle() {
Scanner kbdln = new Scanner(System.in);
System.out.println("Welcome to the Tirangle area cacluator. Enter in the height of your triangle");
double triBase = kbdln.nextDouble();
}
public static void areaCircle() {
}
public static void areaRectangle() {}
}
In Java, everything is an object. So the methods that you are creating are actually methods which belongs to your Area class. If you want to access them you have to use Area class to refer to them.
Given that you have created static method (which means that your methods are at class level and not at object level. you should read more about it). You can access them using classname.methodname. In your case it would be Area.areaTriangle().
Your if/else statements are poorly structured. The first statement should be if, each statement following it should be elseif and the very last one should be else. However in this case a switch statement would be best
switch(request){
case 1:
areaTriangle();
break;
case 2:
areaCircle();
break;
case 3:
areaRectangle();
break;
default:
System.out.println("Goodbye");
}
they aren't being detected in the main method
The main method is a static context, which means if you are trying to call those methods from outside the Area class, you would have to do Area.areaTriangle(), for example.
Alternatively, you could define an AreaPrompter class, that would be like so.
Then, if you want to use those methods in any other class, you can do
AreaPrompter prompter = new AreaPrompter();
prompter.whateverMethodNameHere();
public class AreaPrompter {
public static void main(String[] args) {
AreaPrompter prompter = new AreaPrompter();
// main method
prompter.run();
// just the triangle method
prompter.areaTriangle();
}
public void run() {
Scanner kbdln = new Scanner(System.in);
System.out.println("Welcome to the area calculating code! Which shape would you like to calculate the area of?");
System.out.println("Press 1 for a Triangle, 2 for a Circle, 3 for a Rectangle, and 0 to quit.");
int request = kbdln.nextInt();
if (request <= 0) {
System.out.println("Goodbye");
return;
} else if (request == 1) {
areaTriangle();
} else if (request == 2) {
areaCircle();
} else if (request == 3) {
areaRectangle();
}
}
public void areaTriangle() {
Scanner kbdln = new Scanner(System.in);
System.out.println("Welcome to the Tirangle area cacluator. Enter in the height of your triangle");
double triBase = kbdln.nextDouble();
}
public void areaCircle() { }
public void areaRectangle() { }
}
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
System.out.println("Press 1 for a Triangle, 2 for a Circle, 3 for a Rectangle, and 0 to quit."
int num = sc.nextInt();
if(num == 1){
areaTriangle();
}else if(num == 2){
areaCirlce();
}else if(num == 3){
areaRectangle();
else{
System.out.println("GoodBye");
}
There is nothing wrong with the way you calling your methods since the main method is static you can call the static methods directly without the use of any objects of class etc.

how to get data from other methods?

does anyone know how to get the counters value transfered after it is increased? so if you awnser it right it changes to one in the next method?
package swag;
import java.util.Scanner;
public class Main {
public static void enter(){
System.out.print("welcome to the impossibe game! Press enter to start.");
Scanner input = new Scanner(System.in);
String enter = input.nextLine();
if (enter.equals("")){
System.out.println(" Level one");
}else{
System.out.println("Please press enter");
}
}
public static void firstlevel(){
System.out.println("What is the tenth digit of PI?");
Scanner input = new Scanner(System.in);
int awnser = input.nextInt();
int awnser1 = 5;
int counter = 0;
if (awnser == awnser1 ){
System.out.println("Correct!");
counter++;
System.out.println(" Score: " +counter + "/1");
}else{
System.out.println("Wrong!");
System.out.println(" Score:"+ counter+"/1");
}
}
public static void secondlevel(){
System.out.println("a king and queen get on a boat. then the boat sinks. how many people are alive");
Scanner input = new Scanner(System.in);
String awnser = input.nextLine();
if (awnser.equals("two ")){
System.out.println(" Correct!");
}
}
public static void main(String args[]){
enter();
firstlevel();
}
}
Ah, the way you have defined counter, it can only be seen in firstLevel.
Best thing to do is make it a 'class variable'. To do that:
Delete int counter = 0; from the firstLevel method.
Add static int counter = 0; on the very next line after public class Main {
So the start of your class should look like:
public class Main {
static int counter = 0;
Now counter will be visible in all methods.
I would highly recommend not using a static counter, as suggested by others. Static mutable objects tend to violate the principle of object oriented programming. If you separate the functionality of your game into methods, you'll have a much more beautiful main method:
public static void main(String args[]) {
// Lets create a new Game object. it will keep track of the counter itself!
Game game = new Game();
// Then we only have to call the methods defined below..
game.enter();
game.firstLevel();
game.secondlevel();
}
Now the code for the class Game containing all the logic:
public class Game {
// Some static final members. they are not meant to change throughout the execution of the program!
// The advantage of defining INDENTAION just once, is that you can easily change it in one place and it will always be consistent!
private static final String INDENTAION = "\t\t";
private static final int TOTAL_POINTS = 2;
// We can use the same scanner object in each method!
private Scanner input = new Scanner(System.in);
// Just like the counter. it will be accessible in each method and refer to the same integer!
private int counter = 0;
public void enter() {
System.out.print("welcome to the impossibe game! Press enter to start.");
Scanner input = new Scanner(System.in);
String enter = input.nextLine();
if (enter.equals("")) {
System.out.println(INDENTAION + "Level one");
} else {
// I am not sure why you put this here, but I'll leave it in for now
System.out.println("Please press enter");
}
}
// We put that code into seperate methods, since it will get called multiple times!
private void answerCorrect() {
System.out.println("Correct!");
counter++;
printScore();
}
private void answerWrong() {
System.out.println("Wrong!");
printScore();
}
private void printScore() {
System.out.println(INDENTAION + "Score: " + counter +"/"+ TOTAL_POINTS);
}
public void firstLevel() {
System.out.println("What is the tenth digit of PI?");
int awnser = input.nextInt();
if (awnser == 5) {
answerCorrect();
}else{
answerWrong();
}
}
public void secondlevel() {
System.out.println("a king and queen get on a boat. then the boat sinks. how many people are alive");
String awnser = input.nextLine();
if (awnser.equals("two") || awnser.equals("2")) {
answerCorrect();
} else {
answerWrong();
}
}
}

How do I use array to print out my values when i exit my program?

import java.util.*;
import java.text.*;
public class DvdRental1 {
static Scanner input = new Scanner(System.in).useDelimiter("\r\n");
static DecimalFormat fmt=new DecimalFormat("0.00");
public static void main(String[] args)
{
String [] movies = new String[10];
movies[0] = "DRAG ME TO HELL";
movies[1] = "PARANORMAL ACTIVITY";
movies[2] = "SHUTTER";
movies[3] = "P.S I LOVE YOU";
movies[4] = "500 DAYS OF SUMMER";
movies[5] = "THE NOTE BOOK";
movies[6] = "2012";
movies[7] = "THE DAY AFTER TOMORROW";
movies[8] = "GAMER";
showmainmenu();
} // END OF MAIN
private static void showmainmenu()
{
int perday;
int mainmenu;
System.out.println("Welcome to TP DVD Rental Service");
System.out.println("");
System.out.println("---DVD RENTAL SYSTEM---");
System.out.println("-----------------------");
System.out.println("(1) Rent a DVD");
System.out.println("(2) Exit");
System.out.print("Please select your choice(1-2):");
mainmenu= input.nextInt();
if(mainmenu ==1 )
{
showmenu();
}
else if (mainmenu == 2)
{
goExit();
System.out.println("You have exited");
}
else
System.out.println("Please key in 1,2");
}
}
This is my first time using Java. I have another question whether this is the right way to make the program run this way, as will the showMenu() method i am using will it cause to program to run endlessly ? Thank you so much. As i have most of my content using methods to do a loop.
Make the array an instance variable, declared outside of any method. In other words, have this:
static Scanner input = new Scanner(System.in).useDelimiter("\r\n");
static DecimalFormat fmt=new DecimalFormat("0.00");
String[] movies = new String[10];
You can initialize it either outside of any method as an instance variable as follows:
String movies[] = new String[] { "DRAG ME TO HELL", "PARANORMAL ACTIVITY",
"SHUTTER", "P.S I LOVE YOU", ... };
Or you can just add the elements to the array inside mainmenu() as you are right now.
Then you can access it in showmainmenu() as well as in goExit() and loop through it, printing each entry just before doing System.exit() or whatever you do at the end of goExit();. You can do the latter (printing of the movies array) quite simply like this:
for(int i=0;i<movies.length;i++) {
System.out.println(movies[i]);
}
Alternatively, you can pass a reference to the array as an argument to the various methods.
Either pass movies as a parameter into showmainmenu(), and then in turn pass it onto goExit() or make it a global variable, in which case you can print it wherever you want.
You have two options, you could make the following:
String [] movies = new String[10];
A global variable, so you can reference it from anywhere in the class:
static Scanner input = new Scanner(System.in).useDelimiter("\r\n");
static DecimalFormat fmt=new DecimalFormat("0.00");
String [] movies = new String[10];//add here
Your second option is to pass the array to the showmainmenu() method. It would look as so:
showmainmenu(movies);
} // END OF MAIN
private static void showmainmenu(String [] movies)
{
//rest of code
Finally, you in order to print this you must loop through the array and print each value:
else if (mainmenu == 2)
{
for(int i = 0; i<movies.length; i++){
System.out.println(movies[i]);
}
goExit();
System.out.println("You have exited");
}
Read more about loops over arrays here.
I have another question whether this is the right way to make the
program run this way, as will the showMenu() method i am using will it
cause to program to run endlessly ?
Yes, I would recommend a do-while loop:
private static void showmainmenu()
{
int perday;
int mainmenu;
System.out.println("Welcome to TP DVD Rental Service");
System.out.println("");
System.out.println("---DVD RENTAL SYSTEM---");
System.out.println("-----------------------");
do{
System.out.println("(1) Rent a DVD");
System.out.println("(2) Exit");
System.out.print("Please select your choice(1-2):");
mainmenu= input.nextInt();
//code
else if (mainmenu == 2)
{
goExit();
System.out.println("You have exited");
break;//exits do-while
}
//code
}while(true)
If I understand it correctly, you can define each movies collection seperatelly as global variable like :
static String[] thrillerMovies = new String[] {"2012","THE DAY AFTER TOMORROW","GAMER"};
static String[] loveMovies = new String[] {"P.S I LOVE YOU","500 DAYS OF SUMMER","THE NOTEBOOK"};
static String[] horrerMovies = new String[] {"DRAG ME TO HELL","PARANORMAL ACTIVITY","SHUTTER"};
and define a method like below to show submenus :
private static void showSubmenu(String SubMenu,String[] movies) {
System.out.println("");
System.out.println( SubMenu + "MOVIE SELECTIONS");
System.out.println("------------------------");
for(int i=0;i<movies.length;i++) {
System.out.println("<" +(i+1)+"> " + movies[i]);
}
System.out.println("<4> Back to Main Menu");
System.out.println("------------------------");
System.out.print("Please select desired movie <1-3>:");
}
You can print the choices by calling the above method in your if like
if (menu == 1) {
showSubmenu("HORROR", horrerMovies);
-
else if (menu == 2) {
showSubmenu("LOVE", loveMovies);
-
else if (menu == 3) {
showSubmenu("THRILLER", thrillerMovies);
Similarly you can do the same in case of submenu choices if you wish. #Mohammad S. And #Martin Dinov already mentioned some points there.

Categories

Resources