I want to create an object named "Course", and get the information from the keyboard. The last attribute called the "pre", which means the prerequisite courses of this course. I want to input the whole information in one line and extract the information for each attribute. But I got the problem with"pre". I run the program and the output of course.pre is null. I do not know why. Here is my Course class code:
`import java.util.HashSet;
public class Course{
private String name;
private int isFall;
private int NumPre;
private HashSet<Course> pre;
public Course(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String setName (String n){
return name = n;
}
// 1 - fall 0 - both -1 - spring
public void setType(String isFall) {
if(isFall.equals("F") || isFall.equals("f")){
this.isFall = 1;
}else if(isFall.equals("S") || isFall.equals("s")){
this.isFall = -1;
}else if(isFall.equals("B") || isFall.equals("b")){
this.isFall = 0;
}
}
public int getType(){
return isFall;
}
public void SetNumPre(int n) {
this.NumPre = n;
}
public int getNumPre() {
return NumPre;
}
public void addPre(Course c) {
pre.add(c);
}
public HashSet<Course> getPre() {
return pre;
}
}
`
And here is my main method here:
import java.util.*;
public class TimeToGraduate {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
//System.out.print("Input first two integers here: ");
String globalInfo = scanner.nextLine();
String[] numOfCourse = globalInfo.split(" ");//[0] num of total course [1] max num per semester
int totalNum = Integer.parseInt(numOfCourse[0]);
int maxPre = Integer.parseInt(numOfCourse[1]);
Course courses[] = new Course[totalNum];
//System.out.print("Please input course list here: ");
String coursesList = scanner.nextLine();
String[] nameOfCourse = coursesList.split(" ");
for(int i = 0;i < totalNum; i++){
courses[i] = new Course(nameOfCourse[i]);
}
//System.out.print("Please input course info here: ");
for(int i = 0;i < totalNum; i++){
String courseInfo = scanner.nextLine();
String[] infoOfCourse = courseInfo.split(" ");
courses[i].setName(infoOfCourse[0]);
courses[i].setType(infoOfCourse[1]);
courses[i].SetNumPre(Integer.parseInt(infoOfCourse[2]));
if(courses[i].getNumPre() > 0){
for(int j = 3; j < 3+(courses[i].getNumPre()); j++){
for(int k = 0; k < totalNum; k++){
if(infoOfCourse[j] == courses[k].getName()){
courses[i].addPre(courses[k]);
}
}
}
}
}
scanner.close();
for(int m = 0; m < totalNum; m++){
System.out.print(courses[m].getName()+" ");
System.out.print(courses[m].getType()+" ");
System.out.print(courses[m].getNumPre()+" ");
System.out.print(courses[m].getPre()+" ");
System.out.println();
}
}
}
Notice that you did not initilize the pre attribute. That is why it is null.
It would be a good practise if you initilize the pre inside a constructor for the Course class. Otherwise, do it when you start filling the Course attributes.
Update:
Your constructor should be like this:
public Course() { this.pre = new HashSet()}
As you can see the constructor does not have any arguements, because you will be filling its attribute from the main function.
You can define a constructor with arguments too:
public Course(String name, HashSet<Course> pre)
{ this.name = name; this.pre = pre; }
But you will need to initilize pre and name when you call it from the main:
...
HashSet hs = new HashSet();
course[i] = new Course('course_name', hs);
....
Related
This question already has answers here:
Why do I have NullPointerException in my sort implementation?
(3 answers)
Closed 6 years ago.
Trying to sort an array of objects by overallVisits from greatest to smallest but get an error. The goal is to pass in website objects to the array then have them sorted out according to greatest overall visit to least visit.
I get the following error:
Exception in thread "main" java.lang.NullPointerException at java.util.ComparableTimSort.binarySort(ComparableTimSort.java:258)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:185)
at java.util.Arrays.sort(Arrays.java:1246)
at Project1.main(Project1.java:32)
import java.util.Scanner;
import java.util.Arrays;
public class Project1
{
public static void main (String args[])
{
Scanner input = new Scanner(System.in);
Website [] websites = new Website[20];
String temp;
String temp2;
int days = 4;
for(int i=0; i < 10; i++)
{
System.out.println("Enter the URL of the Website:");
temp = input.nextLine();
websites[i] = new Website();
websites[i].setUrl(temp);
System.out.println("Enter the name of the Website:");
temp2 = input.nextLine();
websites[i].setName(temp2);
}
Arrays.sort(websites);
for(int i = 0; i<10; i++)
{
System.out.println("URL:" + websites[i].getUrl()+ " Current Visits:" + websites[i].getCurvisit() + " Overall Visits:" + websites[i].getOvrvisit());
System.out.println("Name of Website:" + websites[i].getName());
}
}
}
//Class 2:
import java.util.Scanner;
import java.util.Random;
public class Website implements Comparable <Website>
{
private String url;
private String name;
private int currentVisit;
private int overallVisit;
public Website()
{
this.url = url;
this.name = name;
this.currentVisit = getRandom1();
this.overallVisit = getRandom2();
}
public String getUrl()
{
return url;
}
public void setUrl(String s)
{
url = s;
}
public String getName()
{
return name;
}
public void setName(String n)
{
name = n;
}
public int getRandom1()
{
Random rand = new Random();
int num = rand.nextInt(4);
return num;
}
public int getRandom2()
{
Random rand = new Random();
int num2 = 10 + rand.nextInt(11);
return num2;
}
public int getCurvisit()
{
return currentVisit;
}
public int getOvrvisit()
{
return overallVisit;
}
public int compareTo(Website compareVisit)
{
int compareAll = ((Website) compareVisit).getOvrvisit();
return compareAll - this.overallVisit;
}
}
You're getting a java.lang.NullPointerException because you have allocated 20 elements in your array but have only filled it with 10.
New Array
Website [] websites = new Website[20];
Filling the array
for(int i=0; i < 10; i++)
I'm working on a program where I'm inputting values(String and int) into arrays, putting those values into an objects which go into an array list to be sorted by the the int value. When I run the program though, it prints out:
Sorted List Entries:
Item Name:null---Quant:0
Item Name:null---Quant:0
Item Name:null---Quant:0 //etc..
I'm trying to learn on my own here but I'm not sure what to do.
My main class:
import java.io.*;
import java.util.*;
public class InputItem
{
public static void main(String args[])
{
String again;
String names[] = new String[100];
int quant[] = new int[100];
int row=0;
do{
System.out.println("Please input assignment name:");
Scanner newName = new Scanner(System.in);
String name = newNamet.next();
names[row] =name;
System.out.println("Please input assignment quant:");
Scanner quantI = new Scanner(System.in);
int quantity = quantI.nextInt();
quant[row] = quantity;
System.out.println("Would you like to add another item? Enter 'Yes' or 'No'");
Scanner input = new Scanner(System.in);
again = input.next();
row++;
}
while(again.equalsIgnoreCase("Yes"));
List<Items> work = new ArrayList<Items>();
for(int count = 0; count<row; count++)
{
work.add(new Items((names[row]),(quant[row])));
}
Collections.sort(work, new MyComp());
System.out.println("Sorted List Entries: ");
for(Items e:work)
{
System.out.println(e);
}
}
}
Class with Comparator:
import java.util.*;
class MyComp implements Comparator<Items>
{
#Override
public int compare(Items e1, Items e2)
{
if((e1).getQuant()< (e2).getQuant())
{
return 1;
}
else
{
return -1;
}
}
}
public class Items
{
private String name;
private int quant;
public Items(String n, int q)
{
this.name = n;
this.quant = q;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getQuant()
{
return quant;
}
public void setQuant(int quant)
{
this.quant = quant;
}
public String toString()
{
return "Item Name:" + this.name+"---Quant:" +this.quant;
}
}
The problem is here...
for (int count = 0; count < row; count++) {
work.add(new Items((names[row]), (quant[row])));
}
You're using row, which was defined in the previous section of code to keep track of which element you were updating, but is now pointing to the next element in the array (or an empty element). This basically means you are constantly adding the same (empty) values to your Items
Instead, you should be using count
for (int count = 0; count < row; count++) {
work.add(new Items((names[count]), (quant[count])));
}
I'm currently trying to iterate through an ArrayList and see if it contains the following numbers I input into the winners array. However, the ticket object won't allow me to utilize the .contains() method which is where I'm getting the error. Any idea on how to work around this?
int[] winners = new int[6];
for(int i = 0; i < winners.length; i++)
{
winners[i] = in.nextInt();
}
in.close();
Scanner scan = new Scanner(file);
ArrayList<Ticket> info = new ArrayList<Ticket>();
for(int i = 0; i < lim; i++)
{
String name = scan.nextLine();
String num = scan.nextLine();
String[] t = num.split(" ");
int[] tichold = new int[t.length];
for(int j = 0; j < t.length; j++)
{
tichold[j] = Integer.parseInt(t[j]);
}
Ticket ticket = new Ticket(name, tichold);
info.add(ticket);
}
**for(Ticket t : info)
{
if(t.contains(winners))
{
System.out.println("Yes");
}
}**
scan.close();
}
**public static class Ticket
{
public String name;
public int[] tarray;
public Ticket(String name, int[] tarray)
{
this.name = name;
this.tarray = tarray;
}**
You can't use a method that doesn't exist for that class. Since you don't have contains defined for Ticket, I'm not surprised that it isn't working.
From inference, winners is an int[]. In that case, you'd define a new method contains inside of Ticket.
public boolean contains(int[] winningNumbers) {
// logic here
}
Depending on how the winning numbers for a given ticket are stored, and given how you define different conditions of winning, you'd handle your logic here.
If they're stored as an array and you want an exact match, then you can use Arrays.equals for that.
public boolean contains(int[] winningNumbers) {
return Arrays.equals(numbers, winningNumbers);
}
Try this Ticket class with and added contains method:
public class Ticket {
public String name;
public int[] tarray;
public Ticket(String name, int[] tarray)
{
this.name = name;
this.tarray = tarray;
}
public boolean contains(int[] winners) {
for (int i = 0; i < winners.length; i++) {
for (int j = 0; j < tarray.length; j++) {
if (winners[i] == tarray[j])
return true;
}
}
return false;
}
}
Is it possible to do such a thing? Say I wanted to add the values I gave values to in CountriesTest and add them to the ArrayList in Countries. Also how could I reference aCountries to print for option 2, seeing that I created it inside option 1 I can't access it anywhere else.
Here is my interface
public interface CountriesInterface
{
public String largestPop();
public String largestArea();
public String popDensity();
}
Here is the Countries class
import java.util.*;
public class Countries implements CountriesInterface
{
private final List<CountriesInterface> theCountries = new ArrayList<>();
private String cName;
private String finalPopName;
private String finalAreaName;
private String finalDensityName;
private int cPop = 0;
private int cArea = 0;
private int popDensity = 0;
private int popCounter = 0;
private int areaCounter = 0;
private int densityCounter = 0;
public Countries(String cName, int cPop, int cArea, int popDensity)
{
this.cName = cName;
this.cPop = cPop;
this.cArea = cArea;
this.popDensity = popDensity;
}
public String largestPop()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(cPop > popCounter)
{
popCounter = cPop;
finalPopName = cName;
}
}
return finalPopName;
}
public String largestArea()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(cArea > areaCounter)
{
areaCounter = cArea;
finalAreaName = cName;
}
}
return finalAreaName;
}
public String popDensity()
{
for(int i = 0; i < theCountries.size(); i++)
{
if(popDensity > densityCounter)
{
densityCounter = popDensity;
finalDensityName = cName;
}
}
return finalDensityName;
}
}
Here is the CountriesTest class
import java.util.*;
public class CountriesTest
{
public static void main(String[] args)
{
int population = 0;
int area = 0;
int density = 0;
Scanner myScanner = new Scanner(System.in);
boolean done = false;
do
{
System.out.println("1. Enter a country \n2. Print countries with the largest population, area, and population density \n3. Exit");
int choice = Integer.parseInt(myScanner.nextLine());
if (choice == 1)
{
System.out.print("Enter name of country: ");
String input1 = myScanner.nextLine();
System.out.print("Enter area of country in square kilometers: ");
String input2 = myScanner.nextLine();
population = Integer.parseInt(input2);
System.out.print("Enter population of country: ");
String input3 = myScanner.nextLine();
area = Integer.parseInt(input3);
density = population/area;
Countries aCountries = new Countries(input1, population, area, density);
}
else if(choice == 2)
{
System.out.println("The country with the largest population: " );
System.out.println("The country with the largest area: " );
System.out.println("The country with the largest population density is: " );
}
else if(choice == 3)
{
done = true;
}
else
System.out.println("Invalid Choice");
}
while (!done);
System.exit(0);
}
}
OK, there's some mix-up in your code.
You are using the "Countries" class at the same time for an individual Country AND the list of countries. I won't recommand it, but at least you should make "static" members and methods which are for the list of countries. Or you could declare List theCountries = new ArrayList<>(); inside the main method instead.
You are never adding the new "Countries" object to the list of countries. So, if you've declared theCountries in the main method, just uste "theCountries.add(aCountries)" right after the "new Countries(...)".
your seach methods (like largestPop) won't work because they are never searching through the content of the "theCountries" ArrayList. (the "i" variable is just iterating through the indices, but never actually used to get a countent from this ArrayList).
and btw, System.exit(0) is not needed (it's implied)
The point is to write a program that finds an employee by searching by their id number, and by printing out all the information of all the employees and by printing out the information of a single employee. I need help with that (the search) and if printing a single employee alone is correct? Thanks!
Class Employee code:
public class Employee {
private String name;
private int id;
private int salary;
private boolean bonus;
public Employee(String n, int i, int s, boolean b) {
name = n;
id = i;
salary = s;
bonus = b;
}
public void computeSalary(int s, boolean b) {
if (b == true)
salary += 2000;
}
public void printInfo() {
System.out.print("Name: "+name+" ID: "+id+" Salary: "+salary+" Bonus: "+bonus+" ");
}
Class EmployeeApp class code:
import java.util.Scanner;
public class EmployeeApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the name: ");
String n = in.nextLine();
System.out.print("Enter the ID: ");
int g = in.nextInt();
System.out.print("Enter the salary: ");
int s = in.nextInt(); in.nextLine();
System.out.print("true or false for bonus? ");
boolean b = in.nextBoolean();
Employee e = new Employee(n, g, s, b);
e.computeSalary(s, b);
e.printInfo();
}
}
public class Company{
private Employee[] e = new Employee[4];
public void printAllEmployees() {
for(int i = 0; i < e.length; i++)
e[i].printInfo();
}
public Employee searchEmployee(int i) {
Employee temp = null;
for (int j = 0; j < e.length; j++) {
if (Employee.id == i)
temp = Employee;
}
return temp;
}
public void printAnEmployee(Employee e) {
e.printInfo();
}
}
put employees in a structure that will enable simple searching latter, like the following:
private Map<Integer, Employee> e = new HashMap<Integer, Employee>();
public void printAllEmployees() {
for( Integer key : e.keySet() )
System.out.println(e.get( key ));
}
public Employee searchEmployee(int i) {
return e.get(i);
}
I do not know how the code that you gave us works for even for an user because you have a minor issues in your classes.
First, it is a good practice to have setter and getter in your Employee because for safety is good to encapsulate a object , so how to construct them plz refer to this tutorial
http://www.tutorialspoint.com/java/java_encapsulation.htm
Second, in your EmployeeApp class
when you ask this
System.out.print("true or false for bonus? ");
boolean b = in.nextBoolean();
is not clear what kind of input user has to enter, so it is good to change first line to
System.out.print("true or false for bonus? \nplease enter true or false");
Third, it is good to put your company class in different file, and some minor issue in your Company class as follow
Note: Employee is a class and e is an array with Employee type
public Employee searchEmployee(int i) {
Employee temp = null;
for (int j = 0; j < e.length; j++) {
if (**Employee.id** == i)
**temp = Employee;**
}
return temp;
}
change to
public Employee searchEmployee(int i) {
Employee temp = null;
for (int j = 0; j < e.length; j++) {
if (e[i].getId() == i) {
temp = e[i];
}
}
return temp;
}
At the end, if you need to add more employee, you need to put it in a while loop. Hence, while loop is going to be ok till for example an user push X.