Prevent duplicate Integer ID numbers in an Array using While vs If - java

I created a program that will add, view, update and delete student arrays. To prevent user from entering duplicate ID number, I used the following code:
public static void addStud() {
int numID, year;
String userName, course;
int addMore;
do {
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
for(int x = 0; x < count; x++){
if(numID == stud[x].getNumID()) {
System.out.println("The Student ID: " +numID+ " already exist.\nEnter New Student ID: ");
numID = sc.nextInt();
sc.nextLine();
x = 0;
}
}
System.out.println("2. Enter Student Name");
userName = sc.nextLine();
System.out.println("3. Enter Student Course");
course = sc.nextLine();
System.out.println("4. Enter Student Year");
year = sc.nextInt();
stud[count] = new Student(numID, year, userName, course);
++count;
System.out.println("To add another Student Record Press 1 [any] number to stop");
addMore = sc.nextInt();
sc.nextLine();
} while (addMore == 1);
}
However, by inputting ID numbers 1-5 (again and again) for some reason the program accepts the duplicate ID [1]. What I, did is i change the if(numID == stud[x].getNumID()) to while(numID == stud[x].getNumID()) and it fix my problem.
I'm not good with debugging, I just want to know what went wrong? Why it works with while and not with if?
Bellow is my full program. Try to input ID numbers 1 - 5 and repeat it will accept the duplicate if used the IF statement.
import java.util.Scanner;
public class StudentArray {
static Scanner sc = new Scanner(System.in);
static Student[] stud = new Student[100];
static int count = 0;
public static void main(String[] args) {
while (true) {
int select;
System.out.println("1. Add Student Record");
System.out.println("2. View Student Record");
System.out.println("3. Update Student Record");
System.out.println("4. Delete Student Record");
System.out.println("0. Exit");
select = sc.nextInt();
switch (select) {
case 1:
addStud();
break;
case 2:
viewStud();
break;
case 3:
updateStud();
break;
case 4:
deleteStud();
break;
case 0:
return;
default:
System.out.println("Invalid Option");
}
}
}
public static void addStud() {
int numID, year;
String userName, course;
int addMore;
do {
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
for(int x = 0; x < count; x++){
if(numID == stud[x].getNumID()) { // change if to while prevents duplicate
System.out.println("The Student ID: " +numID+ " already exist.\nEnter New Student ID: ");
numID = sc.nextInt();
sc.nextLine();
x = 0;
}
}
System.out.println("2. Enter Student Name");
userName = sc.nextLine();
System.out.println("3. Enter Student Course");
course = sc.nextLine();
System.out.println("4. Enter Student Year");
year = sc.nextInt();
stud[count] = new Student(numID, year, userName, course);
++count;
System.out.println("To add another Student Record Press 1 [any] number to stop");
addMore = sc.nextInt();
sc.nextLine();
} while (addMore == 1);
}
public static void viewStud() {
while(true) {
int select;
System.out.println("1. View Record by ID number ");
System.out.println("2. View Record by Course ");
System.out.println("3. View Record by Course and Year ");
System.out.println("4. View All ");
System.out.println("0. Return Main Menu ");
select = sc.nextInt();
sc.nextLine();
switch (select) {
case 1:
int view1;
System.out.println("Please enter Student ID Number: ");
view1 = sc.nextInt();
viewArray(view1);
break;
case 2:
String view2;
System.out.println("Please enter Student Course: ");
view2 = sc.nextLine();
viewArray(view2);
break;
case 3:
String view3;
int view4;
System.out.println("Please enter Student Course: ");
view3 = sc.nextLine();
System.out.println("Please enter Student Year: ");
view4 = sc.nextInt();
viewArray(view3, view4);
break;
case 4:
viewArray();
break;
case 0:
return;
default:
System.out.println("Invalid Option");
}
}
}
public static void viewArray(){
System.out.println("Student ID\tStudent Name\tStudent Course\tStudent Year");
for (Student student : stud) {
if (student != null) {
System.out.println(student.getNumID()+"\t\t\t\t"+student.getUserName()+ "\t\t\t\t"+student.getCourse()+"\t\t\t\t"+ student.getYear());
}
}
}
public static void viewArray(int key){
boolean isExist = false;
int temp = 0;
for(int x = 0; x < count; ++x){
if(key == stud[x].getNumID()){
temp = x;
isExist = true;
break;
}
}
if(isExist){
System.out.println("1. Student ID: " + stud[temp].getNumID());
System.out.println("2. Student Name: " + stud[temp].getUserName());
System.out.println("3. Student Course: " + stud[temp].getCourse());
System.out.println("4. Student Year: " + stud[temp].getYear() +"\n");
}
else
System.out.println("The Student ID: " +key+ " is invalid");
}
public static void viewArray(String key){
boolean isExist = false;
for(int x = 0; x < count; ++x){
if(key.equalsIgnoreCase(stud[x].getCourse())){
System.out.println("1. Student ID: " + stud[x].getNumID());
System.out.println("2. Student Name: " + stud[x].getUserName());
System.out.println("3. Student Course: " + stud[x].getCourse());
System.out.println("4. Student Year: " + stud[x].getYear() +"\n");
isExist = true;
}
}
if(isExist == false){
System.out.println("The Student Course: " +key+ " is invalid");
}
}
public static void viewArray(String course, int year){
boolean isExist = false;
for(int x = 0; x < count; ++x){
if(course.equalsIgnoreCase(stud[x].getCourse()) && year == stud[x].getYear()){
System.out.println("1. Student ID: " + stud[x].getNumID());
System.out.println("2. Student Name: " + stud[x].getUserName());
System.out.println("3. Student Course: " + stud[x].getCourse());
System.out.println("4. Student Year: " + stud[x].getYear() +"\n");
isExist = true;
}
}
if(isExist == false){
System.out.println("The Student Course: " +course+ " and Year: "+year+" is invalid");
}
}
public static void updateStud(){
int numID, temp = 0;
boolean flag = false;
System.out.println("Student ID\tStudent Name\tStudent Course\tStudent Year");
for (Student student : stud) {
if (student != null) {
System.out.println(student.getNumID()+"\t\t\t\t"+student.getUserName()+ "\t\t\t\t"+student.getCourse()+"\t\t\t\t"+ student.getYear());
}
}
System.out.println("Enter Student ID to update: ");
numID = sc.nextInt();
sc.nextLine();
for(int x = 0; x < count && flag == false; x++){
if (numID == stud[x].getNumID()){
temp = x;
flag = true;
}
}
if(flag) {
System.out.println("Enter Student Name: ");
stud[temp].setUserName(sc.nextLine());
System.out.println("Enter Student Course");
stud[temp].setCourse(sc.nextLine());
System.out.println("Enter Student Year");
stud[temp].setYear(sc.nextInt());
System.out.println("The Student ID: " + numID + " record has been updated");
}
else
System.out.println("The Student ID: " +numID+ " is invalid");
}
public static void deleteStud() {
int numID, temp = 0;
boolean flag = false;
if (count > 0){ // check if array is empty
System.out.println("Student ID\tStudent Name\tStudent Course\tStudent Year");
for (Student student : stud) {
if (student != null) {
System.out.println(student.getNumID()+"\t\t\t\t"+student.getUserName()+ "\t\t\t\t"+student.getCourse()+"\t\t\t\t"+ student.getYear());
}
}
System.out.println("Enter Student ID to delete: ");
numID = sc.nextInt();
sc.nextLine();
for(int x = 0; x < count && flag == false; x++){
if (numID == stud[x].getNumID()){
temp = x; // get the index
flag = true; // stops the loop if id is found
}
}
for( ; temp < count -1; temp++){
stud[temp]=stud[temp+1];
}
stud[count-1] = null;
--count;
}
else {
System.out.println("Cannot delete [Array is Empty]");
}
}
}
My Student class:
public class Student {
private int numID, year;
private String userName, course;
public Student(int numID, int year, String userName, String course) {
this.numID = numID;
this.year = year;
this.userName = userName;
this.course = course;
}
public int getNumID() {
return numID;
}
public void setNumID(int numID) {
this.numID = numID;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}

You don't need the while loop, if you fix the issue with your for loop. Suppose you entered user IDs 1 to 5, and then entered 1 again. The first iteration of the for loop will find that 1 == stud[0].getNumID(), so you will ask for new student ID. Then you'll get a new input and reset x to 0.
Now, x will be incremented to 1 by the x++ part of the loop, so if you entered 1 again, the loop will never compare 1 to stud[0].getNumID(), since x==1. Therefore the duplicate input will be accepted.
This can be fixed by resetting x to -1:
for(int x = 0; x < count; x++){
if(numID == stud[x].getNumID()) {
System.out.println("The Student ID: " +numID+ " already exist.\nEnter New Student ID: ");
numID = sc.nextInt();
sc.nextLine();
x = -1;
}
}
Of course there are much better ways to check for duplicate IDs (that would be more readable and more efficient). Use a HashSet<Integer> to store all the used IDs, and use the Set to check if a new ID has already been used.
For example:
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
Set<Integer> ids = new HashSet<>();
while (!ids.add(numID)) { // add returns false if numID is already in the Set
System.out.println("The Student ID: " +numID+ " already exist.\nEnter New Student ID: ");
numID = sc.nextInt();
sc.nextLine();
}
...

Related

Add, View, Update, and Delete Student Record using Array

i need help with my code. I am stuck at 2 (View student record), we only allowed to use arrays and not arraylist or linked list. Any advice and help will do.
Heres the instructions:
Write a menu driven program that performs the following:
1.Add record
- can add N students record into the list (ID num, name, course, year)
2.View record
- can view record by ID number, by course, by course and year
- or view all
3.Update record
- can edit/modify the records attribute excluding the ID
4.Delete
- can remove student record
Heres my code:
import java.util.Scanner;
public class StudentArray {
public static void main(String[] args){
getMenu();
}
public static void getMenu( ){
Student[] stud = new Student[100];
Scanner sc = new Scanner(System.in);
int select;
System.out.println("1. Add Student Record");
System.out.println("2. View Student Record");
System.out.println("3. Update Student Record");
System.out.println("4. Delete Student Record");
System.out.println("0. Exit");
select = sc.nextInt();
switch (select){
case 1:
addStud(stud);
getMenu();
break;
case 2:
viewStud(stud);
getMenu();
break;
case 3:
break;
case 4:
break;
case 0:
break;
default:
}
}
public static void addStud(Student[] stud){
Scanner sc = new Scanner(System.in);
int numID, year;
String userName, course;
int addMore;
int i = 0;
do{
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
System.out.println("2. Enter Student Name");
userName = sc.nextLine();
System.out.println("3. Enter Student Course");
course = sc.nextLine();
System.out.println("4. Enter Student Year");
year = sc.nextInt();
stud[i] = new Student(numID, year, userName, course);
++i;
System.out.println("To add another Student Record Press 1");
addMore = sc.nextInt();
}while (addMore == 1 );
}
public static void viewStud(Student[] stud){
for(int x = 0; x < stud.length ; ++x){
System.out.println("1. Student ID: " + stud[x].getNumID());
System.out.println("2. Student Name: " + stud[x].getUserName());
System.out.println("3. Student Course: " + stud[x].getCourse());
System.out.println("4. Student Year: " + stud[x].getYear() + "\n");
}
}
}
My Student Class:
public class Student {
private int numID, year;
private String userName, course;
public Student(int numID, int year, String userName, String course) {
this.numID = numID;
this.year = year;
this.userName = userName;
this.course = course;
}
public int getNumID() {
return numID;
}
public void setNumID(int numID) {
this.numID = numID;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
Hello thank you SNJ,
I remove my getMenu method and put the code in the main instead.But I'm unable to set the Student array and i to static
import java.util.Scanner;
public class StudentArray {
public static void main(String[] args) {
static Student[] stud = new Student[100];
static int i = 0;
Scanner sc = new Scanner(System.in);
while (true) {
int select;
System.out.println("1. Add Student Record");
System.out.println("2. View Student Record");
System.out.println("3. Update Student Record");
System.out.println("4. Delete Student Record");
System.out.println("0. Exit");
select = sc.nextInt();
switch (select) {
case 1:
addStud(stud);
break;
case 2:
viewStud(stud);
break;
case 3:
break;
case 4:
break;
case 0:
return;
default:
System.out.println("Invalid Option");
}
}
}
public static void addStud(Student[] stud) {
Scanner sc = new Scanner(System.in);
int numID, year;
String userName, course;
int addMore;
do {
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
System.out.println("2. Enter Student Name");
userName = sc.nextLine();
System.out.println("3. Enter Student Course");
course = sc.nextLine();
System.out.println("4. Enter Student Year");
year = sc.nextInt();
stud[i] = new Student(numID, year, userName, course);
++i;
System.out.println("To add another Student Record Press 1");
addMore = sc.nextInt();
} while (addMore == 1);
}
public static void viewStud(Student[] stud) {
for (Student element : stud) {
if (null != element) {
System.out.println("1. Student ID: " + element.getNumID());
System.out.println("2. Student Name: " + element.getUserName());
System.out.println("3. Student Course: " + element.getCourse());
System.out.println("4. Student Year: " + element.getYear() + "\n");
}
}
}
You are loosing student value in between method calls.If you make Student array and i as static, it will retain your values between method calls.
import java.util.Scanner;
public class StudentArray {
public static void main(String[] args){
static Student[] stud = new Student[100];
static int i = 0;
public static void main(String[] args) {
getMenu();
}
public static void getMenu() {
Scanner sc = new Scanner(System.in);
while (true) {
int select;
System.out.println("1. Add Student Record");
System.out.println("2. View Student Record");
System.out.println("3. Update Student Record");
System.out.println("4. Delete Student Record");
System.out.println("0. Exit");
select = sc.nextInt();
switch (select) {
case 1:
addStud(stud);
break;
case 2:
viewStud(stud);
break;
case 3:
break;
case 4:
break;
case 0:
return;
default:
System.out.println("Invalid Option");
}
}
}
public static void addStud(Student[] stud) {
Scanner sc = new Scanner(System.in);
int numID, year;
String userName, course;
int addMore;
do {
System.out.println("1. Enter Student ID: ");
numID = sc.nextInt();
sc.nextLine();
System.out.println("2. Enter Student Name");
userName = sc.nextLine();
System.out.println("3. Enter Student Course");
course = sc.nextLine();
System.out.println("4. Enter Student Year");
year = sc.nextInt();
stud[i] = new Student(numID, year, userName, course);
++i;
System.out.println("To add another Student Record Press 1");
addMore = sc.nextInt();
} while (addMore == 1);
}
public static void viewStud(Student[] stud) {
for (Student element : stud) {
if (null != element) {
System.out.println("1. Student ID: " + element.getNumID());
System.out.println("2. Student Name: " + element.getUserName());
System.out.println("3. Student Course: " + element.getCourse());
System.out.println("4. Student Year: " + element.getYear() + "\n");
}
}
}

Beginner Java: Understanding error message: Exception in thread "main" java.util.NoSuchElementException

I am very new to Java and I'm having trouble understanding the errors I get from these classes. Even though I have searched it up throughout stackoverflow and various other sites, I am not able to grasp the meaning of them. Any help would be great in understanding these errors messages.
Main Class
import java.io.IOException;
import java.util.Scanner;
public class Assignment4 {
public static void main (String[] args) throws IOException{
int command = 0;
Scanner kb=new Scanner(System.in);
System.out.print("Enter the name of the input file:Enter data.txt: ");
String fileName=kb.next();
ClassRoll cr = new ClassRoll("data.txt");
cr.display();
prompt();
System.out.print("Enter a command: ");
String ans=kb.next();
while (!(ans.equalsIgnoreCase("q") || ans.equalsIgnoreCase("quit")))
{
if(!(ans.equalsIgnoreCase("a") ||ans.equalsIgnoreCase("add") ||
ans.equalsIgnoreCase("sa") || ans.equalsIgnoreCase("average") ||
ans.equalsIgnoreCase("sn") || ans.equalsIgnoreCase("names") ||
ans.equalsIgnoreCase("r") || ans.equalsIgnoreCase("remove") ||
ans.equalsIgnoreCase("s") || ans.equalsIgnoreCase("save") ||
ans.equalsIgnoreCase("c1") || ans.equalsIgnoreCase("change1") ||
ans.equalsIgnoreCase("c2") || ans.equalsIgnoreCase("change2") ||
ans.equalsIgnoreCase("c3") || ans.equalsIgnoreCase("change3") ||
ans.equalsIgnoreCase("f") || ans.equalsIgnoreCase("find") ||
ans.equalsIgnoreCase("d") || ans.equalsIgnoreCase("display")))
System.out.println("Bad Command");
else
switch (command)
{
case 1: cr.add();
break;
case 2: cr.sortAverage();
cr.display();
break;
case 3: cr.sortNames();
cr.display();
break;
case 4: cr.remove();
cr.display();
break;
case 5: cr.save();
cr.display();
break;
case 6: ClassRoll.changeScore1();
cr.display();
break;
case 7: ClassRoll.changeScore2();
cr.display();
break;
case 8: ClassRoll.changeScore3();
cr.display();
break;
case 9: Student s=cr.find();
if (s == null)
System.out.println("Student not found");
else System.out.println(s.toString());
break;
case 10: cr.display();
break;
case 11 : System.out.println("Are you sure you want to quit? "
+ "Yes or No");
String quit = kb.next();
if (quit.equalsIgnoreCase("y") ||
quit.equalsIgnoreCase("yes")){
System.exit(0);
}
else
{
prompt();
System.out.print("Enter a command --> ");
ans=kb.next();
}
cr.save();
System.out.println("Thank you for using this program");
}
}
}
public static void prompt(){
System.out.println("Enter one of the following commands: ");
System.out.println("a or add to add a student in the class roll");
System.out.println("sa or average to sort the students based "
+ "on their average");
System.out.println("sn or names to sort the students "
+ "based on their last names");
System.out.println("r or remove to remove a student from the class roll");
System.out.println("s or save to save the list of students back to the input"
+ "datafile");
System.out.println("d or display to display the class roll");
System.out.println("c1 or change1 to change score 1 of a student");
System.out.println("c2 or change2 to change score 2 of a student");
System.out.println("c3 or change3 to change score 3 of a student");
System.out.println("d or display to display the class roll");
System.out.println("q or quit to exit the program");}
Class Roll
public class ClassRoll {
ArrayList students = new ArrayList();
private String title;
private String fileName;
public ClassRoll(String f) throws IOException{
//acquires title of file
Scanner fileScan;
Scanner lineScan;
String line;
fileName = f;
fileScan = new Scanner(new File(f));
title = fileScan.nextLine();
System.out.println("Course Title: " + title);
while (fileScan.hasNext()) {
line = fileScan.nextLine();
lineScan = new Scanner(line);
lineScan.useDelimiter("\t");
String lastName = lineScan.next();
String firstName = lineScan.next();
Student name = new Student(firstName, lastName);
name.setScore1(lineScan.nextInt());
name.setScore2(lineScan.nextInt());
name.setScore3(lineScan.nextInt());
students.add(name);
ClassRoll cr = new ClassRoll("data.txt");
cr.display();
}
}
void display(){
double classAverage = 0.0;
DecimalFormat f = new DecimalFormat("0.00");
System.out.println("\t" + title );
for (int i = 0; i < students.size(); i++){
//fix this part of the code, get average
Student name = (Student) students.get(i);
System.out.println(name.toString());
System.out.println("\n" + f.format(name.getAverage()));
classAverage = classAverage + name.getAverage();
}
System.out.println("\t\t\t" + f.format(classAverage / students.size()));
}
void add(){
Scanner input = new Scanner(System.in);
System.out.print("First Name: ");
String firstName = input.next();
System.out.print("Last Name: ");
String lastName = input.next();
System.out.print("Score 1: ");
int score1 = input.nextInt();
System.out.print("Score 2: ");
int score2 = input.nextInt();
System.out.print("Score 3: ");
int score3 = input.nextInt();
Student s = new Student(firstName, lastName);
s.setScore1(score1);
s.setScore2(score2);
s.setScore3(score3);
students.add(s);
}
static void changeScore1(){
Scanner kb = new Scanner(System.in);
System.out.println("Student's first Name: ");
String f = kb.next();
System.out.println("Student's last Name: ");
String n = kb.next();
System.out.println("Student's first Exam score: ");
Integer score1 = kb.nextInt();
System.out.println("New score of Exam 1: ");
Integer newScore1 = kb.nextInt();
score1 = newScore1;
}
static void changeScore2(){
Scanner kb = new Scanner(System.in);
System.out.println("Student's first Name: ");
String f = kb.next();
System.out.println("Student's last Name: ");
String n = kb.next();
System.out.println("Student's second Exam score: ");
Integer score2 = kb.nextInt();
System.out.println("New score of Exam 2: ");
Integer newScore2 = kb.nextInt();
score2 = newScore2;
}
static void changeScore3(){
Scanner kb = new Scanner(System.in);
System.out.println("Student's first Name: ");
String f = kb.next();
System.out.println("Student's last Name: ");
String n = kb.next();
System.out.println("Student's third Exam score: ");
Integer score3 = kb.nextInt();
System.out.println("New score of Exam 3: ");
Integer newScore3 = kb.nextInt();
score3 = newScore3;
}
private int search(String fn, String ln) {
int i = 0;
while (i < students.size()) {
Student s = (Student) students.get(i);
if (s.equals(fn, ln)) {
return i;
} else {
i++;
}}
return -1;
}
Student find(){
Scanner input = new Scanner(System.in);
System.out.print("First Name: ");
String firstName = input.next();
System.out.print("Last Name: ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
return (Student) students.get(i);
} else {
return null;
}
}
void remove(){
Scanner input = new Scanner(System.in);
System.out.print("First Name: ");
String firstName = input.next();
System.out.print("Last Name: ");
String lastName = input.next();
int i = search(firstName, lastName);
if (i >= 0) {
students.remove(i);
} else {
System.out.println("Student was not found within the list");
}
}
void sortAverage(){
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.getAverage() < s2.getAverage()) {
students.set(i, s2);
students.set(j, s1);
}
}}
}
void sortNames(){
for (int i = 0; i < students.size() - 1; i++) {
for (int j = i + 1; j < students.size(); j++) {
Student s1 = (Student) students.get(i);
Student s2 = (Student) students.get(j);
if (s1.compareTo(s2) > 0) {
students.set(i, s2);
students.set(j, s1);
}
}}}
void save() throws IOException{
OutputStream file = new FileOutputStream("data.txt");
OutputStream buffer = new BufferedOutputStream(file);
ObjectOutput output = new ObjectOutputStream(buffer);
PrintWriter out = new PrintWriter(fileName);
out.println(title);
for (int i = 0; i < students.size(); i++) {
Student s = (Student) students.get(i);
out.println(s.toString());
output.close();
}}
}
Error Messages
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ClassRoll.<init>(ClassRoll.java:38)
at Assignment4.main(Assignment4.java:16)
hasNext() is a precondition for next(), or else you will get those exceptions. So hasNext() must match the corresponding next()

Scanner ignoring the String "name"

I am trying to take user input for name, last name, phone number and age.
For some odd reason the scanner is skipping name but none of the other variables.
Can someone point out my mistake please? I can't figure it out.
import java.util.Scanner;
public class Lab2{
String [][] info = new String [10][4];
public static void main(String [] args){
new Lab2();
}
public Lab2(){
Scanner input = new Scanner(System.in);
System.out.println();
System.out.println("Student contact Interface");
System.out.println("Please select a number from the options below:");
while(true){
System.out.println("1: Add a new contact.");
System.out.println("2: Remove an existing contact.");
System.out.println("3: Display the contact list.");
System.out.println("0: Exit the contact list.");
int options = input.nextInt();
String name, lastName, number, age;
switch(options){
case 1:
System.out.println("Please enter the name: ");
name = input.nextLine(); // This is the String var that is not accepting input from...
System.out.println("Please enter the last name: ");
lastName = input.nextLine();
System.out.println("Please enter the phone number: ");
number = input.nextLine();
System.out.println("Please enter the age (eg. 25): ");
age = input.nextLine();
addStudent(name, lastName, number, age);
break;
case 2:
System.out.println("\nEnter the name to remove: ");
String delName = input.nextLine();
System.out.println("\nEnter the last name to remove: ");
String delLastName = input.nextLine();
remove(delName, delLastName);
break;
case 3:
display();
break;
case 0:
System.out.println("Thank you for using the contact Database.");
System.exit(0);
}
}
}
public void addStudent (String name, String lastName, String number, String age){
boolean infoInserted = false;
for(int i = 0; i < 10; i++){
if(info[i][0] == null || info[i][0].equals(null)){
info[i][0] = name;
info[i][1] = lastName;
info[i][2] = number;
info[i][3] = age;
infoInserted = true;
break;
}
}
if(infoInserted){
System.out.println("\nContact saved.\n");
}
else{
System.out.println("\nYour database is full.\n");
}
}
public void remove(String delName, String delLastName){
boolean removed = false;
int i = 0;
for (i = 0; i < 10; i++) {
if (info[i][0] != null && !info[i][0].equals(null)) {
if (info[i][0].equals(delName) && info[i][1].equals(delLastName)) {
while (i < 9) {
info[i][0] = info[i + 1][0];
info[i][1] = info[i + 1][1];
info[i][2] = info[i + 1][2];
info[i][3] = info[i + 1][3];
i++;
}
info[9][0] = null;
info[9][1] = null;
info[9][2] = null;
info[9][3] = null;
removed = true;
break;
}
}
}
if (removed) {
System.out.println("Contact removed.");
}
else {
System.out.println("Contact was not found.");
}
}
public void display (){
for (int i = 0; i < 10; i++) {
if (info[i][0] != null && !info[i][0].equals(null)) {
System.out.println("Contact " + (i + 1)+ ":");
System.out.println("\t" + info[i][0]);
System.out.println("\t" + info[i][1]);
System.out.println("\tPhone Number:" + info[i][2]);
System.out.println("\tAge:" + info[i][3]);
}
}
}
}
Add a
input.nextLine();
after your
int options = input.nextInt();
This is because:
nextInt method does not read the last newline character (of your integer input)
that newline is consumed in the next call to nextLine
causing name 'to be skipped'
so you need to 'flush away' the newline character after getting the integer input
Another option:
Take in the entire line, using input.nextLine()
Get the integer value using Integer.parseInt() to extract the integer value
It is skipping name because , input.nextInt() wont go to next input line.
You can use
int option=Integer.parseInt(input.nextLine());
then it wont skip name.

Getting a Null Pointer Exception and not sure how to fix it [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am creating a tester class for a simple input database program. I do not have to store information nor delete anything, but there are two arrays in my the class I am running my tester class for.
This is my tester class:
import java.util.Scanner;
public class Asst_3 {
private static Scanner keyboard;
public Asst_3(){
this.keyboard = new Scanner(System.in);
}
public static void main(String[]args){
Policy insurance = new Policy();
insurance.setCustomerLast(null);
insurance.setCustomerFirst(null);
insurance.setPolicyNumber();
insurance.setAge();
insurance.setAccidentNumber();
insurance.setPremiumDueDate(00,00,0000);
//insurance.toString();
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
Scanner keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(null);
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.getPolicyNumber();
System.out.println("Customer's Policy Number is: " + keyboard.nextInt());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.getCustomerLast();
System.out.println("Customer's Last Name is: " + keyboard.nextInt());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.getCustomerFirst();
System.out.println("Customer's First Name is: " + keyboard.nextInt());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.getAge();
System.out.println("Customer's Age is: " + keyboard.nextInt());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.getAccidentNumber();
System.out.println("Customer's Amount of Accidents is: " + keyboard.nextInt());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.getPremiumDueDate();
System.out.println("Customer's Next Due Date is: " + keyboard.nextInt());
insurance.toString();
showMenuOptions();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
}
And the Null Pointer Error:
Exception in thread "main" java.lang.NullPointerException
at Asst_3.newPolicy(Asst_3.java:55)
at Asst_3.intiateMenuSelection(Asst_3.java:40)
at Asst_3.main(Asst_3.java:35)
This is the class I'm making my tester for:
import java.util.*;
public class Policy {
private int policyNumber;
private int age;
private int accidentNumber;
private String customerLast;
private String customerFirst;
private int [] months;
private int [] premiumDueDate;
public Policy() {
this.policyNumber = 0;
this.age = 0;
this.accidentNumber = 0;
this.customerLast = "";
this.customerFirst = "";
this.premiumDueDate = new int [3];
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
this.months = new int [12];
this.months[0] = this.months[2] = this.months[4] = this.months[6] = this.months[7] = this.months[9] = this.months[11] = 31;
this.months[1] = 28;
this.months[3] = this.months[5] = this.months[8] = this.months[10] = 30;
}
public int getPolicyNumber(){
return this.policyNumber;
}
public void setPolicyNumber(){
if(policyNumber < 1000){
policyNumber = 0;
}
if(policyNumber > 9999){
policyNumber = 0;
}
}
public int[] getPremiumDueDate(){
return this.premiumDueDate;
}
public void setPremiumDueDate(int month, int day, int year){
this.premiumDueDate[0] = month;
this.premiumDueDate[1] = day;
this.premiumDueDate[2] = year;
if(month < 0||month >= 12)
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
else if(day < 0 || day > this.months[month])
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
}
public int getAge(){
return this.age;
}
public void setAge(){
this.age = 0;
}
public int getAccidentNumber(){
return this.accidentNumber;
}
public void setAccidentNumber(){
this.accidentNumber = 0;
}
public String getCustomerLast(){
return this.customerLast;
}
public void setCustomerLast(String customerLast){
this.customerLast = customerLast;
}
public String getCustomerFirst(){
return this.customerFirst;
}
public void setCustomerFirst(String customerFirst){
this.customerFirst = customerFirst;
}
public String toString(){
return "\n Policy Number: " + this.policyNumber + "\n Customer Last Name: " + this.customerLast + "\n Customer First Name: " + this.customerFirst
+ "\n Customer age: " + this.age + "\n Number of Accidents in Past Three Years: " + this.accidentNumber + "\n Premium Due Date: " + this.premiumDueDate;
}
}
Thank you everyone, your amazing!
Here's my edited code:
The Tester
import java.util.Scanner;
public class Asst_3 {
private static Scanner keyboard;
public Asst_3(){
this.keyboard = new Scanner(System.in);
}
public static void main(String[]args){
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(new Policy());
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.setPolicyNumber(poliNum);
System.out.println("Customer's Policy Number is: " + insurance.getPolicyNumber());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.setCustomerLast(custLast);
System.out.println("Customer's Last Name is: " + insurance.getCustomerLast());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.setCustomerFirst(custFirst);
System.out.println("Customer's First Name is: " + insurance.getCustomerFirst());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.setAge(custAge);
System.out.println("Customer's Age is: " + insurance.getAge());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.setAccidentNumber(custAccident);
System.out.println("Customer's Amount of Accidents is: " + insurance.getAccidentNumber());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.setPremiumDueDate(dueDate, dueDate, dueDate);
System.out.println("Customer's Next Due Date is: " + insurance.getPremiumDueDate());
insurance.toString();
returnToMenu();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
}
And the class being tested:
import java.util.*;
public class Policy {
private int policyNumber;
private int age;
private int accidentNumber;
private String customerLast;
private String customerFirst;
private int [] months;
private int [] premiumDueDate;
public Policy() {
this.policyNumber = 0;
this.age = 0;
this.accidentNumber = 0;
this.customerLast = "";
this.customerFirst = "";
this.premiumDueDate = new int [3];
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
this.months = new int [12];
this.months[0] = this.months[2] = this.months[4] = this.months[6] = this.months[7] = this.months[9] = this.months[11] = 31;
this.months[1] = 28;
this.months[3] = this.months[5] = this.months[8] = this.months[10] = 30;
}
public int getPolicyNumber(){
return this.policyNumber;
}
public void setPolicyNumber(int policyNumber){
if(policyNumber < 1000){
policyNumber = 0;
}
if(policyNumber > 9999){
policyNumber = 0;
}
}
public int[] getPremiumDueDate(){
return this.premiumDueDate;
}
public void setPremiumDueDate(int month, int day, int year){
this.premiumDueDate[0] = month;
this.premiumDueDate[1] = day;
this.premiumDueDate[2] = year;
if(month < 0||month >= 12)
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
else if(day < 0 || day > this.months[month])
{
this.premiumDueDate[0] = 0;
this.premiumDueDate[1] = 0;
this.premiumDueDate[2] = 0;
}
}
public int getAge(){
return this.age;
}
public void setAge(int age){
this.age = 0;
}
public int getAccidentNumber(){
return this.accidentNumber;
}
public void setAccidentNumber(int accidentNumber){
this.accidentNumber = 0;
}
public String getCustomerLast(){
return this.customerLast;
}
public void setCustomerLast(String customerLast){
this.customerLast = customerLast;
}
public String getCustomerFirst(){
return this.customerFirst;
}
public void setCustomerFirst(String customerFirst){
this.customerFirst = customerFirst;
}
public String toString(){
return "\n Policy Number: " + this.policyNumber + "\n Customer Last Name: " + this.customerLast + "\n Customer First Name: " + this.customerFirst
+ "\n Customer age: " + this.age + "\n Number of Accidents in Past Three Years: " + this.accidentNumber + "\n Premium Due Date: " + this.premiumDueDate;
}
}
But now I have a new error after executing the program:
Welcome to Drive-Rite Insurance Company
Choose a menu option:
(1) Create New Policies
(2) Search by age
(3) Search by due date
(4) Exit
Input Option Number ---> Exception in thread "main" java.lang.NullPointerException
at Asst_3.main(Asst_3.java:23)
Here's an updated version with that NPE fixed:
import java.util.Scanner;
public class Asst_3 {
private static Scanner keyboard;
public static void main(String[]args){
System.out.println("Welcome to Drive-Rite Insurance Company");
showMenuOptions();
this.keyboard = new Scanner(System.in);
int choice = keyboard.nextInt();
intiateMenuSelection(choice);
}
private static void intiateMenuSelection(int selectedOption) {
switch (selectedOption){
case 1: newPolicy(new Policy());
break;
case 2: returnFromAge();
break;
case 3: returnFromDue();
break;
case 4: System.out.println("Goodbye");
System.exit(0);
break;
default: break;
}
}
private static void newPolicy(Policy insurance) {
System.out.println("Enter Customer's Policy Number: ");
int poliNum = keyboard.nextInt();
insurance.setPolicyNumber(poliNum);
System.out.println("Customer's Policy Number is: " + insurance.getPolicyNumber());
System.out.println("Enter Customer's Last Name: ");
String custLast = keyboard.nextLine();
insurance.setCustomerLast(custLast);
System.out.println("Customer's Last Name is: " + insurance.getCustomerLast());
System.out.println("Enter Customer's First Name: ");
String custFirst = keyboard.nextLine();
insurance.setCustomerFirst(custFirst);
System.out.println("Customer's First Name is: " + insurance.getCustomerFirst());
System.out.println("Enter Customer's Age: ");
int custAge = keyboard.nextInt();
insurance.setAge(custAge);
System.out.println("Customer's Age is: " + insurance.getAge());
System.out.println("Enter Customer's Amount of Previous Accident Reaports in Past 3 years: ");
int custAccident = keyboard.nextInt();
insurance.setAccidentNumber(custAccident);
System.out.println("Customer's Amount of Accidents is: " + insurance.getAccidentNumber());
System.out.println("Enter Customer's next Premium Due Date: ");
int dueDate = keyboard.nextInt();
insurance.setPremiumDueDate(dueDate, dueDate, dueDate);
System.out.println("Customer's Next Due Date is: " + insurance.getPremiumDueDate());
insurance.toString();
returnToMenu();
}
private static void returnFromDue() {
showMenuOptions();
}
private static void returnFromAge() {
showMenuOptions();
}
private static void returnToMenu() {
intiateMenuSelection(0);
}
private static void showMenuOptions() {
System.out.println("Choose a menu option: ");
System.out.println("----------------------------------------");
System.out.println("(1) Create New Policies");
System.out.println("(2) Search by age");
System.out.println("(3) Search by due date");
System.out.println("(4) Exit");
System.out.print("Input Option Number ---> ");
}
}
The errors are I'm having issues with they keyboard variables.
null pointer occurring in
private static void newPolicy(Policy insurance)
this method. For these lines
insurance.getPolicyNumber();
insurance.get....();
insurance.get....();
because the reference/object insurance coming as a parameter from where its being called . in you case you are passing null to the method
newPolicy(null); //try to pass a reference of Policy like 'newPolicy(new Policy())' .
You declare keybord twice.
remove the Scanner from this line:
Scanner keyboard = new Scanner(System.in);
So you have:
keyboard = new Scanner(System.in);
You're shadowing you variables, that is, you've declared keyboard as a class variable
public class Asst_3 {
private static Scanner keyboard;
But in the main, you've re-declared it as a local variable...
Scanner keyboard = new Scanner(System.in);
Which means that the class variable is still null when you call newPolicy.
Start by removing the re-declaration...
//Scanner keyboard = new Scanner(System.in);
keyboard = new Scanner(System.in);
Which will lead you smack bang into you next NullPointerException in newPolicy
insurance.getPolicyNumber();
Caused by the fact that you call the method passing it a null value...
newPolicy(null);
I'll leave you to fix that ;)
Hint: newPolicy should take no parameters and should return an new instance of Policy which can then manipulated by the other methods ;)
The insurance that you are passing to newPolicy is null
case 1: newPolicy(null);
hence
insurance.getPolicyNumber();
will throw a NPE

Java: setting variable on object array

public class ParkingLotApplication {
static Scanner input = new Scanner(System.in);
public static ParkingDescription[][] ParkingLot = new ParkingDescription[3][15];
public StudentDescription StudDesc = new StudentDescription();
static int i = 0;
static int j = 0;
static int parkLevel = 0;
static int parkSlot = 0;
public static void main(String[] args) {
// TODO: Add your code here
ParkingLotApplication PA = new ParkingLotApplication();
PA.menu();
}
public void menu() {
Scanner input = new Scanner(System.in);
System.out.println("WELCOME TO CAR PARK SYSTEM");
System.out.println("Enter your name: ");
String nm = input.nextLine();
System.out.println("Enter your password: ");
int pass = input.nextInt();
if ((nm.equals("admin12")) && (pass == 12345)) {
Login();
} else {
menu();
}
}
public void Login() {
System.out.println("|----------------------------------|");
System.out.println("| Admin Menu |");
System.out.println("|----------------------------------|");
System.out.println("| N- New Registration |");
System.out.println("| U- Update Data |");
System.out.println("|----------------------------------|");
char ch = input.next().charAt(0);
switch (ch) {
case 'N':
case 'n':
Reg();
break;
case 'U':
case 'u':
UpdatePark();
break;
default:
System.out.println("Choose Again!");
Login();
break;
}
}
public void Reg() {
System.out.println();
System.out.println(" **Parking Lot** ");
System.out.println(" ________________________________________________________________________________");
for (i = 0; i < 3; i++) {
for (j = 0; j < 15; j++) {
ParkingLot[i][j] = new ParkingDescription();
System.out.print(" * " + ParkingLot[i][j].getStatus());
}
System.out.println();
System.out.println(" ********************************************************************************");
}
System.out.println("Please insert number 1-3 to choose the parking level");
parkLevel = input.nextInt();
System.out.println("Please insert number 1-15 to choose the parking slot");
parkSlot = input.nextInt();
//check available
if (parkLevel == 1) {
ParkingLot[0][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[0][parkSlot - 1].getAvailable() == true) {
System.out.println("Please Enter tp: ");
int tp = input.nextInt();
System.out.println("Please Enter First Name: ");
String ft = input.next();
System.out.println("Please Enter Last Name: ");
String lt = input.next();
System.out.println("Please Enter Contact Number: ");
int cn = input.nextInt();
System.out.println("Please Enter Email Address: ");
String ea = input.next();
System.out.println("Please Enter Car Number: ");
String cnb = input.next();
System.out.println("Please Enter Date Registered : ");
int date = input.nextInt();
StudDesc.setStudDesc(tp, ft, lt, cn, ea, cnb, date);
int pID = (parkLevel * 1000) + parkSlot;
ParkingLot[0][parkSlot - 1].setPark(pID, false, StudDesc);
System.out.println("Thanks");
menu();
} else {
System.out.println("Sorry");
menu();
}
} else if (parkLevel == 2) {
ParkingLot[1][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[1][parkSlot - 1].getAvailable() == true) {
System.out.println("Please Enter tp: ");
int tp = input.nextInt();
System.out.println("Please Enter First Name: ");
String ft = input.next();
System.out.println("Please Enter Last Name: ");
String lt = input.next();
System.out.println("Please Enter Contact Number: ");
int cn = input.nextInt();
System.out.println("Please Enter Email Address: ");
String ea = input.next();
System.out.println("Please Enter Car Number: ");
String cnb = input.next();
System.out.println("Please Enter Date Registered : ");
int date = input.nextInt();
StudDesc.setStudDesc(tp, ft, lt, cn, ea, cnb, date);
int pID = (parkLevel * 1000) + parkSlot;
ParkingLot[1][parkSlot - 1].setPark(pID, false, StudDesc);
System.out.println("Thanks");
menu();
} else {
System.out.println("Sorry");
menu();
}
} else if (parkLevel == 3) {
ParkingLot[2][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[2][parkSlot - 1].getAvailable() == true) {
System.out.println("Please Enter tp: ");
int tp = input.nextInt();
System.out.println("Please Enter First Name: ");
String ft = input.next();
System.out.println("Please Enter Last Name: ");
String lt = input.next();
System.out.println("Please Enter Contact Number: ");
int cn = input.nextInt();
System.out.println("Please Enter Email Address: ");
String ea = input.next();
System.out.println("Please Enter Car Number: ");
String cnb = input.next();
System.out.println("Please Enter Date Registered : ");
int date = input.nextInt();
StudDesc.setStudDesc(tp, ft, lt, cn, ea, cnb, date);
int pID = (parkLevel * 1000) + parkSlot;
ParkingLot[2][parkSlot - 1].setPark(pID, false, StudDesc);
System.out.println("Thanks");
menu();
} else {
System.out.println("Sorry");
menu();
}
}
}
public void UpdatePark() {
System.out.println();
System.out.println(" **Parking Lot** ");
System.out.println(" ________________________________________________________________________________");
for (i = 0; i < 3; i++) {
for (j = 0; j < 15; j++) {
ParkingLot[i][j] = new ParkingDescription();
System.out.print(" * " + ParkingLot[i][j].getStatus());
}
System.out.println();
System.out.println(" ********************************************************************************");
}
System.out.println("Please insert number 1-3 to choose the parking level");
parkLevel = input.nextInt();
System.out.println("Please insert number 1-15 to choose the parking slot");
parkSlot = input.nextInt();
//check available
if (parkLevel == 1) {
ParkingLot[0][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[0][parkSlot - 1].getAvailable() == false) {
ParkingLot[0][parkSlot - 1].showDetails();
menu();
} else {
System.out.println("Sorry");
menu();
}
} else if (parkLevel == 2) {
ParkingLot[1][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[1][parkSlot - 1].getAvailable() == true) {
ParkingLot[1][parkSlot - 1].showDetails();
menu();
} else {
System.out.println("Sorry");
menu();
}
} else if (parkLevel == 3) {
ParkingLot[2][parkSlot - 1] = new ParkingDescription();
if (ParkingLot[2][parkSlot - 1].getAvailable() == true) {
ParkingLot[2][parkSlot - 1].showDetails();
menu();
} else {
System.out.println("Sorry");
menu();
}
}
}
}
//Class parking description
public class ParkingDescription {
public static int StudID, ParkSpaceID, DReg;
public static String Status, CNum;
public static Boolean Available = true;
public ParkingDescription() {
// TODO: Add your code here
}
public void setPark(int parkSpaceID, Boolean available, StudentDescription StDe)
{
this.StudID = StDe.getStudentID();
this.CNum = StDe.getCarNumber();
this.DReg = StDe.getDateReg();
this.ParkSpaceID = parkSpaceID;
this.Available = available;
}
public Boolean getAvailable()
{
return Available;
}
public String getStatus()
{
if(Available == false){
return "1";
} else {
return "0";
}
}
public void showDetails()
{
//generate report
System.out.println("Student ID : TP"+StudID);
System.out.println();
System.out.println("Car Number : "+CNum);
System.out.println();
System.out.println("Parking Space : L"+ParkSpaceID);
System.out.println();
System.out.println("Date Register : "+DReg);
}
}
//Student class
public class StudentDescription {
public int StudentID, CNumber, DateReg;
public String FName, LName, EMail, CarNum;
public StudentDescription() {
// TODO: Add your code here
}
public void setStudDesc(int studentID, String fName, String lName, int cNumber, String eMail, String carNum, int dateReg)
{
this.StudentID = studentID;
this.FName = fName;
this.LName = lName;
this.CNumber = cNumber;
this.EMail = eMail;
this.CarNum = carNum;
this.DateReg = dateReg;
}
public int getStudentID()
{
return this.StudentID;
}
public String getCarNumber()
{
return this.CarNum;
}
public int getDateReg()
{
return this.DateReg;
}
}
I have this problem. when i want to set one parking detail object into ParkingLot array, the array is insert same data information on all of array. the output suppose to be like this:
**Parking Lot**
* 1 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0
* 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0
* 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0 * 0
but I got all the output being set to 1. So how to solve this problem? thanks..
There's still lots of code that you haven't shown, for example, the code for the ParkingDescription class. But based on what you HAVE shown ...
In the chunk of code that prints out all the statuses, (which for some reason, you've coded twice - once in Reg and once in UpdatePark), you are populating your array with 45 new ParkingDescription objects, and printing the status of each one. That is, you're throwing away all the ParkingDescription objects that you had previously, and only printing brand new objects. You really don't want to do that, because it's the ParkingDescription objects that store all the data that the user has entered.
I guess you're getting all 1s because 1 is the status of a new ParkingDescription.
UPDATE
Now that you've shown your ParkingDescription class, I see that the problem is that you've declared its fields as static. That means that there's only one copy of each field, shared between all the instances of this class. Remove the word static from the field declarations, and the problem should be fixed.
And the next time you post a question on Stack Overflow, I strongly recommend posting ALL the code when you first post the question. Don't just post the part where YOU think the bug is, because you waste everyone's time if you're wrong.

Categories

Resources