Null Pointer Exception using Object Arrays - arrays

I am planning to make an airline system. I have initialized the array using initSeats but it still throws back the NPE error. It happens when i call the seatChecker() from bookMenu.
public void initSeats(){
for(int b = 0; b < seatList.length; b++)
{
initC.setName("null");
initC.setEmail("null");
initC.setCreditNo(0);
initC.setAddress("null");
initC.setPassportNo("null");
seatList[b] = new Seat('A', 0, "null", 0.0, "Available", initC);
}
for(int d = 0; d <= 24; d++)
{
seatList[d].setSeatLetter('A');
seatList[d].setSeatNo(d);
}
for(int n = 25; n <= 48; n++)
{
seatList[n].setSeatLetter('B');
seatList[n].setSeatNo(n);
}
for(int m = 49; m <= 72; m++)
{
seatList[m].setSeatLetter('C');
seatList[m].setSeatNo(m);
}
for(int t = 73; t <= 96; t++)
{
seatList[t].setSeatLetter('D');
seatList[t].setSeatNo(t);
}
for(int q = 97; q <= 120; q++)
{
seatList[q].setSeatLetter('E');
seatList[q].setSeatNo(q);
}
for(int v = 121; v < 144; v++)
{
seatList[v].setSeatLetter('F');
seatList[v].setSeatNo(v);
}
for(int x = 0; x <= 48; x++)
{
seatList[x].setSection("Front");
seatList[x].setPrice(500);
}
for(int j = 49; j <= 96; j++)
{
seatList[j].setSection("Middle");
seatList[j].setPrice(250);
}
for(int u = 97; u < 144; u++)
{
seatList[u].setSection("Back");
seatList[u].setPrice(100);
}
}
public void seatChecker(int index)
{
String status = seatList[index].getStatus();
if(status.equalsIgnoreCase("Available")){
System.out.println("Seat is Available.");
}else{
System.out.println("Seat is not Available. Please Pick Another Seat.");
bookMenu();
}
}
public void bookMenu()
{
int choice1 = 0;
int index;
System.out.println("Where do you want to be seated?");
System.out.println("[1] Front");
System.out.println("[2] Middle");
System.out.println("[3] Back");
choice1 = sc.nextInt();
sc.nextLine();
if(choice1 == 1){
System.out.print("Choose a seat number (0 - 48): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else if(choice1 == 2){
System.out.println("Choose a seat number (49 - 96): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else if(choice1 == 3){
System.out.println("Choose a seat number (97 - 144): ");
index = sc.nextInt();
sc.nextLine();
seatChecker(index);
}else
{
System.out.println("Invalid Choice. Going back to Menu.");
MainMenu();
}
}
Null Pointer Exception Code
Exception in thread "main" java.lang.NullPointerException
at pkg.Airlines.AirlineUI.seatChecker(AirlineUI.java:132)
Seat Class
public class Seat{
private char seatLetter;
private int seatNo;
private String section;
private double price;
private String status;
private Customer customerDetails;
public Seat(char seatLetter, int seatNo, String section, double price, String status, Customer details)
{
this.seatLetter = seatLetter;
this.seatNo = seatNo;
this.section = section;
this.price = price;
this.status = status;
this.customerDetails = details;
}
public Customer getCustomerDetails() {
return customerDetails;
}
public void setCustomerDetails(Customer customerDetails) {
this.customerDetails = customerDetails;
}
public char getSeatLetter() {
return seatLetter;
}
public void setSeatLetter(char seatLetter) {
this.seatLetter = seatLetter;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getSeatNo() {
return seatNo;
}
public void setSeatNo(int seatNo) {
this.seatNo = seatNo;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
}

Probably the problems are this two line :
String status = seatList[index].getStatus();
if(status.equalsIgnoreCase("Available"))
First thing could be seatList[index] is not initialized . Once you declare an array of references as :
Seat[] array = new Seat[10];
The array contains 10 null references for Seat object . You need to instantiate them before using them :
Seat[0] = new Seat();
Second potential problem will be, this check :
if(status.equalsIgnoreCase("Available"))
Replace it to :
if("Available".equalsIgnoreCase(status))
to avoid any NullPointerException in case status is null.
P.S. Please show us the Seat class to understand your problem better.

Well is quite simple resolve a Null Pointer Exception.
Probably in one of the index of seatList there isn't a value.

Related

Need help on solving this Arrays problem using java

Make an array of integer (score) with 10 members. Randomize the
content with value between 0-100. For each of the member of array,
visualize the value using “-” for each ten. For example: score[0] = 55 will be visualized as “-----" (Using Java).
public class w9lab1 {
public static void main(String args[]) {
double[] temperature = new double[7];
for (int i = 0; i < 7; i++) {
temperature[i] = Math.random()*100;
}
for (int i = 0; i < 7; i++) {
System.out.println(temperature[i]);
}
double totalTemperature = 0;
for (int i = 0; i < 7 ; i++) {
totalTemperature += temperature[i];
}
double maxTemperature = temperature[0];
for (int i = 1; i < 7; i++){
if (temperature[i] > maxTemperature){
maxTemperature = temperature[i];
}
}
System.out.println("Temperatur maximum adalah " + maxTemperature);
}
}
import java.util.Random;
import java.util.Arrays;
public class w9lab1 {
public static void main(String[] args) {
Random random = new Random();
int[] score = new int[10];
for (int i = 0; i < score.length; i++) {
score[i] = random.nextInt(101);
for (int n = 1; n <= score[i] / 10; n++)
System.out.print('-');
System.out.println();
}
System.out.println(Arrays.toString(score));
}
}

2d array of type Space

I'm trying to make a 9x9 grid of Spaces with 1-10 int values. I'm using the java n-ide app, and am getting a successful compilation, but it's not printing any values.
class Space {
int one = 1;
int two = 2;
...
int ten = 10;
}
class green {
Space[][] board = new Space[9][9];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j] = new Space();
System.out.println(board[i][j].one);
}
}
}
I think you can just refactor your Space class to just hold a primitive integer value:
class Space {
private int value;
private static final String MSG = "Space values must be between 1 and 10 inclusive";
public Space() { }
public Space(int value) {
// prevent spaces from being created with illegal values
if (value < 1 || value > 10) {
throw new IllegalArgumentException(MSG);
}
this.value = value;
}
public int getValue() {
return value;
}
}
Then, in your consuming class, use the Space class:
class Green {
private Space[][] board = new Space[9][9];
for (int i=0; i < board.length; i++) {
for (int j=0; j < board[i].length; j++) {
// maybe get a value from somewhere and use it below
board[i][j] = new Space();
}
}
}
Regarding your exact question about values not printing, the bigger problem than above is that you don't have any logic for assigning values.

Selection Sort for strings and integers at the same time

Here is the task I have been set with:
Create a text file named Names_ages.txt with the following content:
Jones 14
Abrams 15
Smith 19
Jones 9
Alexander 22
Smith 20
Smith 17
Tippurt 42
Jones 2
Herkman 12
Jones 11
Each line is a person’s last name followed by a space and then his age. We want to sort these names alphabetically and in the case of duplicate names, sort by age in an ascending fashion. A properly sorted list will appear as follows:
Abrams, 15
Alexander, 22
Herkman, 12
Jones, 2
Jones, 9
Jones, 11
Jones, 14
Smith, 17
Smith, 19
Smith, 20
Tippurt, 42
Here are my (working) selection sort methods for Strings and ints respectively:
private static void sort(String[] a) {
String min;
int minIndex;
for (int i = 0; i < a.length; i++) {
min = a[i];
minIndex = i;
// find minimum
for (int j = i + 1; j < a.length; j++) {
// salient feature
if (a[j].charAt(0) < min.charAt(0)) {
min = a[j];
minIndex = j;
}
}
a[minIndex] = a[i]; // swap
a[i] = min;
}
}
private static void sort(int[] a) {
int min, minIndex;
for (int i = 0; i < a.length; i++) {
min = a[i];
minIndex = i;
// find minimum
for (int j = i + 1; j < a.length; j++) {
// salient feature
if (a[j] < min) {
min = a[j];
minIndex = j;
}
}
a[minIndex] = a[i]; // swap
a[i] = min;
}
}
I can sort the names in the text file and then the numbers after, but the ages end up corresponding with incorrect people. Here is my class with the main method:
Scanner scanner = new Scanner(new File("/Users/Krish/IdeaProjects/Lessons/src/Lesson40/MultipleKey/NamesAges.txt"));
String text[] = new String[100];
int index = 0;
while (scanner.hasNext()) {
text[index++] = scanner.nextLine();
}
scanner.close();
String name;
String[] names = new String[index];
int age;
int[] ages = new int[index];
for (int i = 0; i < index; i++) {
Scanner line = new Scanner(text[i]);
name = line.next();
names[i] = name;
age = line.nextInt();
ages[i] = age;
}
sort(names);
sort(ages);
for (int i = 0; i < index; i++) {
System.out.println(names[i] + ", " + ages[i]);
}
Any help is appreciated, thanks.
Create a POJO class Person implementing Comparable<Person>
After parsing, store Person instances in a collection, say List<Person>
Sort the collection
-
public class PersonTest {
static class Person implements Comparable<Person> {
private static final Comparator<Person> COMPARATOR = Comparator
.comparing(Person::getName)
.thenComparingInt(Person::getAge);
final String name;
final int age;
public static Person parse(String rec) {
final String[] parts = rec.split(" ");
return new Person(parts[0], Integer.valueOf(parts[1]));
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
#Override
public int compareTo(Person o) {
return COMPARATOR.compare(this, o);
}
}
#Test
public void testSorting() throws Exception {
final Person[] sortedPersons = Files.lines(Paths.get("/path/to/file.txt"))
.map(Person::parse)
.sorted() // sort it here
.toArray(Person[]::new);
// or instead, sort it here with your custom algorithm
// using Person.COMPARATOR for comparison
}
}
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("/Users/Krish/IdeaProjects/Lessons/src/Lesson40/MultipleKey/NamesAges"));
String[] text = new String[100];
int index = -1;
while (scanner.hasNext()) {
text[++index] = scanner.nextLine();
}
scanner.close();
Scanner line;
String[] name = new String[100];
int[] age = new int[100];
for (int i = 0; i <= index; i++) {
line = new Scanner(text[i]);
name[i] = line.next();
age[i] = line.nextInt();
}
String minName;
int minAge;
int minIndex;
for (int i = 0; i <= index; i++) {
minName = name[i];
minAge = age[i];
minIndex = i;
for (int j = i + 1; j <= index; j++) {
if (name[j].compareTo(minName) == 0) {
if (age[j] < minAge) {
minName = name[j];
minAge = age[j];
minIndex = j;
}
} else if (name[j].compareTo(minName) < 0) {
minName = name[j];
minAge = age[j];
minIndex = j;
}
}
name[minIndex] = name[i];
name[i] = minName;
age[minIndex] = age[i];
age[i] = minAge;
}
for (int j = 0; j <= index; j++) {
System.out.println(name[j] + ", " + age[j]);
}
}

