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];
Related
I need help accessing the variables I have inputted using the child class. I made an object for the child class in my main class, however, I do not know how will I have access to the inputs I have entered and display them at the end of the code.
public abstract class player {
public abstract String name(String name);
public abstract void race(int race);
public abstract int[] getStatArray();
}
import java.util.Scanner;
public class childplayer extends player {
Scanner sc = new Scanner(System.in);
public String name(String name) {
System.out.print("Enter your name: ");
name = sc.nextLine();
return name;
}
public void race(int race) {
System.out.println("Race options: ");
System.out.println("\t 1 - Human \n\t 2 - Elf \n\t 3 - Orc \n\t 4 - Angel \n\t 5 - Demon");
System.out.print("Enter character's race: ");
race = sc.nextInt();
if((race>5)||(race<1)) {
while ((race>5)||(race<1)) {
System.out.print("Enter character's race: ");
race = sc.nextInt();
}
}System.out.println(" ");
}
public int[] getStatArray(){
int [] stat = new int [3];
int x = 0, y = 0, pts = 0;
System.out.println("Enter character's stats.");
while(y<3) {
System.out.print("Enter value: ");
x = sc.nextInt();
y++;
pts = pts + x;
}
int i = 0;
if(pts>10) {
System.out.println("Invalid input. Try again.");
while(i<3) {
System.out.print("Enter value: ");
x = sc.nextInt();
i++;
pts = pts + x;
}
}else {
stat[i] = x;
i++;
}
return stat;
}
}
If you want to keep the values to use later then you need to store them. The best way to do this is simply with a class variable like so:
public class Childplayer extends Player {
//Create class variables that store the values
String name = "";
int race = -1;
int[] stat = new int [3];
Then we just modify your methods to use these variables, for example:
public String name(String name) {
//Process the name
if(someCondition){
name = name +" Smith"
}
//Saved the passed in variable to the class variable `this.name`
this.name = name;
return this.name;
}
And another example:
public void race(int race) {
//Saved the passed in variable to the class variable `this.race`
this.race = race:
}
Then to get the information later we simply use:
//Earlier in the code
Childplayer playerA = new Childplayer();
//Some code here
//...
//Later in the code we can get the values
String name = playerA.name;
int storedRaceFromEarlier = playerA.race;
I strongly recommend making use of a constructor method to populate the class data. I have simplified the code and value checking for the sake of this example:
//Note that Java naming conventions require that classes should always have a capital letter at the start, I have fixed this in my example
public abstract class Player {
//Example getter abstract methods that must be implimented
public abstract String getName();
public abstract int getRace();
public abstract int[] getStatArray();
}
//Note that Java naming conventions require that classes should always have a capital letter at the start, I have fixed this in my example
public class Childplayer extends Player {
Scanner sc = new Scanner(System.in);
//Create class variables that store the values
String name = "";
int race = -1;
int[] stat = new int [3];
//Constructor method with exactly the same name as the class "Childplayer"
//This method should be responsible for creating the object and populating data
Childplayer(){
//Set name
System.out.print("Enter your name: ");
name(sc.nextLine());
System.out.print("Name set as " + name + "\r\n");
//Set race
System.out.println("Race options: ");
System.out.println("\t 1 - Human \n\t 2 - Elf \n\t 3 - Orc \n\t 4 - Angel \n\t 5 - Demon");
int result = -1;
while ((result>5)||(result<1)) {
System.out.print("Enter character's race: ");
result = sc.nextInt();
}
//Set the race with the abstract method
race(result);
System.out.print("Race set as " + race + "\r\n");
System.out.println("Enter character's stats.");
int i = 0;
while(i<3) {
System.out.print("Enter stat value: ");
//Save the stat to the class variable
stat[i] = sc.nextInt();
i++;
}
}
//Abstract methods implemented to return the correct values
public String getName(){
return name;
}
public int getRace(){
return race;
}
public int[] getStatArray(){
return stat;
}
}
how to print Junior, Intermediate,Seniour as string as per age,and must generate roll number and these input must b generated from the user. Ex: junior name:Rahul age:22, roll:1000 intermediate name:prem age:40, roll:1001 senior name: Vamsi age:60, rollno:1002
String name;
static int age;
public static void main(String[] args) {
int size = 3;
DB[] studs = new DB[size];
for (int i = 0; i < size; i++) {
studs[i] = readStudent(i);
}
for (int i = 0; i <studs.length; i++) {
if(age <=30) {
System.out.println( studs[i]);
}else if(age <=40) {
System.out.println("Intermidiate" +" "+studs[i]);
}else {
System.out.println("Seniour" +" "+studs[i]);
}
}
}
static DB readStudent(int i) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name:");
String name = sc.nextLine();
System.out.print("Enter your age:");
int age = sc.nextInt();
DB studs = new DB(name, age);
return studs;
}
}
class juniourStudent extends Student {
String rollno = "juniour";
static int juniourcount = 1000;
juniourStudent(String name, int age) {
rollno = "juniour" + juniourcount++;
}
}
class intermidiateStudent extends Student {
String rollno = "intermidiate";
static int intermidiatecount = 1000;
intermidiateStudent(String name, int age) {
rollno = "intermidiate" + intermidiatecount++;
}
}
class seniourStudent extends Student {
String rollno = " seniour";
static int seniourcount = 1000;
seniourStudent(String name, int age) {
rollno = "seniour" + seniourcount++;
}
}
There are quite a few issues with your code.
Your class structure is counter-intuitive to what you are trying to do. Based on the example output, it seems that you want the rollNo to increase every time a student is made. It also seems to be redundant to create separate classes when the only thing that differs between them is the prefix (like junior, senior, intermediate, etc.). Instead of making multiple classes, why not add an instance variable to your student class. (Also import Scanner so we can use it later for user input, and ArrayList to store the student data) For Example:
import java.util.Scanner;
import java.util.ArrayList;
public class Student {
String name;
String studentType;
int age;
int rollno;
static int schoolRollno = 1000;
Next you should make a proper constructor for your student class consisting of a String name and an int age, and assigning them to the instance variables we declared earlier. We will assign the studentType variable based upon their age, and we will obtain the students rollno from the static variable. We must increment the static variable so the next student will have a different roll number. (You can change the age comparisons to whatever number you need, but these numbers are what I pieced together from your code)
public Student(String name, int age) {
this.name = name;
if(age <= 30) {
this.studentType = "Junior";
}
else if(age <= 40) {
this.studentType = "Intermediate";
}
else {
this.studentType = "Senior";
}
this.age = age;
this.rollno = schoolRollno;
schoolRollno++;
}
The last thing we need to do before we work on our main function is to write a toString() method for our student class. Based upon the output, you might want a method like this:
#Override
public String toString() {
return studentType + " name: " + name + " age: " + age + ", roll: " + rollno;
}
Now we can take a look at the public static void main(String args[]) function. We have a few things we need to do here. Since it appears we do not know the number of students we are going to be adding, we should use an ArrayList. We should also instantiate our scanner here as well:
ArrayList<Student> students = new ArrayList<Student>();
Scanner scan = new Scanner(System.in);
Now we should create a while loop that allows the user to continue inputting students and wish to stop. Personally, I'm a fan of the do/while loop, so I'll do it that way. We'll need to declare our variable outside of the loop so that we can use it as a conditional for the loop.
boolean done = false;
do {
//(inner loop code here)
} while(!done);
//end loop code
Now for the inner loop code. We need to obtain a String (name) from the user and an int (age). Once we obtain the inputs, we want to construct a Student object and add it to our ArrayList. Then, after all that, we want to see if the user wants to input another student (by changing the value of our boolean we used when declaring the first do/while loop according to the user's input). We can do all this using scanner like so:
System.out.println("Enter name:");
String name = scan.nextLine();
System.out.println("Enter age:");
int age = scan.nextInt();
//we use scan.nextLine() here because scan.nextInt() does not read to the end of the line
scan.nextLine();
Student s = new Student(name, age);
students.add(s);
boolean validInput = true;
do {
validInput = true;
System.out.println("Continue? (y/n)");
String input = scan.nextLine();
if(input.equalsIgnoreCase("y")) {
done = false;
}
else if(input.equalsIgnoreCase("n")) {
done = true;
}
else {
validInput = false;
}
} while(!validInput);
Finally, we want to print the students once we are done. We can print all the students in our ArrayList easily using a for-each loop. (This goes at the end of our main(String args[]) method)
for(Student s: students) {
System.out.println(s.toString());
}
TL;DR:
Combine your classes into one student class
Fix the constructor
Add a toString() method
Use an ArrayList to store the students b/c we don't know the number. (DB isn't a class in java, and an array is counter-intuitive when you don't know what size you'll need)
Create a loop that the user can break out of when they wish to
Obtain user input for the name and age, and use this to construct a student object and add it to the ArrayList
Print out all the students in the ArrayList after the loop
Hi i am new to Java and i am writting a simple programm that will emulate a diving competition. I use NetBeans and i cannot find out why it gives me this error.
The code is this :
package agoneskataduseon;
import java.util.Scanner;
public class AgonesKataduseon {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numAth, numJud, numDiv;
System.out.print("Give the number of the athletes in the competition : ");
numAth = input.nextInt();
System.out.print("Give the number of the judges : ");
numJud = input.nextInt();
System.out.print("Give the numbe rof dives : ");
numDiv = input.nextInt();
DivingCompetition game = new Diving Competition(numAth, numJud, numDiv);
}
}
The DivingCompetition class(it is not finished) :
import java.util.Scanner;
public class DivingCompetition {
int numa;
int numj;
int numd;
Athlete[] arr1 = new Athlete[12];
Athlete[] arr2 = new Athlete[12];
public DivingCompetition(int numAthletes, int numJudges, int numDives){
numa = numAthletes;
numj = numJudges;
numd = numDives;
}
public void readAthletesName(){
String nam;
int i=0;
Scanner input = new Scanner(System.in);
while(i < numa){
System.out.print("Give the name of athlete num "+(i+1)+" : ");
nam = input.nextLine();
arr1[i] = new Athlete(nam);
i++;
}
}
public void runCompetition(){
int i=0;
Dive dv = new Dive(numj);
while(i<12){
arr1[i].addDive(dv);
}
}
}
And for the record the Athlete class:
public class Athlete {
String names;
Dive[] arrayd = new Dive[6];
double fullScore;
int point;
public Athlete(String name){
names = name;
fullScore = 0;
point = 0;
}
public void addDive(Dive dive){
arrayd[point] = dive;
fullScore = fullScore + arrayd[point].computeScore();
point++;
}
}
I would also give you the Dive class but i dont see the point of doing that
NetBeans is giving me an error in the main function :
Cannot find symbol
Symbol: class DivingCompetition
location: class AgonesKataduseon
And my question is why it gives me this error?
This problem also happens if i try to make an object of Athlete or Dive inside the main function
Netbeans will try to help and give you suggestions to fix your code if you ask it to. All you have to do is to place the cursor on the line where the problem is and press Alt + Enter.
It actually gives you this keyboard shortcut at that bottom of the error message when you hover over the erroneous statement.
See the Code Assistance page in the manual for more info.
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();
So I've read over all of the constructor undefined posts on stackoverflow and tried the solutions and they haven't worked for me. Maybe I'm trying it wrong. I keep getting "the constructor Gerbil(int) is undefined."
The code that's the problem:
GerbilArray[i] = new Gerbil(i);
My full code:
import java.util.Scanner;
public class Gerbil {
public String name;
public String id;
public String bite;
public String escape;
public Gerbil() {
this.name = "";
this.id = "";
this.bite = "";
this.escape = "";
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("How many foods?");
int totalFood = keyboard.nextInt();
System.out.println("How many gerbils in the lab?");
int numberOfGerbils = keyboard.nextInt();
Gerbil[] GerbilArray = new Gerbil[numberOfGerbils];
for(int i = 0; i <= numberOfGerbils; i++){
GerbilArray[i] = new Gerbil(i);
System.out.print("Lab ID:");
String id = keyboard.next();
System.out.print("Gerbil Nickname:");
String name = keyboard.next();
System.out.print("Bite?");
String bite = keyboard.next();
System.out.print("Escapes?");
String city = keyboard.nextLine();
for (int j = 0; j < totalFood; j++) {
System.out.println("How many of food " + (j+1) + "do you eat?:");
}
}
}
}
Also you've probably seen that my nested for-loop isn't finished as well. I'm trying to make an array inside of an object that will store "x" amount of integers inside of my object listed from the user (int totalFood) but I have no idea how.
You don't have a constructor Gerbil(int a) in the class Gerbil and you try to call it!
Just call it this way:
GerbilArray[i] = new Gerbil();