changing fields in Array of objects in java - java

**this is part of the class i created
class Student{
private String name;
private float avGrade;
private float outstandingGrade = 82.0f;
public Student() { }
public Student(String Name, float avg) {
name = Name;
avGrade = avg;
}
public String getName() {
return name;
}
public void setName(String Name) {
name = Name;
}
}
and this is the main and another method in it :
public static void main(String[] args) {
Student[][] school = CreateStudentMat();
school[0][0].setName("Student");
}
public static Student[][] CreateStudentMat(){
Scanner input = new Scanner(System.in);
System.out.println("Please enter number of classes in school: ");
int NumClasses = input.nextInt();
Student[][] matrix = new Student[NumClasses][];
for(int i = 0; i<matrix.length; i++){
System.out.println("Please enter number of students in class " +(i+1));
matrix[i] = new Student[input.nextInt()];
}
return matrix;
}
when i am trying to change name of the object at [0][0]
with school[0][0].setName("Student");
i get an error
Exception in thread "main" java.lang.NullPointerException
at Homework3.main(Homework3.java:13)
what i did wrong here?

you are instantiating the two dimensional array with matrix = new Student[NumClasses][]
you are instantiating the N one dimensional arrays with matrix[i] = new Student[input.nextInt()]
you are NOT instantiating every single student with matrix[i][j] = new Student()
Hence the two dimensional array is correctly created but every student reference is still null since you are not instantiating any.

There are no student objects. you never called new Student() anywhere. Since array does not have any object, you can't call methods on nulls.

Maybe the problem exist at:
Student[][] matrix = new Student[NumClasses][];
try to initialize the size of the second dimension of your array.

Related

How to ensure two players or more inputted player names in an arraylist are not the same (java)