I need to determine if a random number is unique

I need to write a function that receives the number generated in fillArray and determine if it has already been generated. I need to return a true or false thus determining if the random number must be put into the array.
Here's what I am working on. Thanks for any help. I've searched for anything similar but unfortunately cannot find anything.
public class RandomGenerator {
int Arr[] = new int[6];
int size;
public void fillArray() {
int randNum = (int) (Math.random() * 49) + 1;
for (int i = 0; i < size; i++) {
Arr[i] = randNum;
alreadyThere(randNum);
}
size++;
}
public int alreadyThere(int randNum) {
int find = randNum;
boolean found = false;
int i = 0;
while (!found && i < size) {
if (Arr[i] == find) {
found = true;
}
i++;
}
if (!found) {
}
return randNum;
}

Putting array with unknown variables into another array

The purpose of this code is is to define the root of the sum of the squares.
I cant figure out how to put i into j. Please help.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int input, som, i=0;
int j = 0;
double answer;
Boolean gaDoor= true;
int [] array = new int [24];
while (gaDoor)
{
Console.Write("Specify a positive integer");
input = Convert.ToInt32(Console.ReadLine());
if (input == -1)
{
gaDoor = false;
}
else
{
if (input >= 0)
{
array[i] = input;
i++;
}
else
{
Console.WriteLine("Specify a positive integer ");
}
}
}
while (j<i)
{
sum = array [j] ^ 2;
answer = Math.Sqrt(sum);
Console.Write(answer);
}
Console.ReadKey();
}
}
}
using System;
namespace Test
{
class MainClass
{
public static void Main (string[] args)
{
int[] invoer = new int[24];
double[] resultaat = new double[24];
double totaal = 0;
double wortel = 0;
int commando = 0;
int teller = -1;
try {
// Keep going until a negative integer is entered (or a 0)
while ((commando = Convert.ToInt32 (Console.ReadLine ())) > 0) {
teller++;
invoer [teller] = commando;
}
} catch (FormatException) {
// Not a number at all.
}
teller = -1;
foreach (int i in invoer) {
teller++;
resultaat [teller] = Math.Pow (invoer [teller], 2);
totaal += resultaat [teller];
if (invoer [teller] > 0) {
Console.WriteLine ("Invoer: {0}, Resultaat: {1}", invoer [teller], resultaat [teller]);
}
}
wortel = Math.Sqrt (totaal);
Console.WriteLine ("Totaal: {0}, Wortel: {1}", totaal, wortel);
}
}
}

Resources