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();
}
}
}
Related
import java.util.Scanner;
public class MP3
{
//this is the main code that I need to connect each method to each method.
//so that if the user press 2 it will go to snacks but even if you press two now it just continues the code and go-to meals.
//how can I make it so that the user can choose which menu he/she likes to go through?
public static void main(String[] args)
{
int Options_Snacks;
int Options_Snacks2;
int Options_Snacks3;
int Options_Drinks;
int Options_Drinks2;
int Options_Drinks3;
int diff,prod ;
int yes = 1;
int no = 2;
int End;
do {
mainmenu();
mainmeals();
mainsnacks();
Scanner myInput = new Scanner(System.in);
System.out.println("Would you like to order more: press " + yes +" for yes and " + no +" for no");
End = myInput.nextInt();
} while(End == 1);
}
// this code runs smoothly but the other menus don't run when the user press the number instead it runs all the code within the while loop.
public static void mainmenu()
{
int Orders;
int Meals = 1;
int Snacks = 2;
int Drinks = 3;
int EXIT = 4;
Scanner myInput = new Scanner(System.in);
System.out.println("=======[STRESSFOOD]=====");
System.out.println("---------[ Menu ]-------");
System.out.println("1----------Meals--------");
System.out.println("2---------Snacks--------");
System.out.println("3---------Drinks--------");
System.out.println("4--------[ EXIT ]-------");
Orders = myInput.nextInt();
}
[here's the code I didn't get all in the picture][1]
}
What about the following implementation:
public static void main(String[] args) {
openMenu();
}
With the while loop in the menu function :
private static void openMenu() {
Scanner scan = new Scanner(System.in);
do {
System.out.println("1) Meals");
System.out.println("2) Snacks");
System.out.println("3) Drinks");
System.out.println("4) Exit");
System.out.print("Your choice ? ");
switch (scan.nextInt()) {
case 1:
openMealsMenu();
break;
case 2:
openSnacksMenu();
break;
case 3:
openDrinksMenu();
break;
case 4:
scan.close();
return;
default:
System.out.println("This is not a valid choice");
}
} while (true);
}
Note that you should only use one scanner in your application. If you need your scanner in the openMealsMenu() for example, pass it as a parameter of the method, or just declare a static scanner in your MP3 class since your methods are in the same class.
By the way, by convention, variables should start with a lowercase letter and do not take a _ (ie. Options_Drinks3 becomes optionsDrinks3).
I'm trying to make a program which asks the user a particular bird then how many of them they had seen at that point. If the use at any point enters the word 'END' then the system should print out the most seen bird and the number seen. However, when running my program if I enter 'END' at random points it instead returns that the most seen was END with 0 seen. I can't figure out how to make it work. I've tried different methods but it's just not working properly. Also, I've set the maximum array limit to 10 possitions but it continues after 10 and if i enter a value the system crashes. Have I written the limit part properly? Or am I missing something important?
import java.util.Scanner;
public class testing
{
public static void main (String[] param)
{
birdInput();
most();
System.exit(0);
}
public static void birdInput()
{
int i = 0;
String birdInput;
int numberInput;
Scanner scanner = new Scanner(System.in);
int maxVal = Integer.MIN_VALUE;
int maxValIndex = -1;
while (true)
{
System.out.println("What bird did you see?");
birdInput = scanner.nextLine();
if (birdInput.equals("END"))
{
System.out.print("\nWell....I guess thanks for using this program?\n");
System.exit(0);
}
else
{
String[] birds = new String[10];
int[] numbers = new int[10];
birds[i] = scanner.nextLine();
System.out.println("How many did you see?");
numbers[i] = scanner.nextInt();
i++;
if (birds[i].equals("END"))
{
maxVal = numbers[i];
maxValIndex = i;
System.out.print("\nThe most common bird that you saw was the " + birds[maxValIndex] + " with " + maxVal + " being seen in total\n");
System.exit(0);
}
}
}
}
public static void most()
{
System.out.println("fdff");
}
}
This is my edit of Till Hemmerich's answer to my issue. I tried to remove the global variables and so combine the entire code into 1 method. However, I'm still having some issues. Been working at it but really confused.
import java.util.Scanner;
public class birds2
{
public static void main(String[] param)
{
birdInput();
System.exit(0);
}
public static void birdInput()
{
Scanner scanner = new Scanner(System.in);
String[] birds = new String[99999999];
int[] numbers = new int[99999999];
int i = 0;
int maxIndex;
while (i <= birds.length)
{
System.out.println("What bird did you see?");
birds[i] = scanner.nextLine();
System.out.println("How many did you see?");
numbers[i] = scanner.nextInt();
i++;
}
int newnumber = numbers[i];
if ((newnumber > numbers.length))
{
maxIndex = i;
i++;
}
if (birds[i].toUpperCase().equals("END"))
{
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
}
}
You're re-declaring the birds and numbers arrays in each iteration of the loop. They should be declared and initialized only once, before the loop.
I changed a lot so im going to explain my changes here in total.
First of all i had to move the Array Definition out of your while-loop as >mentioned above, since other wise you would override these Arrays every time.
I also made them globally accessible to work with them in other methods.
public static int maxIndex;
public static String[] birds = new String[10];
public static int[] numbers = new int[10];
in general I re structured the whole code a little bit to make it more readable and a little bit more object-orientated.
For example I created an method called inputCheck() which returns our input as a String and check if it equals END so you do not have to write your logic for this twice. (it also considers writing end lower or Uppercased by just Upper our input before checking it"if (input.toUpperCase().equals("END"))")
static String inputCheck() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.toUpperCase().equals("END")) {
end();
}
return input;
}
this method can now be called every time you need an input like this:
birds[i] = inputCheck();
but you need to be carefull if you want to get an integer out of it you first have to parse it like this:Integer.parseInt(inputCheck())
after that I wrote a method to search for the biggest Value in your numbers Array and getting its index:
public static int getMaxIndex(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int newnumber = numbers[i];
if ((newnumber > numbers.length)) {
maxIndex = i;
}
}
return maxIndex;
}
it takes an int array as parameter and returns the index of the highest element in there as an Integer. Called like this:maxIndex = getMaxIndex(numbers);
Then after that I rewrote your end method. It now just calles our getMaxIndex method and prints some output to the console.
public static void end() {
maxIndex = getMaxIndex(numbers);
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
to fix your last problem (crashing after more then 10 inputs)I changed your while-loop. Since your array only has 10 places to put things it crashes if you try to put information in place number 11. it not looks like this:while (i <= birds.length) instead of while (true) this way the max loops it can take is the amout of places Array birds has and it wont crash anymore.
public static void birdInput() {
int i = 0;
while (i <= birds.length) {
System.out.println("What bird did you see?");
birds[i] = inputCheck();
System.out.println("How many did you see?");
numbers[i] = Integer.parseInt(inputCheck()); //you should check here if its actuall a number otherwiese your programm will crash
i++;
}
}
Here is the whole code in total:
import java.util.Scanner;
/**
*
* #author E0268617
*/
public class JavaApplication1 {
public static int maxIndex;
public static String[] birds = new String[10];
public static int[] numbers = new int[10];
public static void main(String[] param) {
birdInput();
most();
System.exit(0);
}
public static void birdInput() {
int i = 0;
while (i <= birds.length) {
System.out.println("What bird did you see?");
birds[i] = inputCheck();
System.out.println("How many did you see?");
numbers[i] = Integer.parseInt(inputCheck()); //you should check here if its actuall a number otherwiese your programm will crash
i++;
}
}
static String inputCheck() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.toUpperCase().equals("END")) {
end();
}
return input;
}
public static int getMaxIndex(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int newnumber = numbers[i];
if ((newnumber > numbers.length)) {
maxIndex = i;
}
}
return maxIndex;
}
public static void end() {
maxIndex = getMaxIndex(numbers);
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
public static void most() {
System.out.println("fdff");
}
}
I hope you understand where the Problems had been hidden if you have any Questions hit me up.
I am making a game-ish type of thing with three classes, combined. NOT HOMEWORK; hobby.
Codes for three classes:
Runner:
public class CounterGameRunner
{
// instance variables - replace the example below with your own
public static void main(String [] args){
Scanner input = new Scanner(System.in);
CounterGameCounter game = new CounterGameCounter();
System.out.println("You want to play a game I see. What is your name?");
String name = input.next();
game.NameIn(name);
CounterGAME game1 = new CounterGAME();
game1.actual();
}
}
Actual Game:
public class CounterGAME
{
// instance variables - replace the example below with your own
Scanner input = new Scanner(System.in);
int number;
int count=1;
boolean loop = true;
public CounterGAME(){
}
public void actual(){
CounterGameCounter game2 = new CounterGameCounter();
System.out.println("Guess a number between 1 and 101, see how many times you get it!");
number=input.nextInt();
int r = (int)(Math.random() * (100) + 1);
while(loop==true){
if(number < r){
System.out.println("Too small, try again");
number = input.nextInt();
count++;
game2.Counter(count);
} else if(number == r){
System.out.println("Wow, you won! Who'd have thought?");
count++;
game2.Counter(count);
break;
System.out.println(game2.done());
} else if(number > r){
System.out.println("Too large, try again");
number = input.nextInt();
count++;
game2.Counter(count);
}
}
}
}
Counter Class:
public class CounterGameCounter
{
// instance variables - replace the example below with your own
private String Name;
String done1;
int correct;
public CounterGameCounter(){
}
public String NameIn (String nm){
Name = nm;
return Name;
}
public String NameOut(){
return Name;
}
public void Counter(int count){
correct = count;
}
public int getCount(){
return correct;
}
public String done(){
done1 = "Name: " + NameOut() + "\n" +
"Times Answered: " + getCount();
return done1;
}
}
Problem:
The counter works properly and everything else displays and functions properly in the end. However, any name I input in the beginning always shows "null" while running the program. Why?
Your variable names are really confusing, and there are a lot of bad practices in your code, but null in name is because you create a new Counter in CounterGAME:
public void actual(){
// here
CounterGameCounter game2 = new CounterGameCounter();
// more code
}
Change actual to receive a CounterGameCounter:
public void actual(CounterGameCounter game2){
// more code
}
And call it like:
public static void main(String [] args){
Scanner input = new Scanner(System.in);
CounterGameCounter game = new CounterGameCounter();
System.out.println("You want to play a game I see. What is your name?");
String name = input.next();
game.NameIn(name);
CounterGAME game1 = new CounterGAME();
game1.actual(game);
// more stuff
}
FREE TIPS:
use String getName() and void setName(String)
start variable, object and attribute names with lowercase
String name;
Object object;
Variable names must be representative and descriptive
CounterGameCounter counterGameCounter = new CounterGameCounter();
This is also applicable to Object names:
GameCounter gameCounter = new CounterGameCounter();
try this:
String name = input.nextLine();
instead of:
String name = input.next();
This question already has answers here:
Creating an array of objects in Java
(9 answers)
Closed 7 years ago.
I'm getting an NullPointerException error and cant figure out why. I've included all three classes which I'm working on and made ////note where eclipse is saying the error is coming from in the main method (two locations apparently).
I'm new to coding and from what I understand this happens when you are trying to pass something that is considered null, but I believe I'm trying to pass the newly created fish from earlier in the code. I'm sure the error is very easily caught by someone with an experienced eye.
Thank you!
import java.util.Scanner;
public class FishTankManager {
private static Scanner stdin = new Scanner(System.in);
private static int userInput, userInput2;
private static FishTank[] tanks = new FishTank[10];
public static void main (String[] args) {
while (true){
System.out.println("Welcome to your new fish tank manager!\n"+
"What would you like to do?\n"+
"(1)Add a Fish\n(2)Remove a Fish\n"+
"(3)Check a tank");
userInput = stdin.nextInt();
if (userInput == 1){
Fish fish = new Fish();
changeTank(fish); //// Says its at here
continue;
}
else if(userInput ==2){
removeFish();
}
else{
checkTank();
}
}
}
private static void changeTank(Fish fish){
System.out.println("Which tank would you like to put this fish in? (1-10)");
userInput = stdin.nextInt();
tanks[userInput-1].addFish(fish); ////and says its at here also
}
private static void removeFish(){
System.out.println("Which tank would you like to remove the fish from? (1-10)");
userInput = stdin.nextInt();
System.out.println("Which fish would you like to flush down the toilet?");
tanks[userInput-1].fishInTank();
userInput2 = stdin.nextInt();
tanks[userInput-1].flushFish(userInput2-1);
}
private static void checkTank(){
System.out.println("Which tank would you like to check?");
userInput = stdin.nextInt();
tanks[userInput-1].fishInTank();
}
}
public class FishTank {
private Fish[] tank;
private int fishCount = 0;
public FishTank(){
this.tank = new Fish[5];
this.fishCount = 0;
}
public void addFish(Fish fish){
if (this.fishCount >=5 ){
System.out.println("This tank is full! Try another");
return;
}
else {
this.tank[fishCount] = fish;
this.fishCount++;
}
}
public void fishInTank(){
for(int i=0; i<5; i++)
if (this.tank[i] == null){
continue;
}
else{
System.out.println("("+(i+1)+")"+this.tank[1].getName());
}
}
public void flushFish(int f){
this.tank[f] = null;
}
}
import java.util.Scanner;
public class Fish {
private static Scanner stdin = new Scanner(System.in);
private String userInput;
private int userInput2;
private boolean mean;
private String name;
public Fish(){
System.out.println("What is your fishes name?");
userInput = stdin.next();
this.name = userInput;
System.out.println("Is this fish aggressive?\n"+
"(1)Yes\n(2)No");
userInput2 = stdin.nextInt();
if (userInput2 == 1)
this.mean = true;
else
this.mean = false;
}
public String getName(){
return this.name;
}
public boolean getMean(){
return this.mean;
}
}
tanks is only created as array, but without creating any FishTank. Due to this, all elements in tanks are null. So this: tanks[userInput-1].addFish(fish); won't work because tanks[userInput - 1] is null. And for the locations: the stacktrace tells you all methods up to the one causing the exception. So "it happens here" and "also here" is actually "this method calls this method which throws the exception here" and "in this method the exception is thrown here"
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().