java having trouble with multiple classes - java

so I'm trying to use a switch so that when i click on a range of 1 to 4, each one is directed to a class and performs its function. The choice "1" should asks for the user to input the id, name, other name and marks, then calculate it's average. The second class should then display all the information and I'm not sure how to do it.
Here is my main code:
public class lab3q1 {
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
Entries entriesobject = new Entries(); //object declaration
display displayobject = new display(); //object declaration
displayall displayallobject = new displayall(); //object declaration
sortdata sortdataobject = new sortdata();
System.out.println("1. Add new entries: ");
System.out.println("2. Display an entry: ");
System.out.println("3. Display all entries: ");
System.out.println("4. Sort Data: ");
System.out.println("5. Exit: ");
int s = sc.nextInt();
switch(s){
case 1:{
if(s==1)
try{
entriesobject.method0();
}
catch(Exception e){
System.out.println("You can't do that");
}
}
case 2:{
if(s==2){
try{
displayobject.method();
}
catch(Exception e){
System.out.println("You can't do that");
}
}
}
case 3:{
if(s==3){
try{
displayallobject.method2();
}
catch(Exception e){
System.out.println("You can't do that");
}
}
}
case 4:{
if(s==4){
try{
sortdataobject.method3();
}
catch(Exception e){
System.out.println("You can't do that");
}
}
}
case 5:{
if(s==5){break;}
}
}
}
}
Here is the first class:
public class Entries {
public void method0(){
int total=0,total2;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the student id: ");
int id = sc.nextInt();
sc.nextLine();
System.out.println("Enter the student name: ");
String name = sc.nextLine();
System.out.println("Enter the student other names: ");
String othername = sc.nextLine();
for(int i=1;i<=4;i++){
System.out.println("Enter the student marks" +(i));
int mark = sc.nextInt();
total += mark;
total2 =total/4;
System.out.println("The average marks is: "+total2);
}
}
}
And here is my second class:
public class display {
public void method() {
int n;
Scanner sc = new Scanner(System.in);
System.out.println("Here is the student id: ");
}
}
As you can see i can't seem to link them.

