Java Inventory Project. Arrays - java

So I am trying to figure out how to get my code to work, but I keep on getting a nullError. Am I not storing my data correctly? Here is my code:
public class ProductTesterPart1{
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter the product number, name, stock, and price in that order.");
List<ProductPart1> products = new ArrayList<ProductPart1>();
String line = userInput.nextLine();
while (!line.equals("quit")) {
if (line == null || line.trim().isEmpty()) {
products.add(new ProductPart1());
}
else {
try {
Scanner s = new Scanner(line);
int number = s.nextInt();
String name = s.next();
int stock = s.nextInt();
double price = s.nextDouble();
products.add(new ProductPart1(number, name, stock, price));
}
catch (NoSuchElementException e) {
System.out.print("Error: " + e.getMessage());
}
}
}
for (ProductPart1 p : products) {
System.out.println(p.toString());
}
}
And of course, that is the driver class, here is my object:
public class ProductPart1 {
//Declares variables
private int productNumber;
private String productName;
private int productStock;
private double productPrice;
//Constructor
public ProductPart1(){
setNumber(0);
productName = "Null";
productStock = 0;
productPrice = 0.0;
}
//Overload constructor
public ProductPart1(int number, String name, int stock, double price){
productNumber = number;
productName = name;
productStock = stock;
productPrice = price;
}
//set the number of the object
public void setNumber(int newNumber){
productNumber = newNumber;
}
//set the name of the object
public void setName(String newName){
productName = newName;
}
//set the stock of an object
public void setStock(int newStock){
productStock = newStock;
}
//set the price of an object
public void setPrice(double newPrice){
productPrice = newPrice;
}
//get the number of an object
public int getNumber(){
return getNumber();
}
//get the name of an object
public String getName(){
return productName;
}
//get the stock of an object
public int getStock(){
return productStock;
}
//get the price of an object
public double getPrice(){
return productPrice;
}
//toString to bring the object together.
public String toString(){
return new String("Number: " + getNumber() + " Name: " + productName + " Price: " + productPrice + " Stock: " + productStock);
}

try this updated code:
public class ProductTesterPart1{
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter the product number, name, stock, and price in that order.");
List<ProductPart1> products = new ArrayList<ProductPart1>();
String line = userInput.nextLine();
while (!line.equals("quit")) {
if (line == null || line.trim().isEmpty()) {
products.add(new ProductPart1());
}
else {
try {
Scanner s = new Scanner(line);
int number = s.nextInt();
String name = s.next();
int stock = s.nextInt();
double price = s.nextDouble();
products.add(new ProductPart1(number, name, stock, price));
} catch (NoSuchElementException e) {
System.out.print("Error: " + e.getMessage());
}
}
if(userInput.hasNext()){
line = userInput.nextLine();
} else {
break;
}
}
for (ProductPart1 p : products) {
System.out.println(p.toString());
}
}
}

Your code creates an infinite loop. First you read line of product number, name, stock, and price. Then you go into a while loop, where you read this line out, but never again change the line variable, so it gets read again and again infinitely.

Related

How to print out functions from a loop of an array of objects in java

