This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 years ago.
Keep getting this error, sorry I am a beginner in Java.
Exception in thread "main": java.lang.NullPointerException
at assignment01.Student.addGrade(Student.java:28)
at assignment01.GpaTest.main(GpaTest.java:11)
package assignment01;
public class Grades
{
private double qualPts;
private int numCred;
public double getGPA()
{
if(numCred!=0)
{
return(qualPts/numCred);
}
return numCred;
}
public void addGrade(int creds, double grade)
{
grade+=creds+numCred;
qualPts+=creds*grade;
}
public int getNumCred()
{
return numCred;
}
}
.
package assignment01;
public class Student
{
private String name;
private String bNumber;
private Grades grades;
public Student(String name, String bNumber)
{
this.name=name;
this.bNumber=bNumber;
}
public void addGrade(int creds, double grade)
{
grades.addGrade(creds, grade);
}
.
package assignment01;
public class GpaTest {
public static void main(String[] args)
{
Student theStudent= new Student("Ethan","00000000");
int CREDITS_ENROLLED1=4;
double GRADE1=90;
theStudent.addGrade(1, 100);
theStudent.addGrade(CREDITS_ENROLLED1,GRADE1);
System.out.println("Determining the grades of student named Ethan.");
System.out.println("Ethan has a grade of 90.");
}
}
grades variable is not initialized. You need to initialize it inside Student constructor:
public Student(String name, String bNumber)
{
this.name=name;
this.bNumber=bNumber;
this.grades = new Grades();
}
You may wish to initialize qualPts and numCred as well
Initialize the object 'grades'.
Related
These are my quiz and question class.
class Question{
String question, answer;
Question()
{
question = null;
answer = null;
}
public Question(String question, String answer)
{
this.question = question;
this.answer = answer;
}
public String toString(){
return question;
}
}
class Quiz extends Question{
String name;
Quiz(String name)
{
super();
this.name = name;
}
public void addQuestion(Question q)
{
answer = q.answer;
question = q.question;
}
public String toString(){
return name+"\n\n" + question;
}
}
And this is my driver class.
public class QuizSample{
public static void main(String[] args){
Quiz sample = new Quiz("Sample 1903 Quiz");
sample.addQuestion(new Question("Who is known as the father of Java?", "James Gosling"));
sample.addQuestion(new Question("Write a statement that assigns the length of a string s to int i", "i = s.length();"));
sample.addQuestion(new Question("True or false: assigning an int to double is an example of a widening conversion", "true"));
System.out.println(sample);
}
}
This is the output:
Sample 1903 Quiz
True or false: assigning an int to double is an example of a widening conversion
But I want to print all the questions that I have passed.
Please help guys.
Class Quiz does not need to extend Question but rather to have a collection of questions (list or set).
Also, toString method needs to be updated to pretty print questions.
import java.util.*;
import java.util.stream.*;
class Quiz {
String name;
List<Question> questions = new ArrayList<>();
Quiz(String name) {
this.name = name;
}
public void addQuestion(Question q) {
questions.add(q);
}
public String toString() {
return name+"\n\n" + questions.stream()
.map(Question::toString)
.collect(Collectors.joining("\n"));
}
}
Your Quiz class can have a List to store all the questions,
like
List<Questions> lstQuestions = new ArrayList<Questions>();
and can be used in addQuestion method to add all the questions,
public void addQuestion(Question q)
{
lstQuestions.add(q);
}
and the main method can look like below,
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Welcome to my Quiz");
for(Question quest : lstQuestion){
System.out.println(quest);
String ans = console.next();
if(quest.getAnswer().equals(ans.trim())){
System.out.println("right answer");
}else{
System.out.println("wrong answer");
}
}
console.close();
}
This question already has answers here:
Just started learning Java. Why is the main() inside of a class?
(3 answers)
Closed 5 years ago.
I don't understand why I get a compilation error, I hope someone can help out here. I would appreciate it a lot. I'm trying to make a system for a lot of cars.
public class Car {
//Instance Variables
String make;
String model;
int year;
boolean isNew;
double miles;
String owner;
public void sell (String newOwner) {
owner=newOwner;
if (isNew){
isNew=false;
}
}
public boolean isOld() {
int thisYear=Calendar.getInstance().get(Calendar.YEAR);
if (thisYear-year > 10) {
return true;
} else {
return false;
}
}
}
public static void main(String[] args) {
Car myCar = new Car(); //myCar is a variable and new the keyword
myCar.make = "Audi";
myCar.model = "A4";
myCar.year =2014;
myCar.isNew=true;
myCar.miles =0;
myCar.owner ="Jeyson";
boolean isMyCarOld = myCar.isOld();
myCar.sell("John Doe");
System.out.println("Car owned by" + myCar.owner);
}
You cannot write main method out side of your class. It should be written inside class.
The following code should work,
public class Car {
//Instance Variables
String make;
String model;
int year;
boolean isNew;
double miles;
String owner;
public void sell (String newOwner) {
owner=newOwner;
if (isNew){
isNew=false;
}
}
public boolean isOld() {
int thisYear=Calendar.getInstance().get(Calendar.YEAR);
if (thisYear-year > 10){
return true;
} else {
return false;
}
}
public static void main(String[] args){
Car myCar = new Car(); //myCar is a variable and new the keyword
myCar.make = "Audi";
myCar.model = "A4";
myCar.year =2014;
myCar.isNew=true;
myCar.miles =0;
myCar.owner ="Jeyson";
boolean isMyCarOld = myCar.isOld();
myCar.sell("John Doe");
System.out.println("Car owned by" + myCar.owner);
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to make a student registration interface with several classes, provided in the requirement. In doing so, the linkedlist in my CourseFactory class is showing a null pointer.
public class Course {
private String id;
private String title;
private int credit;
private int tuitionPerCredit;
public void setId(String id){
this.id=id;
}
public String getId(){
return this.id;
}
public void setTitle(String title){
this.title=title;
}
public String getTitle(){
return this.title;
}
public void setCredit(int credit){
this.credit=credit;
}
public int getCredit(){
return this.credit;
}
public void setTuitionPerCredit(int tuitionPerCredit){
this.tuitionPerCredit=tuitionPerCredit;
}
public int getTuitionPerCredit(){
return tuitionPerCredit;
}
public int getSubTotal(){
return this.credit*this.tuitionPerCredit;
}
}
And CourseFactory class
import java.util.LinkedList;
import static android.R.attr.id;
public class CourseFactory {
LinkedList<Course> cList;
public void CourseFactory(){
Course course = new Course();
course.setId("CSE327");
course.setTitle("SOFT ENG");
course.setCredit(3);
course.setTuitionPerCredit(1500);
cList.add(course);
Course course1 = new Course();
course1.setId("CSE115");
course1.setTitle("INTRO C");
course1.setCredit(3);
course1.setTuitionPerCredit(1500);
cList.add(course1);
Course course2 = new Course();
course2.setId("CSE215");
course2.setTitle("INTRO JAVA");
course2.setCredit(3);
course2.setTuitionPerCredit(1500);
cList.add(course2);
Course course3 = new Course();
course3.setId("CSE225");
course3.setTitle("DATA STRUCT");
course3.setCredit(3);
course3.setTuitionPerCredit(1500);
cList.add(course3);
Course course4 = new Course();
course4.setId("CSE373");
course4.setTitle("ALGOR.");
course4.setCredit(3);
course4.setTuitionPerCredit(1500);
cList.add(course4);
}
public Course getCourse(String id){
int temp = 0;
for(int i=0;i<cList.size();i++) {
if (cList.get(i).getId().equals(id)) {
temp=i;
break;
}
}
return cList.get(temp);
}
}
The error is on the line "if (cList.get(i).getId().equals(id))
You have to initialize LinkedList. Or else it will get null-pointer exception.
LinkedList<Course> cList=new LinkedList<Course>();
You need to initialize cList before use
LinkedList<Course> cList=new LinkedList<Course>();
or better, initialize into CourseFactory's constructor
public void CourseFactory(){
cList=new LinkedList<Course>();
Course course = new Course();
...
...
}
diamond operator is supported in -source 7 or higher
LinkedList<Course> cList=new LinkedList<>();
This question already has answers here:
Java Reserve Keywords
(4 answers)
Closed 7 years ago.
i'm writing the following code and i'm getting the error 'identifier expected' on the line
private String class;
public class Records
{
private String name;
private String class;
private int cabinNumber;
public Records(String n, String c, int cn)
{
name = n;
class = c;
cabinNumber = cn;
}
public void setClass (String c){
class = c;
}
public void set cabinNumber (int cn){
cabinNumber = cn;
}
public String name(){
return name;
}
public String class(){
return class;
}
public int cabinNumber(){
return cabinNumber;
}
}
can someone please explain why this is happening and what I can do to fix it?
thank you!
class is a java keyword, you cannot have a variable with this name.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
having problem with null pointer exception and i read few article bout that error and still coundnt figure out what the problem.
The error happen at CompatibleActivity[topIndex]=new Activity(aNum,bNum,c);
topIndex=0 by the way.
Can anyone highlight the problem im having?
here my class
public class Schedulingtest {
public static void main (String[] args) throws IOException
{
Scanner fileScan;
fileScan=new Scanner(new File("data.txt"));
Schedule compatibility = new Schedule();
while(fileScan.hasNext())
{String url=fileScan.nextLine();
compatibility.addActivity(url);
}
}
public class Schedule{
import java.util.Scanner;
import java.util.Arrays;
public class Schedule {
Activity[] CompatibleActivity;
int totalTime=0,topIndex=0;
Scanner urlScan;
public Schedule(){
Activity[] CompatibleActivity=new Activity[30];
}
public int getTotalTime()
{return totalTime;
}
public void addActivity(String entry){
urlScan=new Scanner(entry);
urlScan.useDelimiter(" ");
String c=null;
int aNum = 0,bNum=0;
while(urlScan.hasNext())
{String a=urlScan.next();
String b=urlScan.next();
c=urlScan.next();
aNum=Integer.parseInt(a);
bNum=Integer.parseInt(b);
}
CompatibleActivity[topIndex]=new Activity(aNum,bNum,c);
topIndex++;
System.out.println("Activity added: start "+aNum+ " stop "+bNum+" "+c );
}
}
Activity Class
public class Activity {
private int start,stop,duration;
private String name;
public Activity(int Start,int Stop,String Name)
{
start=Start;
stop=Stop;
name=Name;
duration=Stop-Start;
}
public String getName()
{return name;
}
public int getStart()
{return start;
}
public int getStop()
{return stop;
}
public int getDuration()
{return duration;
}
public boolean compatible(int Start1,int Stop1,int toMatchsideStart,int toMatchsideStop)
{
int Start=Start1;
int Stop=Stop1;
int toMatchStart=toMatchsideStart;
int toMatchStop=toMatchsideStop;
if(toMatchStop<=Start)
{return true;
}
if(toMatchsideStart>=Stop)
{return true;
}
else
{return false;}
}
public String toString()
{return( name+"<"+start+","+stop+">"); }
}
Most likely you have CompatibleActivity declared in your class as
private Activity[] CompatibleActivity;
which declares a reference and initializes it to null by default. You need to assign it a real array with enough elements (e.g. in your constructor):
CompatibleActivity = new Activity[myBigNumber];
If the NullPointerException is definitely on that line, then it can only be caused by CompatibleActivity being null. You will need to find in your code where that Array Object is declared and make sure that it is also instantiated, e.g.
Activity[] CompatibleActivity = new Activity[size];
Check if you've initialized the array before you access one of its cells. You need an expression like
CompatibilityActivity = new Activity[1]; // or any other positve number if size is bigger
Activity[] CompatibleActivity = new Activity[size];
// put some element in it like
CompatibleActivity[0]=new CompatibleActivity();