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<>();
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:
What are Generics in Java? [closed]
(3 answers)
Closed 3 years ago.
im having a problem calling a method i created for a class when it is returned from a list. I get a "java.lang.Object cannot be converted to Thing"
error when running the following code
public class Test1
{
public static void main(String args[])
{
Thing whipersnaper = new Thing(30, "whipersnaper");
List storage = new List();
storage.insert(whipersnaper);
Thing x = storage.getItem(0);
x.doubleWeight();
System.out.println(x.getWeight());
}
}
here is the "Thing" class
public class Thing
{
private int weight;
private String name;
public Thing(int weight,String name){
this.weight = weight;
this.name = name;
}
public void doubleWeight(){
this.weight *= 2;
}
public int getWeight(){
return this.weight;
}
}
finally here is the List class
public class List
{
private Object[] itemList;
private int size;
public List()
{
this.itemList = new Object[10];
this.size = 0;
}
public void insert(Object item){
itemList[size] = item;
size++;
}
public Object getItem(int index){
return itemList[index];
}
}
i need the list to be able to hold objects of any type and not exclusively Thing objects.
i have tried to google a solution but I cant find a good way to phrase the question to get an answer. thanks in advance.
Change that line Thing x = storage.getItem(0); with Thing x = (Thing) storage.getItem(0);
Thing x = (Thing) storage.getItem(0);
I want to create a method which returns a Boolean value. It should return true if the sale is over 5 years old or older and false if the sale is under 5 years.
I have given it an attempt but I cannot seem to get it work. If anyone can think over a more efficient way of completing this I am open to a different direction.
I have tried the below but the method continue to error out no matter what I change. Google has not been helpful either as the method is so specific.
the method is called isSaleOld() (Go to the bottom of the code)
Thank you for any help in advance. Code is below for the whole project.
public class Sale
{
// instance variables
private String company;
private String yearBought;
private int saleValue;
private Seller seller;
public Sale(String aCompany, String aYear, int aValue,
Seller theSeller)
{
this.company = aCompany;
this.yearBought = aYear;
this.saleValue = aValue;
this.seller = theSeller;
}
public void setSellersName(String aName)
{
this.seller.setName(aName);
}
public void setSaleValue(int aValue)
{
this.saleValue = aValue;
}
public void setyearBought(String aYear)
{
this.yearBought = aYear;
}
public void setCompany(String aCompany)
{
this.company = aCompany;
}
public int getSaleValue()
{
return this.saleValue;
}
public boolean isApprovalRequired()
{
return this.getSaleValue() >=10000;
}
public String getYearBought()
{
return this.yearBought;
}
public void isSaleOld(String[] args)
{
yearBought = getYearBought("2020");
boolean after = yearBought.after(yearBought);
}
}
import java.time.LocalDateTime;
public class Sale {
private int yearBought;
public void sale(int year) {
setYearBought(year);
}
private int getYearBought() {
return this.yearBought;
}
private void setYearBought(int year) {
this.yearBought = year;
}
public boolean isSaleOld() {
int now = LocalDateTime.now().getYear();
int yearBought = getYearBought();
if (now - yearBought > 5) {
System.out.println("Yes, older than 5 years");
return true;
}
System.out.println("No, less than 5 years old");
return false;
}
public static void main(String[] args) {
Sale sale = new Sale();
Sale sale2 = new Sale();
sale.sale(2010);
sale2.sale(2020);
sale.isSaleOld();
sale2.isSaleOld();
}
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 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();