Hello in my monopoly game i need to make sure no inputted player names are the same to avoid confusion using an arraylist in java any way how to do it so only one player can have one name
public class Player {
private ArrayList<Property> properties = new ArrayList<Property>();
private final String name;
private int position;
private int money = 0;
public boolean inJail = false;
public int outOfJailCards = 0;
public int turnsInJail = 0;
public Player(String name){
this.name = name;
position = 0;
}
public String getName() {
return name;
}
// in monopoly.java
static ArrayList<Player> createPlayers(int numPlayers){
ArrayList<Player> players = new ArrayList<>();
for(int i = 1; i <= numPlayers; i++){
System.out.print("Player " + i + " name: ");
players.add(new Player(Input.read()));
}
return players;
}
}
import java.util.List;
import java.util.Scanner;
public class Input {
public static String read(){
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
Instead of directly adding the player to the array list, check with .contains() first. If not, ask for re-input. You will not be able to do this directly with a for loop, you will need to restructure your code.
PS: This sounds very much like homework in a programming course.
you can save the input from the user into a variable and check if the name already exists in the list:
String input = Input.read();
if(!list.stream().findAny(s -> s.getName().equals(input)).isPresent()({
players.add(new Player(input));
}
Stream API were used to check if name already exists in the list, but you could also use the .contains method, but first you need to override the equals method in your Player class.

How can I declare an array in one function and use that same array in another function?

Here is my code
class Employee{
private String Animal;
private int Quantity;
Employee(String Animal, int Quantity){
this.Animal=Animal;
this.Quantity=Quantity;
public String getAnimal{
return animal;
}
public void setAnimal{
this.Animal=Animal;
}
public String getQuantity{
return Quantity;
}
public void setQuantity{
this.Quantity=Quantity;
}
public static void Input(){
Scanner sc = new Scanner(System.in);
int n = 0;
Employee[] list = new Employee[20];
list[no] = new Employee(" ", 0);
String nameOfAnimal = sc.nextLine();
list[n].setAnimal(nameOfAnimal);
String numberOfAnimal = sc.nextLine();
list[n].setQuantity(numberOfAnimal);
++n;
}
public static void Output(){
...
for(int i=0; i<n; ++i){
System.out.println(" -" + list[i].getAnimal + " - " + list[i].getQuantity);
}
}
}
In the Output method, I dot 3 points because I don't know how to get the array declared in the Input method and print its content within the Output method. It always shows an error that the first element is null when I create the same array in the Output function. Concisely, how can I keep an array that both functions can be used?

Returning and displaying contents of ArrayList in different class?

I'm working on a project where I will tally a Student's choices and add them to a count array (still working on this part). For now, I'm trying to retrieve the choices that have been sent and added to a Student ArrayList in my Student class.
Student class:
public class Students {
private String name;
private ArrayList<Integer> choices = new ArrayList<Integer>();
public Students(){
name = " ";
}
public Students(String Name){
name = Name;
}
public void setName(String Name){
name = Name;
}
public String getName(){
return name;
}
public void addChoices(int Choices){
choices.add(Choices);
}
public ArrayList<Integer> getChoices(){
return choices;
}
Here is my main driver class:
public class P1Driver {
public static void main(String[] args) throws IOException{
ArrayList<Students> students = new ArrayList<Students>();
String[] choices = new String[100];
int[] count;
Scanner scan1 = new Scanner(new File("Choices.txt"));
Scanner scan2 = new Scanner(new File("EitherOr.csv"));
// Scan the first file.
int choicesIndex = 0;
while(scan1.hasNextLine()){
String line = scan1.nextLine();
choices[choicesIndex] = line;
choicesIndex++;
}
scan1.close();
// Scan the second file.
int studentIndex = 0;
while(scan2.hasNextLine()){
String line = scan2.nextLine();
String [] splits = line.split(",");
students.add(new Students(splits[0]));
for(int i = 1; i < splits.length; i++){
students.get(studentIndex).addChoices(Integer.parseInt(splits[i]));
}
studentIndex++;
}
scan2.close();
// Instantiate and add to the count array.
int countIndex = 0;
for(int i = 0; i < students.size(); i++){
if(students.get(i).getChoices(i) == -1){
}
}
The last part is where I am now. It's nowhere near done obviously (I'm right in the middle of it) but during my construction of a for loop to get the choices from the students, I'm getting an error that says, "The method getChoices() in the type Students is not applicable for the arguments (int)." Can someone explain what this means, where me error is, and possibly how to fix it? Thanks all.
getChoices(int i) is not a method you've defined.
if(students.get(i).getChoices(i) == -1){
}
getChoices() returns a list, so you can just use the get method on the list:
if(students.get(i).getChoices().get(i) == -1){
}
Alternatively, make a getChoice method:
public Integer getChoice(int i){
return choices.get(i);
}
Have you tried getChoices()[i] instead of getChoices(i)

Insert two arrays in one using two methods for each array

i want to create 3 arrays with objects.The two arrays(pin and age) i want to put them on one array named Alltogether.I use from each method to return me an array i dont know if this is right i try it.In the end i want to systemout only the array that has all this.
package worklin1;
public class worklin1{
static int N; //from keyboard i have a class userinput
private String Name; // name
private int age; // age
private int costVehicle; //vehicle
public worklin1(){}
public worklin1(String Name, int Age, int cost, String name) {
Name=name;
Age=age;
costVehicle=cost;
}
// Access methods
public String getName(){
return Name;
}
public int getAge(){
return age;
}
public int getcostVehicle(){
return costVehicle;
}
// Mutator methods
public void setName(String name){
Name=name;
}
public void setSurname(String age){
age=age;
}
public void setcostVehicle(int cost){
costVehicle=cost;
}
public String toString() {
String s=name+" "+age+", "+cost+"\t";
return s;
}
public static void main(String[] args){ //main
int[] pin= new int[N]; // the first array
int[] age=new int[]; // the second array.i dont know why it is false this array maybe i use an object as name for an array thats why its false.
Allmethodtogether[] pin = new Allmethodtogether[N]; // Allmethodotogether is an array.It has the combination of age and the cost.The N is just a number i give from keyboard i dont care about this right now.I just wanted to focus on my problem which is how to combine the two methods(which they give me each one 2 arrays and i will add them in this array name Allmethodtogether).
for (int i = 0; i < 10; i++) { // i want to put in an array all the arrays from the methods so i start the counting from 0 until 10.Until the 10 will be saved the pin and after 10 will be saving the array age
Allmethodtogether[i] = new Vehcost();
Allmethodtogether[i+10] = new AllAge();
} //finished //Now i want to display those arrays and i am trying this .
int y; // i create a variable to save my results from the method
y=worklin1.Vehcost(int[] pin); // i take the result from the method Vehcost
System.out.println("Appear all array"+y ); //i want to appear the array.Did i create and an array with objects?
int k; // i do the same thing as the other
k=worklin1.Allage(int[] age);
System.out.println("Appear all array"+k);
} // end main
public static int Vehcost(int[] pin ) { //starting first method 1
int cost = 0;
for(int i =0; i < pin.length; i++) {
cost += pin[i].getcostVehicle();
pin[i]=getname()+ cost; //i want to save to pin the names and the cost of each one
}
return pin[i]; // i want to return the array pin
}//end method 1
public static int allAge(int[] age ) { //second method
if(getage() >18 ){ //if age is >18 only then will going to save on the array
for(int i =0; i < age.length; i++) {
age += age[i].getage();
}
}
return age; // i want to return the array age
}// end method 2
}

Null pointer with 2d arrays and objects

Hello I am making a project of multiple classes that creates a progress report. However I am testing out methods and am not yet complete with the project and came across a null pointer exception. Take a look at the code and see if you can help me out please. Keep in mind all methods aren't finished just trying to focus on my problem first. I also have a separate driver file that i do not find relevant to post, unless needed otherwise.
Student class:
public class Student {
private String name;
private char grade;
private double average;
private int[] scores = new int[5];
// Constructor
public Student() {
this.name = name;
this.grade = grade;
this.average = average;
this.scores = scores;
}
// Get the Name.
public String getName() {
return name;
}
// Set the Name.
public void setName(String name) {
this.name = name;
}
// Get the Grade.
public char getGrade() {
return grade;
}
// Set the Grade.
public void setGrade(char grade) {
this.grade = grade;
}
// Get the Average.
public double getAverage() {
return average;
}
// Set the Average.
public void setAverage(double average) {
this.average = average;
}
// Get the Scores.
public int[] getScores() {
return scores;
}
// Set the Scores.
public void setScores(int[] scores) {
this.scores = scores;
}
// Determine the average of the five test scores for each student
public void calculateAverage(){
}
public void calculateGrade(){
}
}
ProgressReport class (where im getting the null pointer exception):
public class ProgressReport {
// Create array to hold sections and students.
Student[][] sectionArray = new Student[2][];
// Constructor.
public ProgressReport() {
}
// Get sectionArray.
public Student[][] getSectionArray() {
return sectionArray;
}
// Set sectionArray.
public void setSectionArray(Student[][] sectionArray) {
this.sectionArray = sectionArray;
}
// Read the input file.
public void readInputFile() throws FileNotFoundException{
String line;
int studentNo;
// Open file
File inFile = new File("file.in");
// Create scanner for reading.
Scanner scanner = new Scanner(inFile);
// While inFile has more lines.
while(scanner.hasNext()){
// Read the next line.
line = scanner.nextLine();
// Trim line.
line = line.trim();
//Parse line into int.
studentNo = Integer.parseInt(line);
// For the number of students in section 1 extract data.
for(int i = 0; i<= studentNo; i++){
//Create new student.
sectionArray[0][i] = new Student(); **THIS IS WHERE I GET NULL POINTER EXCEPTION**
// Read next line.
line = scanner.nextLine();
// Create String Tokenizer using a space as the delimiter.
StringTokenizer strTokenizer = new StringTokenizer(line," ");
// While the String Tokeizer has more tokens get data.
while(strTokenizer.hasMoreTokens()){
// Extract name
String name = strTokenizer.nextToken();
// Set name
sectionArray[0][i].setName(name);
int[] scores = new int[5];
// Extract scores.
int score1 = Integer.parseInt(strTokenizer.nextToken());
int score2 = Integer.parseInt(strTokenizer.nextToken());
int score3 = Integer.parseInt(strTokenizer.nextToken());
int score4 = Integer.parseInt(strTokenizer.nextToken());
int score5 = Integer.parseInt(strTokenizer.nextToken());
//Put scores in scores array.
scores[0] = score1;
scores[1] = score2;
scores[2] = score3;
scores[3] = score4;
scores[4] = score5;
// Set scores.
sectionArray[0][i].setScores(scores);
}
}
}
}
// Generate a report.
public void generateReport(){
System.out.println("Progress Report\n");
System.out.println("Section 1");
System.out.println(sectionArray[0][0].getName());
}
// Sort by name.
public void sortByName(){
}
// Binary search.
public Student binarySearch(int section, String searchName){
return null;
}
}
I'm not asking anyone to finish my work, just explain why I am getting a null pointer exception please.
You need to initialize the second dimension once you know your number of Students as
studentNo = Integer.parseInt(line);
// initialize the Array
sectionArray[0] = new Student[studentNo];
// For the number of students in section 1 extract data.
for(int i = 0; i<= studentNo; i++){
You've always used your sectionArray as sectionArray[0][*]. I'm not sure if you actually need the array to be two-dimensional. Initializing it as new Student[2][]; suggests that you would be using sectionArray[1][*] as well at some point of time.
If you do that later on; you would need to initialize sectionArray[1] as well.
If you do something like this
String[][] array = new String[2][];
it would create one array that will have two null elements, so it is the same as
String[][] array = {null,null};
and since you are invoking sectionArray[0][i] on such array it is the same as invoking null[i] which throws NPE.
You need to specify both dimensions like: Student[][] sectionArray = new Student[2][2]; or initialize the second dimension like this: sectionArray[0] = new Student[students]; and sectionArray[1] = new Student[students];.
Well You are using array of array here for Student Class.
For each array of (array of array) you need to initiate each array with its required number
of elements .
Here :
Before this line... where you are getting Null pointer Exception,
sectionArray[0][i] = new Student();
you need to initiate the array sectionArray[0] with new keyword like this.
sectionArray[0]= new Student[studentNo]; // add this line to you code
then the code you have used will come.

Categories

Resources