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"
Related
I'm trying to return the string "otheruser" from static void Answer2 to my main method.
public static void main(String[] args) {
System.out.println("is there another person with you?");
Scanner Answer2 = new Scanner(System.in);
String answer2 = Answer2.nextLine();
if (answer2.equals("yes")) {
System.out.println("ok then type there name in please");
Answer2();
} else if (answer2.equals("no")) {
System.out.println("ok then good day");
}
System.out.println("how old are you " + Answer2());
}
static void Answer2() {
Scanner otheruser = new Scanner(System.in);
String Otheruser = otheruser.nextLine();
System.out.println("hi " + Otheruser);
}
Instead of printing the string you got from the Scanner, you could return it, so it's available to the rest of the program:
static String answer2() {
Scanner otheruser = new Scanner(System.in);
String otherUser = otheruser.nextLine();
return otherUser;
}
In Java it is common practice to name methods and variables using camel case naming convention
You can not get a return value from the function static void Answer2() because the return type is void, which means it doesn't return anything. You need to change the return type to String to get the value.
As mentioned by Zabuza in the comments, you should not create multiple scanners on the same stream.
Additionally, if you really want to use methods for this you can make them more generic, and use them to get any input.
import java.util.Scanner;
public class Main {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("is there another person with you?");
String answer = getString();
if (answer.equalsIgnoreCase("yes")) {
System.out.println("ok then type their name in please");
String otherUser = getString();
System.out.printf("hi %s. how old are you?%n", otherUser);
int age = getNumber();
System.out.printf("%s is %d years old%n", otherUser, age);
} else {
System.out.println("ok then good day");
}
}
static String getString() {
return scanner.nextLine();
}
static int getNumber() {
return scanner.nextInt();
}
}
I am new to java ,I just want to create array of humans object in class Earth
But I am getting error :
Exception in thread "main" java.lang.NullPointerException
at Earth.main(Earth.java:14)
I don't know what's wrong with my program it seems everything regarding syntax is correct .
Input:
2
12
aks (...and .. program crash)
import java.util.*;
public class Human {
String name;
int age;
int height;
String eyecolor;
//construct necessary
public Human() {
}
public void speak() {
System.out.println("Hello My name is " + name);
System.out.println("I am "+height + "inches tall");
}
public void eat() {
System.out.println("eating...");
}
}
import java.util.*;
public class Earth {
public static void main(String args[]) {
Human humans[] = new Human[10];
System.out.println("Enter the number of humans\n");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=0;i<n;i++) {
int age;
String name;
age = sc.nextInt();
name = sc.next();
humans[i].age=age;
humans[i].name=name;
}
for(int i=0;i<n;i++) {
System.out.printf("name is %s and age is %d \n", humans[i].name,humans[i].age);
}
sc.close();
}
}
Your statement :
Human humans[] = new Human[10];
creates an array to hold 10 humans, but it does not create those humans. Instead, each of the 10 entries is initialised to null - hence your exception when you try to use them in humans[i].age=age;
Instead, create the humans in the loop :
for(int i=0;i<n;i++) {
int age;
String name;
age = sc.nextInt();
name = sc.next();
humans[i] = new Human(); // Add This
humans[i].age=age;
humans[i].name=name;
}
It would also be a good idea to move the declaration of the array to after the user has entered the number of humans they want; As it stands, there's nothing to stop the user entering a number more than 10, which would also cause a problem. So try something like :
System.out.println("Enter the number of humans\n");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Human humans[] = new Human[n];
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();
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();
}
}
}
I'm trying to make a quiz type game and for some reason when I add the if statement below it executes the ask method twice. You will get asked the question twice before it returns whether it is correct or not.
import java.util.Scanner;
public class QuizGame
{
private int correct;
private int wrong;
private Scanner inputScan;
private Quiz customQuiz;
public QuizGame()
{
correct=0;
wrong=0;
inputScan = new Scanner(System.in);
}
private void startQuiz()
{
System.out.println("Use custom upper limit? (y/n) ");
String custom = inputScan.next();
if(custom.equalsIgnoreCase("y"))
{
System.out.println("What do you want to be your upper limit?");
int limit = inputScan.nextInt();
customQuiz = new Quiz(limit);
customQuiz.ask();
if(customQuiz.ask())
{
correct +=1;
System.out.println("Correct!");
}
else
{
wrong+=1;
System.out.println("Wrong!");
}
}
}
public static void main(String[] args)
{
QuizGame quiz1 = new QuizGame();
quiz1.startQuiz();
}
}
other class that asks the questions:
import java.util.Random;
import java.util.Scanner;
public class Quiz
{
private Random rGen;
private int num1;
private int num2;
private Scanner getInput;
private int answer;
public Quiz(int n1)
{
rGen = new Random();
num1 = rGen.nextInt(n1);
num2 = rGen.nextInt(n1);
getInput = new Scanner(System.in);
}
public boolean ask()
{
int answer = num1 * num2;
System.out.println("What is " + num1 + " x " + num2);
int userAnswer = getInput.nextInt();
return answer == userAnswer;
}
}
I isolated the problem and it definitely seems to be the if statement: if(customGame.ask()) {} in the driver class, but I don't see why. It's not like if(customGame.ask()) calls the ask method again, it just tests if it returns true? I've also tried with just if(customGame.ask() == true) and still nothing.
Well, you are calling customQuiz.ask() twice :
customQuiz.ask();
if (customQuiz.ask ())
{
correct += 1;
System.out.println ("Correct!");
}
Simply call it just once :
if (customQuiz.ask ())
{
correct +=1;
System.out.println ("Correct!");
}
Or (as suggested by #RobertHarvey) you can put the result of the method in a variable and use it later :
boolean correct = customQuiz.ask ();
if (correct)
{
correct += 1;
System.out.println ("Correct!");
}