arraylist in self-designed class errors. please help me - java

This is my Class
1 // This class reads in integers and puts the values into a set
2
3 import java.util.ArrayList;
4 import java.util.*;
5
6 class Set {
7
8 private ArrayList<Integer> members;
9 private static int quantity = 0;
10
11 // Constructors
12 public Set() {
13 new ArrayList<Integer>();
7
8 private ArrayList<Integer> members;
9 private static int quantity = 0;
10
11 // Constructors
12 public Set() {
13 new ArrayList<Integer>();
14 }
15
16 public Set(int member){
17 new ArrayList<Integer>();
18 addMember(member);
19 quantity++;
20 }
21 // Accessors
22 public static int getQuantity() {
23 return quantity;
24 }
25
26 // Mutators
27 public void addMember(int member) {
28 members.add(member);
29 }
30 // toString() method
31 public String toString() {
32 int i;
33 String str = "[";
34 System.out.print("[");
35 for(i=0; i<getQuantity(); i++){
36 str += members.get(i);
37 if(i+1 == getQuantity())
38 str += "]";
39 else
40 System.out.print(", ");
41 str += ", ";
42 }
43 return str;
44 }
45
46 // Return true if 'this' is a subset of 'set',
47 // otherwise return false.
48 public boolean isSubset(Set set) {
49 if(this.members.contains(set))
50 return true;
51 else
52 return false;
53 }
54 // Return true if 'this' is equals to 'obj',
55 // Otherwise return false
56 public boolean equals(Set set) {
57 return (members.contains(set) && set.members.contains(this));
58 }
59 }
And this is my Test case.
1 // This program reads two sets of integers A and B, and determines
2 // if A is a subset of B, and if A is same as B.
3
4 import java.util.Scanner;
5 import java.util.ArrayList;
6
7 public class TestSet {
8
9 public static void main(String[] args) {
10 Scanner sc = new Scanner(System.in);
11 int i, setAnum, setBnum;
12
13 System.out.print("Enter number of elements in set A: ");
14 setAnum = sc.nextInt();
15 ArrayList<Integer> list1 = new ArrayList<Integer>();
16
17 System.out.print("Enter elements for set A: ");
18 for(i=0; i<setAnum; i++)
19 list1.add(sc.nextInt());
20
21 Set setA = new Set();
22 for(i=0; i<setAnum; i++)
23 setA.addMember(list1.get(i));
24
25 System.out.print("Enter number of elements in set A: ");
26 setBnum = sc.nextInt();
27 ArrayList<Integer> list2 = new ArrayList<Integer>();
28
29 System.out.print("Enter elements for set A: ");
30 for(i=0; i<setBnum; i++)
31 list2.add(sc.nextInt());
32
33 Set setB = new Set();
34 for(i=0; i<setAnum; i++)
35 setB.addMember(list2.get(i));
36
37 System.out.println("Set A: " + setA);
38 System.out.println("Set B: " + setB);
39
40 if (setA.isSubset(setB)) {
41 System.out.println("Set A is a subset of set B.");
42 }
43 else {
44 System.out.println("Set A is not a subset of set B.");
45 }
46 if (setA.equals(setB))
47 System.out.println("Set A is equal to set B.");
48 else
49 System.out.println("Set A is not equal to set B.");
50 }
51
52 }
I keep getting this error
Exception in thread "main" java.lang.NullPointerException
at Set.addMember(Set.java:28)
at TestSet.main(TestSet.java:23)
I can read and pinpoint where the problem is but I don't know what to correct it to. This is the first time I'm writing a user-defined class with an ArrayList inside. Previously I've only be writing classes with primitive data types. So I'm confused with a lot of things like what the constructors accessors and mutators are supposed to look like, when to use the 'this' reference. Someone answered and I inferred that if I'm using an arraylist here with the attribute 'members', I should use the reference to 'members' rather than 'this' because that's the attribute that I want to play around with. I know it's not a hard and fast rule but I sorta get the picture. Please help!!

The constructor:
public Set() {
new ArrayList<Integer>();
}
doesn't do anything. It just creates an object, and discards it. So the members instance variable is still null. Change the constructor to:
public Set() {
members = new ArrayList<Integer>();
}
And please choose a different name for your class. Set is already an interface in Java API.

Related

How can I print out 1-50 even numbers only, but the it start a new line every multiples of 10. (JAVA)

I'm a newbie, but I'm willing to learn how to code.
I tried using this code:
int n = 50;
int counter = 0;
System.out.print("Even Numbers from 1 to "+n+" are: ");
for (int i = 1; i <= n; i++) {
counter++;
if (counter == 2) {
System.out.println(i + " ");
counter = 0;
%10== 0
to find all even numbers between 1 to 50 and make a new line at multiples of 10 just follow these steps -
Make one loop which will go 1 to 50
Check if the number is even by checking the remainder after diving it with 2, if YES print that number.
Check if the number is a multiple of 10 by checking the remainder after dividing it by 10, if YES make a new line
The code will look something like this -
int i = 1;
while(i<=50){
if(i%2 == 0) System.out.print(i + " ");
if(i%10 == 0) System.out.println();
i++;
}
Output -
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
It's up to you which looping method you want to use for me While loop looks cleaner.
I hope this solves all your queries.
PFB Snippet:
public class Main
{
public static void main(String[] args) {
for(int i=1;i<=50;i++){
if (i%2 == 0) //Check whether number is even
{
System.out.print(i+" ");
if (i%10 == 0) // Check if it is multiple of 10
{
System.out.print("\n");
}
}
}
}
}
Output:
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
"\n" is a Escape Sequence which means new line

Need help figuring it out errors with my code

so I need help figuring it out why my code is not including the number 2 and it is including number 99 on the prime printed line. Do I need to change something on my findPrime()? I tried playing with the index and just got worse.
class Sieve {
private int max;
private boolean[] numbers;
public Sieve(int max) {
if (max < 2) {
throw new IllegalArgumentException();
}
this.max = max;
numbers = new boolean[max];
numbers[0] = false;
numbers[1] = false;
numbers[2] = true;
for (int i = 2; i < max-1; i++) {
numbers[i] = true;
}
}
public void findPrimes() {
for (int num = 2; num < max-1; num++) {
int multiples = num + num;
while (multiples < max-1) {
numbers[multiples-1] = false;
multiples += num;
}
}
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (int num = 2; num < max; num++) {
if (numbers[num]) {
builder.append(num+1).append(" ");
}
}
return builder.toString();
}
}
class Driver
{
// MAIN. Find some primes.
public static void main(String [] args)
{
Sieve sieve = null; // We must initialize SIEVE or Java will cry.
// 5 points. This must print "Sieve size must be at least 2." but without the
// quotes.
try
{
sieve = new Sieve(0);
}
catch (IllegalArgumentException oops)
{
System.out.println("Sieve size must be at least 2.");
}
// 5 points. This must print nothing.
try
{
sieve = new Sieve(100);
}
catch (IllegalArgumentException oops)
{
System.out.println("Sieve size must be at least 2.");
}
// 10 points. This must print integers from 2 to 99, separated by blanks.
System.out.println(sieve);
// 10 points. This must print the prime numbers between 2 and 99, separated by
// blanks. They are:
//
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
sieve.findPrimes();
System.out.println(sieve);
}
}
It is displaying this, instead of having the number 2 at the beginning and not having the number 99 at the last line of the program.
Sieve size must be at least 2.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 99
Your toString() method starts looping at num = 2 (which appends num+1 to the output). Your loop should start at 1.
public String toString() {
StringBuilder builder = new StringBuilder();
for (int num = 1; num < max; num++) { . // used to start at 2
if (numbers[num]) {
builder.append(num+1).append(" ");
}
}
return builder.toString();
}
}
Plus your code sets numbers[1] = false. That should be numbers[1] = true.
You are also looping until < max - 1. Consider looping until < max.
I made a few changes to your code the big things to point out is that you don't need max. Your findPrimes() looks ok but is difficult to read and hard to verify for correctness. Your toString() method should be iterating over every element and if that element is true append it to the list.
also 1 is not prime so numbers[1] = false; is as it should be. Why is 1 not a prime number?
class Sieve {
// private int max; // max is superfluous use numbers.length instead
private boolean[] numbers;
public Sieve(int max) {
if (max < 2) {
throw new IllegalArgumentException();
}
numbers = new boolean[max];
numbers[0] = false;
numbers[1] = false;
numbers[2] = true;
for (int i = 2; i <numbers.length; i++) {
numbers[i] = true;
}
}
public void findPrimes() {
// a bit more compact and neater in my opinion
for (int num=2; num<numbers.length; num++) {
for (int multiple=num+num; multiple<numbers.length; multiple+=num) {
numbers[multiple] = false;
}
}
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
// you should be iterating from 0 to 99
for (int i=0; i<numbers.length; i++) {
if (numbers[i]) {
builder.append(i).append(" ");
}
}
return builder.toString();
}
}
class Driver
{
// MAIN. Find some primes.
public static void main(String [] args)
{
Sieve sieve = null; // We must initialize SIEVE or Java will cry.
// 5 points. This must print "Sieve size must be at least 2." but without the
// quotes.
try
{
sieve = new Sieve(0);
}
catch (IllegalArgumentException oops)
{
System.out.println("Sieve size must be at least 2.");
}
// 5 points. This must print nothing.
try
{
sieve = new Sieve(100);
}
catch (IllegalArgumentException oops)
{
System.out.println("Sieve size must be at least 2.");
}
// 10 points. This must print integers from 2 to 99, separated by blanks.
System.out.println(sieve);
// 10 points. This must print the prime numbers between 2 and 99, separated by
// blanks. They are:
//
// 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
sieve.findPrimes();
System.out.println(sieve);
}
}

How to read first line of ints in a text file, use those numbers, then go to the second line and repeat until the end of the file

This is my main method. I am trying to read the first line of integers (5 4 3 7 8 4 3 1 3 ) from a text file. I want to then run those numbers through the methods i am calling in my main method. I then want to go to the next line in the text file (15 1 60 1 43 24 3), also run these numbers through the methods I am calling and so on until I reach the end of the text file. What is the best way to implement something like this? How I my code now will run through all of the integers in the text file and then run them through the method.
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
try
{
int num;
Scanner reader = new Scanner(new File("numbers.txt"));
while(reader.hasNextInt())
{
num = reader.nextInt();
if(tree.contains(num))
{
tree.remove(num);
}
else
{
tree.add(num);
}
}
reader.close();
tree.preorder(root);
System.out.println();
tree.inorder(root);
System.out.println();
tree.postorder(root);
System.out.println("\nTotal: " + tree.size(root));
System.out.println("Height: " + tree.height(root));
System.out.println("Max: " + tree.getMax(root));
System.out.println("Min: " + tree.getMin(root));
}
catch(IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
This is the text file that I want to use called numbers.txt
5 4 3 7 8 4 3 1 3
15 1 60 1 43 24 3
25 28 71 18 48 35 97
6 41 24 40 85 2 92 72 86 59 7 40
76 19 23 40 84 6 67 41 34 66 79 11 38 5 61 60 64 5
81 8 30 80 88 38 90 55 37 45 70 32 41 26
I would try something more like this:
public static void main(String[] args) throws Exception {
Scanner reader = new Scanner(new File("numbers.txt"));
while (reader.hasNextLine()) {
String[] temp = reader.nextLine().split("\\s+"); // Regex for any and all whitespace used as a delimiter
for (int x = 0; x < temp.length; x++) {
// Iterate through each element in the string array temp
}
// Resume while loop.
}
}

How to print nth number series in java

Could anyone please help me to print below series in java . I am trying to use below code but it seems not working correctly.
Desired output:
9 18 27 36 45
9 18 27 36
9 18 27
9 18
9
My code :
public class NumberSet {
public static void main (String args[])
{
int i = 0, j=0;
for (j=1;j<=5;j++)
{
for (i=1;i<=50;i++)
{
if (i%9 ==0)
{
System.out.print(" " + i + " ");
}
}
System.out.println();
}
}
}
Output of my code:
9 18 27 36 45
9 18 27 36 45
9 18 27 36 45
9 18 27 36 45
9 18 27 36 45
Thanks for your help in Advance.
Arfater
First, you can generate multiplies of 9 more efficiently by multiplying by 9 than by looping over all numbers and checking if they are divisible by 9.
Second, you can simply change the order of the outer loop, and make the inner loop variable depend on the outer loop variety to get different behavior for every iteration of the outer loop.
public class NumberSet {
public static void main (String args[])
{
int i,j;
for (j=5;j>=1;j--)
{
for (i=1;i<=j;i++)
{
System.out.print(" " + i*9 + " ");
}
System.out.println();
}
}
}
Output:
9 18 27 36 45
9 18 27 36
9 18 27
9 18
9
Try this:
public class NumberSet {
public static void main (String args[])
{
int i = 0, j=0, mul= 1;
for (j=5;j>=1;j--)
{
mul = 1;
for (i=1;i<=j;i++)
{
System.out.print(" " + mul++ * 9 + " ");
}
System.out.println();
}
}
}
Hope this helps u...
Try this:
enter code here
public class Myclass {
public static void main(String args[])
{
int num = 5;
for (int i = 0; i < 5; i++, num--)
{
for (int j = 1; j <= num; j++ )
{
System.out.print(9*j + " ");
}
System.out.println();
}
}
}

Attempting to call an array and setting the value from a text file

This class here is creating a student object:
public class Student {
String firstName;
String lastName;
int assignmentScores[];
int labScores[];
int attendanceScore;
int totalHomeworkScore;
int midterm1;
int midterm2;
int finalExam;
int zyanteScore;
int patScore;
int totalTestScore;
String letterGrade;
public Student() {
}
public void setFirstName(String fName) {
firstName = fName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lName) {
lastName = lName;
}
public String getLastName() {
return lastName;
}
public void setAssignmentScores(int[] assignmentScore) {
assignmentScores = assignmentScore;
}
public int[] getAssignmentScores() {
return assignmentScores;
}
public void setLabScores(int[] labScore) {
assignmentScores = labScore;
}
public int[] getLabScores() {
return labScores;
}
public void setAttendanceScore(int attenScore) {
attendanceScore = attenScore;
}
public int getAttendanceScore() {
return attendanceScore;
}
public void setTotalHomeworkScore(int hScore) {
totalHomeworkScore = hScore;
}
public int getTotalHomeworkScore() {
return totalHomeworkScore;
}
public void setMidTerm1(int mT1) {
midterm1 = mT1;
}
public int getMidterm1() {
return midterm1;
}
public void setMidterm2(int mT2) {
midterm2 = mT2;
}
public int getMidterm2() {
return midterm2;
}
public void setFinalExam(int fExam) {
finalExam = fExam;
}
public int getFinalExam() {
return finalExam;
}
public void setZyanteScore(int zyant) {
zyanteScore = zyant;
}
public int getZyanteScore() {
return zyanteScore;
}
public void setPatScore(int pat) {
patScore = pat;
}
public int getPatScore() {
return patScore;
}
public void setTotalTestScore(int tScore) {
totalTestScore = tScore;
}
public int getTotalTestScore() {
return totalTestScore;
}
public void computeGrade() {
if (getTotalHomeworkScore() <= 599 || getTotalTestScore() <= 149
|| getTotalHomeworkScore() <= 719 && getTotalTestScore() <= 179
|| getTotalHomeworkScore() <= 779 && getTotalTestScore() <= 164
|| getTotalHomeworkScore() <= 659 && getTotalTestScore() <= 209) {
letterGrade = "P";
}
if (getTotalHomeworkScore() >= 1140 && getTotalTestScore() >= 180
|| getTotalHomeworkScore() >= 1080
&& getTotalTestScore() >= 195 || getTotalHomeworkScore() >= 960
&& getTotalTestScore() >= 210 || getTotalHomeworkScore() >= 900
&& getTotalTestScore() >= 225 || getTotalHomeworkScore() >= 840
&& getTotalTestScore() >= 240 || getTotalHomeworkScore() >= 780
&& getTotalTestScore() >= 255 || getTotalHomeworkScore() >= 720
&& getTotalTestScore() >= 285) {
letterGrade = "G";
} else {
letterGrade = "A";
}
}
public String getGrade() {
return letterGrade;
}
}
This class creates a student object, with values to be set from a text file. This next class creates an array of these student objects, as well as a few other things that aren't important at the moment. The important method right now is the setStudents method, which is creates the array of student objects:
public class CourseOffering {
Student[] students;
String description;
double homeworkAverage;
double testAverage;
int passingStudents;
public CourseOffering() {
}
public void setStudents(Student[] studentArray) {
students = studentArray;
}
public void setDescription(String descript) {
description = descript;
}
public String getDescription() {
return description;
}
public double computeHomeworkAverage() {
int temp = 0;
for (int i = 0; i < students.length; i++) {
temp += students[i].getTotalHomeworkScore();
}
homeworkAverage = temp / students.length;
return homeworkAverage;
}
public double computeTestAverage() {
int temp = 0;
for (int j = 0; j < students.length; j++) {
temp += students[j].getTotalTestScore();
}
testAverage = temp / students.length;
return testAverage;
}
public int countPassingStudents() {
int temp = 0;
for (int k = 0; k < students.length; k++) {
if (students[k].getGrade() == "G") {
temp++;
}
}
passingStudents = temp;
return passingStudents;
}
}
Finally, this class is the driver that is running the entire thing:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CourseStatistics {
static int numberOfClasses = 0;
static int numberOfStudents = 0;
public static void main(String[] args) {
Student myStudent = new Student();
CourseOffering myCourseOffering = new CourseOffering();
Scanner scanner = new Scanner(System.in);
try {
scanner = new Scanner(new File("gradesA5.txt"));
} catch (FileNotFoundException e) {
System.out
.println("Error opening file. Please make sure that you have a grades.txt file in the same folder as GradeCalculator.class");
System.exit(0);
}
numberOfClasses = scanner.nextInt();
System.out.println(numberOfClasses);
myCourseOffering.setDescription(scanner.next()); // CSCE
myCourseOffering.setDescription(scanner.next()); // 155A
myCourseOffering.setDescription(scanner.next()); // -
myCourseOffering.setDescription(scanner.next()); // Reads Semester
System.out.print(myCourseOffering.getDescription() + " "); // Prints
// Semester
myCourseOffering.setDescription(scanner.next()); // Reads Year
System.out.println(myCourseOffering.getDescription()); // Prints Year
numberOfStudents = scanner.nextInt(); // Number Of Students
System.out.println(numberOfStudents); // Prints number of students
System.out.println("Name" + "\t" + "\t" + "Assignment Score" + "\t"
+ "Test Score" + "\t" + "Grade");
myCourseOffering.students[0].setFirstName(scanner.next());
System.out.println(myCourseOffering.students[0].getFirstName());
// for (int i = 0; i < numberOfClasses; i++) {
// }
}
}
Ok, now the part I am having difficulties with. This piece of code is where I am attempting to call the first index on the student object array and setting the .firstName value from reading the text file:
myCourseOffering.students[0].setFirstName(scanner.next());
System.out.println(myCourseOffering.students[0].getFirstName());
But I keep the null pointer exception. The exception points to myCourseOffering.students[0].setFirstName(scanner.next()); as the problem line, but I am not sure what the problem is. This is the text file I am attempting to read:
3
CSCE 155A - Fall 2011
4
Anthony Hopkins 80 90 95 87 80 78 25 17 20 22 21 24 19 22 21 23 24 21 20 25 20 55 56 110 30 20 25 8
John Smith 99 95 82 72 64 52 15 14 11 21 25 12 19 20 21 23 21 12 12 10 15 50 50 60 25 15 20 9
Pan Mei 85 92 72 45 82 78 22 13 16 22 24 10 18 12 21 24 25 10 11 14 20 58 51 95 28 14 28 7
Rafael Vega 99 45 87 52 87 99 25 25 21 21 14 19 19 25 25 20 20 18 20 24 20 60 60 60 25 16 23 8
CSCE 155A - Spring 2012
1
Paul Kubi 80 90 5 87 80 0 25 0 20 22 21 24 19 22 21 0 24 21 20 25 20 0 0 0 30 20 25 8
CSCE 155A - Fall 2012
3
Tianna Delp 99 99 99 99 99 99 24 15 16 21 25 15 19 20 21 22 21 21 23 15 15 60 50 60 20 17 20 9
Taylor Delp 95 92 80 90 82 78 25 25 25 25 24 10 25 25 25 25 25 25 25 25 25 58 51 95 28 14 28 7
Rachel Valenz 99 45 87 52 87 99 25 25 21 21 14 19 19 25 25 20 20 18 20 24 20 60 60 60 25 16 23 8
The reason is that when declare myCourseOffering
CourseOffering myCourseOffering = new CourseOffering();
You are initializing the myCourseOffering class object, but the member Student[] students never gets initialized and remains null.
public class CourseOffering {
Student[] students; // never initialized, hence NULL
String description;
double homeworkAverage;
Thus initialize it (and other members to avoid future errors), preferably inside the constructor
public class CourseOffering {
Student[] students;
String description;
double homeworkAverage;
double testAverage;
int passingStudents;
public CourseOffering() {
this.students = new Student[100];
this.description = "";
this.homeworkAverage = 0.0;
this.testAverage = 0.0;
this.passingStudents = 0;
}
or you can initialize it outside in the main method like this
myCourseOffering.students = new Student[numberOfStudents];
The value myCourseOffering.students is null because you haven't initialized the array. An array in Java has to be initialized, as well as every instance in the array.
An array is instantiated using new and a specific size for the array - it looks like the number of students is provided on the previous line, so you'll want to read that and use it to instantiate:
myCourseOffering.students = new Student[10];
Also, you will want to initialize each entry, probably in some sort of loop:
for (int i = 0; i < number of students; i++) {
myCourseOffering.students[i] = new Student();
// populate properties of Student
}

Categories