To answer your question: when different classes want to know about data in other classes (aka fields of other objects), you need ways to access that, like:
public class Student {
private int id;
... methods to put a value into id
public int getId() { return id; }
and then some other class that has one more Student objects can do.
Beyond that: you are getting your "separation of concerns" wrong. You should have one class that uses a scanner to "collect" data from the user. This class creates various other objects; and puts the data from the user into those objects.
All your other classes do not have / need a scanner object. They get their data, for example as parameters to their constructor.
System.out.println("The id is: " + someStudentObject.getId());

Related

Auto Inventory Program - Problems with file output and capturing int Index

import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Scanner;
public class AutoMobile {
private static String make;
private static String model;
private static String color;
private static int year;
private static int mileage;
private static int index =300;
public AutoMobile(String make, String model, String color, int year,
int mileage, int index) {
super();
this.make = make;
this.model = model;
this.color = color;
this.year = year;
this.mileage = mileage;
this.index = index;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public static int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
class Vehicle {
static ArrayList<AutoMobile> vehicleList = new ArrayList<>();
public static final String FILENAME = "F:\\CSU\\CSC320-01 Programming 1\\Week 8\\AutoMobile.txt";
//Prints to location with proper header, but returns package and no vehicles
public static void addVehicle() {
Scanner s = new Scanner(System.in);
System.out.println("------Add Vehicle-------");
System.out.print("Enter Vehicle make: ");
String make = s.nextLine();
System.out.print("Enter Vehicle model: ");
String model = s.nextLine();
System.out.print("Enter Vehicle color: ");
String color = s.nextLine();
System.out.print("Enter Vehicle year: ");
int year = s.nextInt();
System.out.print("Enter Vehicle mileage: ");
int mileage = s.nextInt();
System.out.print("Enter the Vehicle Index Number: ");
int index = s.nextInt();
AutoMobile a = new AutoMobile(make, model, color, year, mileage, index);
vehicleList.add(a);
System.out.println("Vehicle Added Successfully");
System.out.println("------------------------");
}
public static void removeVehicle() {
Scanner s = new Scanner(System.in);
System.out.println("------Remove Vehicle-------");
System.out.print("Enter Vehicle make: ");
String make = s.nextLine();
System.out.print("Enter Vehicle model: ");
String model = s.nextLine();
System.out.print("Enter the Vehicle Index Number: ");
int index = s.nextInt();
ListIterator<AutoMobile> iterator =vehicleList.listIterator();
boolean find = false;
while(iterator.hasNext()){
AutoMobile a1 =iterator.next();
if(a1.getMake().equalsIgnoreCase(make) && a1.getModel().equalsIgnoreCase(model) &&
a1.getIndex().equalsIgnoreCase(index)){ // Line Showing Error
iterator.remove();
find = true;
break;
}
}
if(find){
System.out.println("Vehicle Removed Successfully");
System.out.println("------------------------");
}
else{
System.out.println("No such Vehicle Exist");
System.out.println("------------------------");
}
}
public static void updateVehicle() {
Scanner s = new Scanner(System.in);
System.out.println("------Update Vehicle-------");
System.out.print("Enter the make of Automobile: ");
String make = s.nextLine();
System.out.print("Enter the model of Automobile: ");
String model = s.nextLine();
System.out.print("Enter the Vehicle Index Number: ");
int index = s.nextInt();
ListIterator<AutoMobile> iterator =vehicleList.listIterator();
boolean find = false;
while(iterator.hasNext()){
AutoMobile a1 =iterator.next();
if(a1.getMake().equalsIgnoreCase(make) && a1.getModel().equalsIgnoreCase(model)
&& a1.getIndex().equalsIgnoreCase(index)){ // Line Showing Error
System.out.println("-----Vehicle found-------");
System.out.print("Enter the new make of Automobile: ");
make = s.nextLine();
System.out.print("Enter the new model of Automobile: ");
model = s.nextLine();
System.out.print("Enter the new color of Automobile: ");
String color = s.nextLine();
System.out.print("Enter the new year of Automobile: ");
int year = s.nextInt();
System.out.print("Enter the new mileage of Automobile: ");
int mileage = s.nextInt();
a1.setMake(make);
a1.setModel(model);
a1.setColor(color);
a1.setYear(year);
a1.setMileage(mileage);
a1.setIndex(index);
find = true;
break;
}
}
if(find){
System.out.println("Vehicle Updated Successfully");
System.out.println("------------------------");
}
else{
System.out.println("No such Vehicle Exist");
System.out.println("------------------------");
}
}
public static void printfile() {
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(FILENAME);
bw = new BufferedWriter(fw);
String content = "ID Make Model Color Year Mileage\n";
bw.write(content);
Iterator itr=vehicleList.iterator();
while(itr.hasNext()){
bw.write(itr.next().toString()+"\n");
}
System.out.println("Done printing");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) throws FileNotFoundException {
do {
System.out
.println("============================VEHICLE OPTIONS============================");
System.out.println("1. Add Vehicle");
System.out.println("2. Remove Vehicle");
System.out.println("3. Update Vehicle");
System.out.println("4. Print Vehicle List");
System.out.println("5. Exit");
System.out
.println("=======================================================================");
System.out.println();
Scanner s = new Scanner(System.in);
System.out.print("Enter the choice: ");
int i = s.nextInt();
s.nextLine();
switch (i) {
case 1:
addVehicle();
break;
case 2:
removeVehicle();
break;
case 3:
updateVehicle();
break;
case 4:
printfile();
break;
case 5:
System.out.println("Good Bye!!!!!");
break;
default:
System.out.println("You entered the wrong choice!!!!");
System.out.println();
}
if(i==4)
break;
System.out.println();
} while (true);
PrintWriter pw = new PrintWriter("VehicleInventory");
String text ="Index,Make,Model,Color,Year,Mileage\n";
for(AutoMobile a : vehicleList){
text+=a.getIndex()+","+a.getMake()+","+a.getModel()+","+a.getColor()+","+a.getYear()+","+a.getMileage()+"\n";
}
pw.write(text);
pw.flush();
pw.close();
System.out.println("VehicleInventory file created succesfully");
System.out.println();
System.out.println(text);
}
}
Forgive my inexperience, but I am trying to compile a program for school that achieves the following.
private string make
private string model
private string color
private int year
private int mileage.
Your program should have appropriate methods such as:
default constructor
parameterized constructor
add a new vehicle method
list vehicle information (return string array)
remove a vehicle method
update vehicle attributes method.
All methods should include try..catch constructs. Except as noted all methods should return a success or failure message (failure message defined in catch).
Create an additional class to call your automobile class (e.g., Main or AutomobileInventory). Include a try..catch construct and print it to the console any errors.
Call automobile class with parameterized constructor (e.g., "make, model, color, year, mileage").
Then call the method to list the values. Loop through the array and print to the screen.
Call the remove vehicle method to clear the variables.
Print the return value.
Add a new vehicle.
Print the return value.
Call the list method and print the new vehicle information to the screen.
Update the vehicle.
Print the return value.
Call the listing method and print the information to the screen.
Display a message asking if the user wants to print the information to a file (Y or N).
Use a scanner to capture the response. If Y, print the file to a predefined location (e.g., C:\Temp\Autos.txt). Note: you may want to create a method to print the information in the main class.
If N, indicate that a file will not be printed.
I have the program working somewhat as i wanted, until i tried to assign index numbers to the user inputted vehicles for updating or removing at a later date. This does not return in the output, and all that is returning in the .txt file is the header, and my package listed, no vehicles. Any suggestions or help would be great!
index parameter is of primitive int data type
For int use = for comparing.
if (a1.getMake().equalsIgnoreCase(make) && a1.getModel().equalsIgnoreCase(model)
&& a1.getIndex() == index) {}

Create a program that allows to receive multiples entry data, shows the data from the list

i was told to make a program like that, after input i can see the data
This is my code, please help i had search how to do it but i mostly only if the data is already known not by user input.
is it using an array or using for?
i search many time but i still dont find like mine
ive tried using array but i dont know how to get the array like, there is 3 user input in one array. mostly i found just using one user input
and sometime i get the error where the string cannot meet the int type
import java.util.Scanner;
public class Case7{
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int choose=0;
String name ="";
String pos = "";
int age = 0;
do{
System.out.println("JOB VACANCY");
System.out.println("===========");
System.out.println("1. Insert new data");
System.out.println("2. List of staff");
System.out.println("3. Search staff");
System.out.println("4. Exit");
System.out.print("Choose: ");
choose = input.nextInt();
if (choose == 1)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
do{
System.out.print("Input staff name: ");
name = input.nextLine();
}while(name.length() < 3 || name.length() > 20);
do{
System.out.print("Input staff position [Manager | Analyst | Programmer]: ");
pos=input.nextLine();
}while(!pos.equalsIgnoreCase("Manager") && !pos.equalsIgnoreCase("Analyst") && !pos.equalsIgnoreCase("Programmer"));
do{
System.out.print("Input staff age: ");
age=input.nextInt();
}while(age <= 17);
System.out.println("Data has been added!");
input.nextLine();
input.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
else if (choose == 2)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
for (int i = 1; i < 6 ; i++ )
{
System.out.println("Staff ID :" + i);
System.out.println("==============");
System.out.println("1. name : " +name );
System.out.println("2. position : " +pos );
System.out.println("3. age : " +age );
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}
Can I suggest a radically different implementation?
You can use a switch to score the options and You can use a LinkedList to store all the new staff member dinamically.
Here's my commented code:
static LinkedList<Staffer> staff=new LinkedList<>(); //ours database
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
String s="";
int number=-1;
while(number!=4){ //if your choice is 4, we can exit!
//Chooser:
System.out.print("JOB VACANCY\n===========\n1. Input data\n2. Show Data\n3.Delete Data\n4.£xit\nYour choice: ");
s=input.nextLine();
if(s.matches("\\d+")){ //Check if s is a number
number=Integer.parseInt(s);
switch(number){
case 1: input(); break;
case 2: showData(); break;
case 3: deleteData(); break;
case 4: System.out.println("Goodbye!"); break;
default: System.out.println("Number not valid. Try again!");
}
}else
System.out.println("Number not valid. Try again!");
}
}
private static void showData() {
for(Staffer st:staff)
System.out.println(st);
}
private static void deleteData(/*parameters*/) {
// You can delete a staffer by passing the name, for example
}
private static void input() {
//Plese, implements your data control options...
String name, position;
int age;
System.out.print("Name: ");
name=input.nextLine();
System.out.print("Position: ");
position=input.nextLine();
System.out.print("Age: ");
age=(Integer.parseInt(input.nextLine()));
Staffer staffer=new Staffer(name,position, age);
staff.add(staffer);
}
public static class Staffer{ //a staff member has 3 parameter: name, position and age... You can add others
/*You should store the name using only upperCase or LowerCase, or
* John Williams != john williams != JOHN WILLIAMS and you can have three times
* the same people.
*
* The position can be converted in enum for the same reason.
*/
private String name, position;
private int age;
public Staffer(String name, String position, int age){
this.name=name;
this.position=position;
this.age=age;
}
#Override
public String toString(){
return "Mr. "+name+", "+position+" (age: "+age+")";
}
}
You can see the following example output:
.
Obviously, you have to improve the output and all the data check options.

Method to Find ArrayList Index to Where the Object Will be Added

I have an ArrayList that is being filled with customer information using a Customer class. In my addCustomerRecord method, I am calling findAddIndex within the addCustomerRecord method so the data entered will be sorted prior to displaying the data. Here is my code and do not mind the fileWhatever method, I don't use it.
public class CustomerDemo
{
//arrayList of customer objects
public static ArrayList<Customer> customerAL = new ArrayList<>();
public static void main (String[] args)
{
//to hold menu choice
String menuChoice = "";
Scanner kb = new Scanner(System.in);
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
//loop priming read
menuChoice = kb.nextLine();
//make input case insensitive
menuChoice = menuChoice.toLowerCase();
do
{
if(menuChoice.equals("a"))
addCustomerRecord(kb);
else if(menuChoice.equals("d"))
{
displayCustomerRecords();
}
else if(menuChoice.equals("q"))
{
System.out.println("Program exiting..");
System.exit(0);
}
else
{
System.out.println("incorrect entry. Please re-enter a valid entry: \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}
System.out.println("To add a record press 'A': \n"
+ "to display all records press 'D': \n"
+ "to exit press 'Q': \n");
menuChoice = kb.nextLine();
menuChoice = menuChoice.toLowerCase();
}while(menuChoice.equals("a") || menuChoice.equals("d") || menuChoice.equals("q"));
kb.close();
}
/* public static void displayCustomerRecords()
{
System.out.println();
for (int i = 0; i < customerAL.size(); ++i)
{
System.out.printf("%-15s", customerAL.get(i).getLastName());
System.out.printf("%-15s", customerAL.get(i).getFirstName());
System.out.printf("%-6s", customerAL.get(i).getCustID());
System.out.printf("%15s\n", customerAL.get(i).getPhoneNumber());
}
System.out.println();
}
/**
* prompts to enter customer data and mutator methods called
* with a Scanner object passed as an argument to set data
* #param location index position of where the element will be added.
* #param kb a Scanner object to accept input
*/
public static void addCustomerRecord(Scanner kb)
{
Customer currentCustomerMemoryAddress = new Customer();
System.out.println("Enter first name: \n");
String fName = kb.nextLine();
currentCustomerMemoryAddress.setFirstName(fName);
System.out.println("Enter last name: \n");
String lName = kb.nextLine();
currentCustomerMemoryAddress.setLastName(lName);
System.out.println("Enter customer phone number: \n");
String pNum = kb.nextLine();
currentCustomerMemoryAddress.setPhoneNumber(pNum);
System.out.println("Enter customer ID number: \n");
String ID = kb.nextLine();
currentCustomerMemoryAddress.setCustID(ID);
int addLocation = findAddLocation(currentCustomerMemoryAddress);
customerAL.add(addLocation, currentCustomerMemoryAddress);
currentCustomerMemoryAddress = null;
}
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(int i = 0; i < customerAL.size(); i++)
{
//Stumped here
}
}
else
return location;
return location;
}
}
It looks like you are reinventing the wheel here William
Replace your code for displayCustomerRecords with this:
public static void displayCustomerRecords()
{
System.out.println();
customerAL.stream().map(c -> String.format("%-15s%-15s%-6s%15s\n",
c.getLastName(), c.getFirstName(), c.getCustID(), c.getPhoneNumber()))
.sorted()
.forEach(System.out::print);
System.out.println();
}
Update
Taking into account your comment you can replace your findAddLocationmethod by the following:
private static Comparator<Customer> comparator = Comparator.comparing(Customer::getLastName)
.thenComparing(Customer::getFirstName)
.thenComparing(Customer::getCustID)
.thenComparing(Customer::getPhoneNumber);
public static int findAddLocation(Customer cust)
{
int location = 0;
if(!customerAL.isEmpty())
{
for(Customer customerInList : customerAL)
{
if(comparator.compare(customerInList, cust) > 0) {
break;
}
location++;
}
}
return location;
}
We are traversing the array using Java's enhanced for-loop and comparing the objects using a Java 8 declared comparator (which I believe is the key to this assignment).
It would be a good idea if you could look into the Comparable interface and implement it in your Customer class. That way you could simply do a simple call to customerInList.compareTo(cust) to compare both objects.
As already stated, this is not a good practice and shouldn't be used in production code.

How do you run a Java class from another class?

I am working on a project for school. at this point i'm just going over board, I would like to run the class bookstoreCreditPersonal if none of the following conditions are true, but I cant get it to work. any suggestions?
import java.util.Scanner;
public class bookstoreCreditPersonal {
public static void main(Object o) {
String studentNamePers;
String userType;
double studentGPAPers;
double bookstoreCreditPers;
Scanner input = new Scanner(System.in);
System.out.print("Please enter 'S' if you are the student, 'T' if you are the teacher, or 'P' if you are the Parent: ");
userType = input.nextLine();
if (userType.equals("S")) {
System.out.println("Greetings student...");
Scanner Sinput = new Scanner(System.in);
System.out.println("Please enter your(The students) first and last name :");
studentNamePers = input.nextLine();
Scanner SSinput = new Scanner(System.in);
System.out.println("Please enter your(The student's) GPA :");
studentGPAPers = input.nextDouble();
bookstoreCreditPers = studentGPAPers * 10;
System.out.println(studentNamePers + ", your GPA is " + studentGPAPers + ", and you have an available bookstore credit of $" + bookstoreCreditPers);
} else if (userType.equals("T")) {
System.out.println("Teacher");
} else if (userType.equals("P")) {
System.out.println("Parent");
} else {
System.out.println("Lets try that again, one character, in capital form only please.");
//created a class that reruns this class
runClassBSCP.call(null);
}
}
}
Here is the class runClassBSCP:
public class runClassBSCP {
public void call() {
bookstoreCreditPersonal.main(null);
}
}
You need to instantiate/create an object of the class. Then you can call the desired method with the object.
runClassBSCP bscp = new runClassBSCP();
bscp.call();
Also, your class names should always start with an uppercase letter: RunClassBSCP, rather than `runClassBSCP'. For more info, check out Code Conventions for the Java Programming Language.

An application for a temporary management with Java

Hello the StackOverflow community! I am recent Java learner with 1 year of experience only. I was asked to design a software that mimics a school DB, storing all names, class, roll, and other details. When asked to, it would display appropriate messages, like calculating performance, deleting records, etc. It is yet an incomplete work but the first part (accepting and storing details) are done. I have spent a lot of time behind this and the only thing I get is a nullPointerError. Sorry, but I have been asked to stick to the basics, so no glitzy code. I have used inheritance. The superclass is "Student".
public class Student {
int roll,age = 0; // Roll to be auto-updated
String cl,name;
// Marks variables now
int m_eng, m_math, m_physics, m_chem, m_bio = 0;
public Student(){
}
public Student(int a, String cla){
age = a;
cl = cla; // Assign values
}
void setMarks(int eng, int math, int phy, int chem, int bio){
m_eng = eng; m_math = math; m_physics = phy; m_chem = chem; m_bio = bio;
}
}
Here's the error:
java.lang.NullPointerException
at Application.accept_data(Application.java:35)
at Application.execute(Application.java:23)
at Application.input(Application.java:16)
at Application.main(Application.java:101)
Here is the code, though:
import java.util.Scanner;
public class Application extends Student {
static int n; static Scanner sc = new Scanner(System.in);
static Student s[];
void input(){
System.out.println("Enter the number of students: ");
n = sc.nextInt();
s = new Student[n]; // Create array for n students
System.out.println("Enter your choice: ");
System.out.println("1. Accept student's details ");
System.out.println("2. Display all records ");
System.out.println("3. Display data student-wise ");
System.out.println("4. Delete record");
System.out.println("5. Display performance status");
System.out.println("6. Exit");
execute();
}
static void execute(){
boolean correct = false;
while (!correct){
int op = sc.nextInt();
switch(op){
case 1: accept_data(); correct = true;
case 2: disp_data();correct = true;
case 3: disp_studentwise();correct = true;
case 4: del_record();correct = true;
case 5: performance();correct = true;
case 6: System.exit(0); correct = true;//Terminate
default: System.out.println("You must enter a choice. Kindly re-enter: ");correct = false;
}
}
}
static void accept_data(){
for (int i = 0; i<s.length; i++){
s[i].roll = i+1; //Autoupdate roll
System.out.println("Enter name: "); s[i].name = sc.nextLine();
System.out.println("Enter age: "); s[i].age = sc.nextInt(); // Refer to object prope.
System.out.println("Enter class: "); s[i].cl = sc.nextLine();
System.out.println("We're heading for marks entry!");
System.out.println("Enter marks in the following order: ENGLISH, MATH, PHYSICS, CHEMISTRY, BIOLOGY");
s[i].setMarks(sc.nextInt(),sc.nextInt(),sc.nextInt(),sc.nextInt(),sc.nextInt());
}
System.out.println("Thanks. Main menu, please enter your choice now: ");
execute();
}
static void disp_data(){
System.out.println("The system will display all stored information of students available.");
for (int i = 0; i<s.length; i++){
if (s[i].roll != -1){
continue; // In case record is deleted, it won't display
}
else {
printrec(i);
}
}
System.out.println("Main menu, please enter your choice: ");
execute();
}
static void disp_studentwise(){
System.out.println("Enter the roll number");
int r = sc.nextInt();
boolean ok = (r>s.length||r<0)?false:true;
while (!ok){
System.out.println("Incorrect roll. Please re-enter: ");
r = sc.nextInt();
if (r>s.length) ok = false;
else ok = true;
}
printrec(r-1);
System.out.println("Main menu, please enter your choice: ");
execute();
}
static void printrec(int n){
int i = n;
System.out.println("For roll number " + s[i].roll + ", details: ");
System.out.println("Name: " + s[i].name); System.out.println("Age: " + s[i].age);
System.out.println("Class: " + s[i].cl);
System.out.println("Subject \t Marks");
System.out.println("English: \t " + s[i].m_eng); // Display record with marks
System.out.println("Maths: \t " + s[i].m_math);
System.out.println("Physics: \t " + s[i].m_physics);
System.out.println("Chemistry: \t " + s[i].m_chem);
System.out.println("Biology: \t " + s[i].m_bio);
}
static void del_record(){
System.out.println("Enter the roll number you want to delete: ");
int rll = sc.nextInt();
for (int i = 0; i<s.length; i++){
if (rll == s[i].roll){
s[i].roll = -1; // Assign non-positive value to refer deleted items
}
}
}
static void performance(){
}
public static void main(String[] args){
Application ob = new Application();
ob.input(); // Start program
}
}
Can anyone point out what's going wrong? Why there's a problem with accepting details of students after pressing for the 1st option? It shows nullPointer on s[i].roll. Keep in mind that roll is autoupdated, and user doesn't intervene there. It serves as a primary key. An explanation would be beneficial, if possible of course, I am eager to learn. Thanks.
this :
s = new Student[n]; // Create array for n students
You are just creating an array of 'n' Student objects here ... that doesn't mean that your 'n' Students are initialized ... your array contains only 'null' values ...
you may want in your accept_data method do a :
for (int i = 0; i<s.length; i++){
s[i] = new Student();
s[i].roll = i+1; //Autoupdate roll
....
You are getting an NPE because you create an array of Students in your input method, but you never populate it with Student objects, so in accept_data, you're trying to access the roll field on a non-existent object.
You will need to fill in the array with new Student objects in your input method before you call accept_data.

Categories

Resources