How can I be able to print out the objects that I gave the program in case 2
What I'm trying to implement is case 2 giving me all the info about the stuff I put into case 1
At first I tried to just use the setters and getters but for some reason I was having a NullPointerException when I used the do-while method.
So I decided to use the constructor but at the same time it gave me an error when trying to implement case 2. so any help would be appreciated.
import java.util.Scanner;
public class GameProject {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int choice;
do{
GameSale[] game;
System.out.println("Hello! welcome to the menu!");
System.out.println("Please Choose your option!");
System.out.println(" 1-Enter a new game's Info \n 2-Check a game's Information \n 3- Check a game's sales \n 0-Exit");
choice = input.nextInt();
switch (choice){
case 0:
break;
case 1:
System.out.println("");
System.out.print("How many games do you want to add? : ");
int size = input.nextInt();
game = new GameSale[size];
for (int i = 0; i < size; i++) {
System.out.print("Enter Game "+(i+1) + "'s Name!: \n");
String tempname = input.next();
System.out.print("Enter the ID of the Game : \n");
int tempid = input.nextInt();
System.out.print("Enter the Game Type : \n");
String tempgametype=input.next();
System.out.print("Enter the development Company's Name : \n");
String tempgamecomp = input.next();
System.out.print("Enter the Release Sale : \n");
double temprelsale = input.nextDouble();
System.out.print("Enter the total Sales : \n");
double temptotsale = input.nextDouble();
game[i]=new GameSale(temprelsale,temptotsale,tempid,tempname,tempgamecomp,tempgametype);
}break;
case 2:
for(int i = 0; i < game.length; i++){
System.out.println(game[i].toString());
}
}while(choice!=0);
}
}
i got a class that has the setters and getters for some of the regular info
public class GameInfo {
protected int ID;
protected String GameName;
protected String DevelopmentCompany;
protected String GameType;
public GameInfo(int ID, String GameName, String DevelopmentCompany, String GameType) {
this.ID = ID;
this.GameName = GameName;
this.DevelopmentCompany = DevelopmentCompany;
this.GameType = GameType;
}
public void SetID(int id) {
this.ID = id;
}
public int GetID() {
System.out.println("The ID is " + ID);
return ID;
}
public void SetName(String Name) {
this.GameName = Name;
}
public String GetName() {
System.out.println("The Name of the Game Is " + GameName);
return GameName;
}
public void SetCompanyName(String CompanyName) {
this.DevelopmentCompany = CompanyName;
}
public String GetCompanyName() {
System.out.println("The Name Of the Development company Is " + DevelopmentCompany);
return DevelopmentCompany;
}
public void SetGameType(String GameType){
this.GameType=GameType;
}
public String GetGameType(){
System.out.println("The Game Type is : "+GameType);
return GameType;
}
}
and a super class with the sales and a constructor for the sales
public class GameSale extends GameInfo {
protected double ReleaseSales;
protected double TotalSales;
public GameSale(double ReleaseSales, double TotalSales, int ID, String GameName, String DevelopmentCompany, String GameType) {
super(ID, GameName, DevelopmentCompany, GameType);
this.ReleaseSales = ReleaseSales;
this.TotalSales = TotalSales;
}
public void SetReleaseSales(double RelSale){
this.ReleaseSales=RelSale;
}
public void SetTotalSales(double totSales){
this.TotalSales=totSales;
}
public double GetReleaseSales(){
System.out.println("The Release Sales Are "+ReleaseSales );
return ReleaseSales;
}
public double GetTotalSales(){
System.out.println("The Total Sales Are "+TotalSales);
return TotalSales;
}
}
Answered by Alex (thanks a lot dude)
here's a temporary fix just for debugging so far by initializing the array dimensions outside the do-while loop
main
import java.util.Scanner;
public class GameProject {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
int choice;
GameSale[] games = new GameSale[1];
do {
System.out.println("Hello! welcome to the menu!");
System.out.println("Please Choose your option!");
System.out.println(" 1-Enter a new game's Info \n 2-Check a game's Information \n 3- Check a game's sales \n 0-Exit");
choice = input.nextInt();
switch (choice) {
case 0:
break;
case 1:
for (int i = 0; i < games.length; i++) {
System.out.print("Enter Game " + (i + 1) + "'s Name!: \n");
String tempname = input.next();
System.out.print("Enter the ID of the Game : \n");
int tempid = input.nextInt();
System.out.print("Enter the Game Type : \n");
String tempgametype = input.next();
System.out.print("Enter the development Company's Name : \n");
String tempgamecomp = input.next();
System.out.print("Enter the Release Sale : \n");
double temprelsale = input.nextDouble();
System.out.print("Enter the total Sales : \n");
double temptotsale = input.nextDouble();
games[i] = new GameSale(temprelsale, temptotsale, tempid, tempname, tempgamecomp, tempgametype);
}
break;
case 2:
for (int i = 0; i < games.length; i++) {
System.out.println(games[i].toString());
}
}
} while ( choice != 0 );
}
}
game info
public class GameInfo {
protected int ID;
protected String GameName;
protected String DevelopmentCompany;
protected String GameType;
public GameInfo(int ID, String GameName, String DevelopmentCompany, String GameType) {
this.ID = ID;
this.GameName = GameName;
this.DevelopmentCompany = DevelopmentCompany;
this.GameType = GameType;
}
public void SetID(int id) {
this.ID = id;
}
public int GetID() {
System.out.println("The ID is " + ID);
return ID;
}
public void SetName(String Name) {
this.GameName = Name;
}
public String GetName() {
System.out.println("The Name of the Game Is " + GameName);
return GameName;
}
public void SetCompanyName(String CompanyName) {
this.DevelopmentCompany = CompanyName;
}
public String GetCompanyName() {
System.out.println("The Name Of the Development company Is " + DevelopmentCompany);
return DevelopmentCompany;
}
public void SetGameType(String GameType){
this.GameType=GameType;
}
public String GetGameType(){
System.out.println("The Game Type is : "+GameType);
return GameType;
}
}
game sale
public class GameSale extends GameInfo {
protected double ReleaseSales;
protected double TotalSales;
public GameSale(double ReleaseSales, double TotalSales, int ID, String GameName, String DevelopmentCompany, String GameType) {
super(ID, GameName, DevelopmentCompany, GameType);
this.ReleaseSales = ReleaseSales;
this.TotalSales = TotalSales;
}
public void SetReleaseSales(double RelSale){
this.ReleaseSales=RelSale;
}
public void SetTotalSales(double totSales){
this.TotalSales=totSales;
}
public double GetReleaseSales(){
System.out.println("The Release Sales Are "+ReleaseSales );
return ReleaseSales;
}
public double GetTotalSales(){
System.out.println("The Total Sales Are "+TotalSales);
return TotalSales;
}
public String toString(){
return this.ID + " " + this.GameName + " " + this.DevelopmentCompany + " " + this.GameType;
}}
Solution
toString()
In your class you should implement a toString() method.
This basically returns all the property values of your object as a String
public String toString(){
return this.ID + " " + this.GameName + " " + this.DevelopmentCompany + " " + this.GameType;
}
Then call it on your object in case2
game[i].toString()
Display
To list all games you have to iterate over your gamesArray and print out the informations with your toString() method;
for(int i = 0; i < games.length(); i++){
System.out.println(game[i].toString());
}
Scope
Create the games array outside of you case1 scope.
GameSale[] game = new GameSale[SomeFixedSize];
If you wanted to print a game's info at a given index in case 2:
if (game == null) { // Break if no game exists
System.out.println("There is no games to show!");
break;
}
System.out.print("Enter game index to show information: ");
int index = input.nextInt();
// Break if index is not in bounds
if (index < 0 || index > game.length) {
System.out.println("Incorrect index");
break;
}
System.out.println("Info of game: " + game[index].toString());
This code should ask for index as input and prints the info of the game and it will print 'There is no games to show!' if there was no any game added yet
Note you must add the toString() method in your GameSale class:
#Override
public String toString() {
return "ID: " + this.ID + " Name: " + this.GameName + " Development Company: " +
this.DevelopmentCompany + " Game Type: " + this.GameType + " Release Sales: " + ReleaseSales + " Total Sales: " + TotalSales;
}
also move the decleration of the game variable out of the scope of the do-while loop (above it) it will look like
GameSale[] game = null;
do { ...
Also if you want case 2 to show all games info you can replace the index part with a loop that iterates the whole 'game' array and prints every element's toString.

Using toString() method in Java

I am trying to utilize the toString() in a class I have called Employee(). I have a 1D array of type Employee, which stores Employee Data, which include the Employee ID, Employee Name, Employee Address, and Employee Hire Date. I want the user to specify the amount of employees, and then enter the relevant data for however many employees the user wants. I then want to print the result for the user with the information entered. I keep getting some results that are null. I tried using an If statement that printed output if it didn't equal null, but that didn't work. I know the output works if I print out a single variable, such as address, but I want all variables to print out. Thank you for any help.
public class Address
{
public String address;
public void getAddress(String a)
{
address = a;
}
public String toString()
{
return address;
}
}
public class Name
{
String name;
public void getName(String n)
{
name = n;
}
public String toString()
{
return name;
}
}
public class Date
{
public String date;
public String date1;
public void getDate(int d, int m, int y)
{
date1 = (m + "/" + d + "/" + y);
}
public String toString()
{
return date1;
}
}
import java.util.Scanner;
public class Employee
{
private int number;
private Name name1 = new Name();
private Address address1 = new Address();
private Date hireDate = new Date();
String number1;
public void getDate1(int d, int m, int y)
{
hireDate.getDate(d, m, y);
}
public void getID(int x)
{
number = x;
}
public void setName( String n)
{
name1.getName(n);
}
public void getAddress(String a)
{
address1.address = a;
}
String z;
public String toString()
{
number1 = String.valueOf(number);
String name2 = String.valueOf(name1);
String address2 = String.valueOf(address1);
String hireDate2 = String.valueOf(hireDate);
z = number1 + " " + name2 + " " + address2 + " " + hireDate2;
return z;
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter amount of Employees: ");
int input1 = input.nextInt();
input.nextLine();
for (int i = 0; i < input1; i++)
{
Employee [] employees = new Employee[4];
System.out.println("Please enter the employee ID: ");
int employeeID = input.nextInt();
input.nextLine();
employees[0] = new Employee();
employees[0].getID(employeeID);
System.out.println("Please enter the employees Name: ");
String name2 = input.nextLine();
employees[1] = new Employee();
employees[1].setName(name2);
System.out.println("Please enter the employee's address: ");
String address2 = input.nextLine();
employees[2] = new Employee();
employees[2].getAddress(address2);
System.out.println("please enter hire date, day (1-31),");
System.out.print("month (1-12), year (1901 - 2019) in order on seperate");
System.out.print(" lines: ");
int input2 = input.nextInt();
int input3 = input.nextInt();
int input4 = input.nextInt();
employees[3] = new Employee();
employees[3].getDate1(input2, input3, input4);
for (int p = 0; p < employees.length; p++)
{
System.out.println(employees[p]);
}
}
}
}
I have create classes which were needed. You can change them but you are creating employee object every time. I have corrected the code debug it and you will know what was wrong.
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
class Name {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class Employee {
private int number;
private Name name1 = new Name();
private Address address1 = new Address();
private Date hireDate = new Date();
String number1;
public void getDate1(int d, int m, int y) {
Calendar calendar = Calendar.getInstance();
calendar.set(y, m, d);
hireDate = calendar.getTime();
}
public void getID(int x) {
number = x;
}
public void setName(String n) {
name1.setName(n);
}
public void getAddress(String a) {
address1.setAddress(a);
}
String z;
public String toString() {
number1 = String.valueOf(number);
String name2 = name1.getName();
String address2 = address1.getAddress();
String hireDate2 = String.valueOf(hireDate);
z = number1 + " " + name2 + " " + address2 + " " + hireDate2;
return z;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter amount of Employees: ");
int input1 = input.nextInt();
input.nextLine();
Employee[] employees = new Employee[input1];
for (int i = 0; i < input1; i++) {
System.out.println("Please enter the employee ID: ");
int employeeID = input.nextInt();
input.nextLine();
employees[i] = new Employee();
employees[i].getID(employeeID);
System.out.println("Please enter the employees Name: ");
String name2 = input.nextLine();
employees[i].setName(name2);
System.out.println("Please enter the employee's address: ");
String address2 = input.nextLine();
employees[i].getAddress(address2);
System.out.println("please enter hire date, day (1-31),");
System.out.print("month (1-12), year (1901 - 2019) in order on seperate");
System.out.print(" lines: ");
int input2 = input.nextInt();
int input3 = input.nextInt();
int input4 = input.nextInt();
employees[i].getDate1(input2, input3, input4);
System.out.println(employees[i]);
}
}
}

Trying to populate ArrayList with user input with methods

I am trying to populate my array with user input; however, I cannot get it to properly work. I am trying to get an int for the user for the number of products they want to enter. Then I want to populate the array with more user input of actual products (Strings) based on the number of products they said they wanted to enter. This is my code:
import java.util.Scanner;
import java.util.ArrayList;
public class Practice {
public static void main(String[] args) {
bannerPrinter();
getNum();
int num = 0;
ArrayList<String> products = productBuilder(num);
boolean productGuess = getOrder(products);
if (productGuess) {
double price = getPrice();
double tax = getTax(price);
double total = getTotal(tax, price);
printTotal(total);
}
else {
System.out.print("Product not found.");
}
}
public static void bannerPrinter() {
System.out.println();
System.out.println("******************************************");
System.out.println("****** Welcome to my eCommerce app! ******");
System.out.println("******************************************");
System.out.println();
}
public static int getNum() {
Scanner scnr = new Scanner(System.in);
int num = 0;
System.out.print("Enter the number of products: ");
num = scnr.nextInt();
return num;
}
public static ArrayList<String> productBuilder(int num) {
Scanner scnr = new Scanner(System.in);
String arrayNames = "";
ArrayList<String> products = new ArrayList();
for (int i = 0; i <= num; i++) {
System.out.print("Enter the products: ");
products.add(arrayNames);
}
return products;
}
public static boolean getOrder(ArrayList<String> products) {
Scanner scnr = new Scanner(System.in);
String guess = "";
boolean productName = products.contains(guess);
System.out.print("Enter a product: ");
guess = scnr.nextLine();
if(productName) {
System.out.println();
System.out.print("This product has been found.");
System.out.println();
}
else {
System.out.println();
}
return productName;
}
public static double getPrice() {
double price = 0.0;
price = (int)(Math.random() * 100);
return price;
}
public static double getTax(double price) {
double tax = 0.0;
tax = price * 0.10;
return tax;
}
public static double getTotal(double price, double tax) {
double saleTotal = 0.0;
saleTotal = price + tax;
return saleTotal;
}
public static void printTotal(double saleTotal) {
System.out.println("You total is $" + saleTotal + "0");
}
}
I may not fully understand what you attempt to do but I did see some interesting lines... see my comments
public static ArrayList<String> productBuilder(int num) {
Scanner scnr = new Scanner(System.in);
String arrayNames = "";
ArrayList<String> products = new ArrayList();
for (int i = 0; i <= num; i++) {
System.out.print("Enter the products: ");
// I assume here scnr is supposed to read something
// and assign it to arrayNames?
products.add(arrayNames);
}
return products;
}
public static boolean getOrder(ArrayList<String> products) {
Scanner scnr = new Scanner(System.in);
String guess = "";
// I assume this line is supposed to be after
// guess = scnr.nextLine()?
boolean productName = products.contains(guess); // very confusing line
System.out.print("Enter a product: ");
guess = scnr.nextLine();
if(productName) {
System.out.println();
System.out.print("This product has been found.");
System.out.println();
}
else {
System.out.println();
}
return productName;
}

Java can't get array list to print out?

So i have 3 classes, and one that runs all the code. A student class, a Graduate student class and an undergraduate class, and a class called lab 4 that runs the code. The code asks for how many grad students and how many undergrad students there are, then asks the user to input all the information for that number of each. After all the info is inputed, the under grad or grad student objects are added to an array list of students. after all the students are added, then prints all the information. However when i input all the information, the array does not print, the program terminates. How do i get the array to print out?
Code:
Lab 4: creates the student objects, array list, adds them to the array, and the prints all information for objects added to the array list
import java.util.ArrayList;
import java.util.Scanner;
public class Lab04 {
public static void main(String[] args) {
ArrayList <Student> studentList = new ArrayList <Student>();
Scanner s = new Scanner(System.in);
System.out.println("How many Graduate Students do you want to store?");
int numOfStudents = s.nextInt();
s.nextLine();
for (int i = 0; i < numOfStudents; i++) {
System.out.println("What is the student's name?");
String name = s.nextLine();
System.out.println("What is the student's GPA?");
double GPA = s.nextDouble();
s.nextLine();
System.out.println("What is the student's ID?");
String ID = s.nextLine();
System.out.println("What is the student's High School?");
String highSchool = s.nextLine();
System.out.println("What is the student's graduate major?");
String gradMajor = s.nextLine();
System.out.println("What is the student's undergraduate major?");
String underMajor = s.nextLine();
System.out.println("What is the student's undergradute school? ");
String underSchool = s.nextLine();
GraduateStudent gradStu = new GraduateStudent(name, GPA, ID, highSchool, gradMajor, underMajor,
underSchool);
studentList.add(gradStu);
}
System.out.println("How many UnderGraduate students are there?");
int numOfUnder = s.nextInt();
s.nextLine();
for (int j = 0; j < numOfUnder; j++) {
System.out.println("What is the student's name?");
String name = s.nextLine();
System.out.println("What is the student's GPA?");
double GPA = s.nextDouble();
s.nextLine();
System.out.println("What is the student's ID?");
String ID = s.nextLine();
System.out.println("What is the student's High School?");
String highSchool = s.nextLine();
System.out.println("What is the student's major?");
String major = s.nextLine();
System.out.println("What the student's minor?");
String minor = s.nextLine();
UnderGraduate UnderGrad = new UnderGraduate(name, GPA, ID, highSchool, major, minor);
studentList.add(UnderGrad);
}
for (int j = 0; j < studentList.size(); j++) {
(studentList.get(j)).getStudentInformation();
}
}
}
Student Class:
public class Student {
private String name;
private double gpa;
private String id;
private String highSchool;
//private String major;
//private String minor;
public Student() {
name = "";
gpa = 0.0;
id = "";
highSchool = "";
//major = "";
//minor = "";
}
public Student(String name, double gpa, String id, String highSchool){
this.name = name;
this.gpa = gpa;
this.id = id;
this.highSchool = highSchool;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getGpa() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getHighSchool() {
return highSchool;
}
public void setHighSchool(String highSchool) {
this.highSchool = highSchool;
}
public String getStudentInformation() {
String result = "Name: " + name + " GPA: " + gpa + " ID: " + id
+ " High School: " + highSchool;
return result;
}
}
graduate Class:
public class GraduateStudent extends Student {
private String gradMajor;
private String underMajor;
private String underSchool;
public GraduateStudent(String name, double gpa, String id, String highSchool,
String gradMajor, String underMajor, String underSchool) {
super(name, gpa, id, highSchool);
this.gradMajor = gradMajor;
this.underMajor = underMajor;
this.underSchool = underSchool;
}
public String getGradMajor() {
return gradMajor;
}
public void setGradMajor(String gradMajor) {
this.gradMajor = gradMajor;
}
public String getUnderMajor() {
return underMajor;
}
public void setUnderMajor(String underMajor) {
this.underMajor = underMajor;
}
public String getUnderSchool() {
return underSchool;
}
public void setUnderSchool(String underSchool) {
this.underSchool = underSchool;
}
#Override
public String getStudentInformation() {
String result = super.getStudentInformation()+
"Graduate Major: " + gradMajor + "Undergraduate Major: " + underMajor +
"Undergraduate School: " + underSchool;
return result;
}
}
Because you're not printing anything. Change
for (int j = 0; j < studentList.size(); j++) {
(studentList.get(j)).getStudentInformation();
}
to
for (int j = 0; j < studentList.size(); j++) {
System.out.println((studentList.get(j)).getStudentInformation());
}
When you ask getStudentInformation, it returns a String, what you want to do now is to System.out.println(...) this String object

cannot enter value and null pointer exception

import java.util.*;
import java.io.*;
public class Patient
{
private String patientId;
private String patientName;
private String gender;
private int age;
private String patientWardNumber;
private int patientBedNumber;
private String dateRegistered;
private String treatment;
private int wardedDuration;
private double price;
private double payment;
public Patient()
{
String patientId =" ";
String patientName =" ";
String patientWardNumber =" ";
String dateRegistered =" ";
String treatment =" ";
int patienBedDuration = 0;
int wardedDuration = 0;
int age = 0;
String gender = " ";
double price = 0.00;
}
public Patient(String ID,String N,String G,int A,String WN,int BN,String DR,String T,int WD)
{
patientId = ID;
patientName = N;
gender = G;
age = A;
patientWardNumber = WN;
patientBedNumber = BN;
dateRegistered = DR;
treatment = T;
wardedDuration = WD;
}
public void SetPatient(String ID,String N,String G,int A,String WN,int BN,String DR,String T,int WD)
{
patientId = ID;
patientName = N;
gender = G;
age = A;
patientWardNumber = WN;
patientBedNumber = BN;
dateRegistered = DR;
treatment = T;
wardedDuration = WD;
}
public String getPatientId()
{
return patientId;
}
public String getPatientName()
{
return patientName;
}
public String getGender()
{
return gender;
}
public int getAge()
{
return age;
}
public String getPatientWardNumber()
{
return patientWardNumber;
}
public int getPatientBedNumber()
{
return patientBedNumber;
}
public String getDateRegistered()
{
return dateRegistered;
}
public String getTreatment()
{
return treatment;
}
public int getWardedDuration()
{
return wardedDuration;
}
public double getPrice()
{
return price;
}
public double getPayment()
{
return payment;
}
public String toString()
{
return patientId+" "+patientName+" "+gender+" "+age+" "+patientWardNumber+" "+patientBedNumber+" "+dateRegistered+" "+treatment+" "+wardedDuration+" "+price+" "+payment;
}
public static void main(String[]args)
{
ArrayList PatientList = new ArrayList();
Scanner scan = new Scanner(System.in);
System.out.println("Enter how many patient are : ");
int num = scan.nextInt();
for(int i=0; i<num; i++)
{
System.out.println("Enter patient ID: ");
String patientId = scan.next();
System.out.println("Enter patient Name: ");
String patientName = scan.next();
System.out.println("Enter the patient's gender: ");
String gender = scan.next();
System.out.println("Enter the patient's age: ");
int age = scan.nextInt();
System.out.println("Enter patient ward number: ");
String patientWardNumber = scan.next();
System.out.println("Enter patient's Bed Number: ");
int patientBedNumber = scan.nextInt();
System.out.println("Enter patient's registeration date: ");
String dateRegistered = scan.next();
System.out.println("Enter the treatment: ");
String treatment = scan.next();
System.out.println("Enter the ward duration: ");
int wardedDuration = scan.nextInt();
Patient data = new Patient(patientId,patientName,gender,age,patientWardNumber,patientBedNumber,dateRegistered,treatment,wardedDuration);
PatientList.add(data);
}
System.out.println("Total patients are: "+PatientList.size());
System.out.println("Enter patient name : ");
Patient D= null;
Object data ;
String user=scan.next();
boolean found=false;
while(!PatientList.isEmpty())
{
if(D.getPatientName().equalsIgnoreCase(user))
{
found=true;
System.out.println(D.toString());
}
else if (found==false)
{
System.out.println("Patient is not found ! TRY AGAIN");
}
}
}
}
I got 2 problems while running this coding.First i cannot enter value for my ward duration. .Second,when i want to search my patient,it cannot display the information about the patient.Its say null pointer exception.i'm still beginner at java.someone can show me the solution?
This is my output
Because you haven't initialized your Patient object D inside the main() method.
Patient D= null;
and invoking a method on it.
if(D.getPatientName().equalsIgnoreCase(user)){ // Here D is null
found=true;
System.out.println(D.toString());
}
You have to create an object of Patient and initialized variable D like,
Patient D= new Patient();
For your "ward duration" input problem; you are reading strings with Scanner.next(). Note that this only reads one word. So if you were to enter "Level 1" for, e.g., treatment, only "Level" would be read; the "1" would be left on the stream and could corrupt later input (in your case, the "1" is being read by the nextInt() call for ward duration).
I suggest using Scanner.nextLine() for those string inputs instead. That way it will read every word on the full line, and will allow you to enter data that contains spaces without issue.
As for your NullPointerException, Kugathasan Abimaran's answer covers that well.
Also, you have another smaller issue. In your Patient constructor, you are not actually initializing any of the member fields. You are declaring and initializing local variables instead:
public Patient() {
String patientId = " ";
String patientName = " ";
String patientWardNumber = " ";
String dateRegistered = " ";
String treatment = " ";
int patienBedDuration = 0;
int wardedDuration = 0;
int age = 0;
String gender = " ";
double price = 0.00;
}
Should be:
public Patient() {
patientId = " ";
patientName = " ";
patientWardNumber = " ";
dateRegistered = " ";
treatment = " ";
patientBedNumber = 0; // <- note: "patienBedDuration" was probably a typo
wardedDuration = 0;
age = 0;
gender = " ";
price = 0.00;
}
By the way, traditionally "" is used to represent an empty string, not " ". Also, it's redundant to initialize the numeric fields to 0 because that's their default initial value anyways.

Categories