Why is this getting NullPointerException & ArrayIndexOutOfBoundsException errors [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
Getting a NullPointerError on line 24 (second for loop) and an arrayoutofindexexception on the main method. I have no idea how to solve this and an explanation would be much appreciated. Please help!
Edit: 'NullPointerError' solved, just needed to initialize the ArrayList for it, but still can't work out the 'ArrayOutOfIndexException' error.
import java.util.*;
public class SnackBar
{
private Random randomizer;
private String[] flavours;
private SnackMachine barMachine;
ArrayList<Student> students;
public SnackBar(int numStudents, int packetsBarMachine, int costPacket)
{
randomizer = new Random();
flavours = new String[] {"prawn cocktail", "tango cheese", "natural", "paprika", "salt and vinegar"};
barMachine = new SnackMachine(packetsBarMachine, costPacket);
students = new ArrayList<Student>();
for(int i = 0; i < packetsBarMachine; i++)
{
barMachine.addPack(new PackOfCrisps(randomFlavour()));
i++;
}
for(int j = 0; j < numStudents; j++)
{
students.add(new Student(randomFlavour(), barMachine));
j++;
}
}
public String randomFlavour()
{
int random = randomizer.nextInt(flavours.length);
return flavours[random];
}
public void describe()
{
System.out.println("The SnackBar has " + students.size() + " hungry students.");
System.out.println("The Snackmachine has:");
System.out.println(barMachine.countPacks("prawn cocktail") + " packets of prawn cocktail crisps,");
System.out.println(barMachine.countPacks("tango cheese") + " packets of tango cheese crisps,");
System.out.println(barMachine.countPacks("natural") + " packets of natural crisps,");
System.out.println(barMachine.countPacks("paprika") + " packets of paprika crisps,");
System.out.println(barMachine.countPacks("salt and vinegar") + " packets of salt and vinegar crisps.");
}
public void runSnackBar(int nSteps)
{
int step = 1;
while(step <= nSteps)
{
System.out.println("Time Step " + step);
describe();
int atRandom = randomizer.nextInt(students.size());
students.get(atRandom).snackTime();
step++;
}
}
public static void main(String[] args)
{
SnackBar bar = new SnackBar (Integer.parseInt(args[4]), Integer.parseInt(args[20]), Integer.parseInt(args[5]));
bar.runSnackBar(Integer.parseInt(args[30]));
}
}

First thing, you should initialize the ArrayList<Student> students list.
Integer.parseInt(args[30]) is also suspicious, since for that not to throw an exception, you have to supply 31 command line arguments. Same goes for all your other attempts to access elements of args array without checking its length first.

Related

How do I make a class to dynamic check different objects variable?

I'm new to Java, and i'm trying to create an automatic working shift schedule.
I want the code to mix four different employees to handle a morning shift and afternoon shift every work day.
I have made some code that just pick a random employee into a shift:
import java.util.Arrays;
import java.util.Random;
public class CreateNewShift {
public static void main(String[] args) {
int startWeek = 30; //Which week would start from?
int endWeek = 32; //which week will you end on?
generateShift(startWeek, endWeek);
}
private static void generateShift(int startWeek, int endWeek) {
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
for (int x = 0; x <= (endWeek - startWeek); x++) { //This is counting the number of weeks
System.out.println("\nWeek: " + (startWeek+x));
for (int i = 1; i <= 5; i++) { //this is finding the next working shift day
morningShift = p.chooseRandomEmployee(Employees);
afternoonShift = p.chooseRandomEmployee(Employees);
if (i == 1) {
System.out.println("Mon: " + morningShift + " + " + afternoonShift);
}
else if (i == 2) {
System.out.println("Tue: " + morningShift + " + " + afternoonShift);
}
else if (i == 3) {
System.out.println("Wed: " + morningShift + " + " + afternoonShift);
}
else if (i == 4) {
System.out.println("Thu: " + morningShift + " + " + afternoonShift);
}
else {
System.out.println("Fri: " + morningShift + " + " + afternoonShift);
}
}
}
}
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
However, I now want the code to handle more restictions.
So i'm currently trying to add the option for the employees to choose some specific days that they dont want to have a shift. I have done this by adding this code to the Employee class:
public class Employee {
boolean monShift = true;
boolean tueShift = true;
boolean wedShift = true;
boolean thuShift = true;
boolean friShift = true;
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
return Employees[randomNumber];
}
}
And then i had tried to create new objects in my main class:
private static void generateShift(int startWeek, int endWeek) {
Employee Employee1 = new Employee("Employee1");
Employee Employee2 = new Employee("Employee2");
Employee Employee3 = new Employee("Employee3");
Employee Employee4 = new Employee("Employee4");
String Employees[] = {"Employee1", "Employee2", "Employee3", "Employee4"};
String morningShift;
String afternoonShift;
....
Quetions:
How can I improve my code in the Employee class to do a check if the random chosen employee have
monShift = true;
I have tried something like this, but i know it will not work, (and does not work either):
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
Random r = new Random();
int randomNumber = r.nextInt(Employees.length);
**if (("Employee" + randomNumber).monShift == false) {**
// Go back and try find a new random employee
}
else {
return Employees[randomNumber];
}
}
}
So i need a way to make my code dynamic to know which object (employee) it has to check if they are available that specific day or not.
Feel free to ask for a deepening if my question is not clear.
Since this i my first question on this forum, I also appriciate feedback if my question and thoughts are too long, or any other comments.
I dont think that putting the chooseRandomEmployee() function inside the Employee object is a good idea beacuse is not a part of the employee, is not an "action" of it. I think you shiudl put it outside but I want to respect your decision so shoudl check the do while loop.
import java.util.Random;
public class Employee {
public String chooseRandomEmployee(String[] Employees) {
int randomNumber;
do {
//Generate a new random number
Random r = new Random();
randomNumber = r.nextInt(Employees.length);
//The line under is the same that saying "If monSift == false return to
//the beginning and start again generating a new number"
} while ("Employee" + randomNumber).monShift == false);
return Employees[randomNumber];
}
}

returning an array filtered from an existing array

So here's the question I need to answer: Implement a method that takes a research area as an input and returns the names of scientists associated with that area.
I've got a lot of the base code necessary but am struggling because I am trying to filter out the array of scientist professions to only return the scientist whose profession is the specified input. What I need help with is finding a way to make a new array with only certain filtered scientists and excluding the unspecified scientist. Any idea on how to change the code to return an array of only certain scientists would be very helpful! The issue is in the CheckField method, and I'll put my code below of the program:
public class computerScientists {
String name;
String researchArea;
String contribution;
// Constructor
public computerScientists(String NM, String RA, String C) {
this.name = NM;
this.researchArea = RA;
this.contribution = C;
}
public static void main(String[] args) {
computerScientists[] personDatabase = {
new computerScientists("Katherine Johnson", "Mathematician", "Mathmetician for NASA during space race"),
new computerScientists("Kimberely Bryant", "Entrepreneur & Activist", "Founded black girls code"),
new computerScientists("Mark Dean", "Inventor and Engineer", "Helped design and release some of the first computers"),
new computerScientists("Marie Van Brittan Brown", "Inventor and Pioneer", "Pieneered and invented an audio-video alarm system"),
new computerScientists("Marian R Croak", "Engineer", "Helped develop the Voice Over Internet Protocol (VOIP)")
};
//int size = person1.length
for(int i=0; i<personDatabase.length; i++){
System.out.println("Innovator " + String.valueOf(i + 1) + ": \n");
System.out.println("Name: " + personDatabase[i].name + "\n"
+ "Research Area: " + personDatabase[i].researchArea + "\n"
+ "Contribution: " + personDatabase[i].contribution);
System.out.println();
}
checkField("Inventor", personDatabase);
}
public static computerScientists[] checkField(String researchField, computerScientists[] array1) {
computerScientists[] newArray1 = new computerScientists[array1.length];
//int difference = newArray1.length - array1.length;
for (int i=0; i < array1.length; i++) {
if (array1[i].researchArea.contains(researchField)) {
newArray1[i].researchArea = String.valueOf(array1[i]);
}
}
for (int j=0; j<newArray1.length; j++) {
System.out.println(newArray1[j].researchArea);
}
return newArray1;
}
}

Error in Java Method Cant get it to print to the console

I'm not sure where I went wrong but I could use some help. I'm new to JAVA and I'm not sure where I'm going wrong. Just trying to get the items in the public void method to print to my console.
public class HomersDonutShop {
public static void main (String[] args) {
//Creates flavor array
String[] donutFlavors = new String[4];
donutFlavors[0]= "Chocolate";
donutFlavors[1]= "Vanilla";
donutFlavors[2]= "Chocolate With Sprinkles";
donutFlavors[3]= "Blueberry";
//default is chocolate. prints string with array selected
System.out.println("You picked " +donutFlavors[0]+"."+" Great choice!!");
//creates donut rating
final int donutRating[] = new int[5];
donutRating[0] = 1;
donutRating[1] = 2;
donutRating[2] = 3;
donutRating[3] = 4;
donutRating[4] = 5;
//default is 5 prints string with array selected
System.out.println("You gave " +donutFlavors[0]+" donuts"+" a rating of"+ " "+donutRating[4]);
}
public void makeDonuts(){
donutCount = donuCount + 1;
System.out.println("Time to mke more donuts."+" MMMMMMMM DOOOONNNUUUUTSSS.");
}
public void buyMoreIngredients() {
int ingredients = 10;
while (ingredients >= 10)
System.out.println(ingredients);
ingredients--;
if (ingredients <=1) {
System.out.println("Time to go shopping");
}
}
}

how do I use insertion sort on a 2D array?

So, I made this code almost work, but I want to use insertion sort on the array and for the output to display results sorted by product ID only by insertion sort. Each product ID should have the same corresponding number of units. The units should not be sorted independently. The only order would be by product ID is what I'm basically implying.
import java.util.*;
import java.io.*;
class newversion {
public static int [][] table; // the output table
public static int numOfRows; //number of rows used up in the table
public static int lookfor(int productID){
int location = -1; //-1 an error
for(int i = 0; i < numOfRows; i++){
if (table[i][0] == productID){
location = i;
}
}
return location;
}
/*
here is my modified bubble sort code. I based it on this, but done differently:
http://stackoverflow.com/questions/23283655/bubble-sort-on-2d-array-java
public static void swap(int int1, int int2, int[] array) {
if(int1 == int2){
return;
}
else{
int temp = int2;
array[int2] = array[int1];
array[int2] = temp;
}
}
but it didn't work and I had to try something else
*/
public static boolean contains(int productID){
if (lookfor(productID) == -1){
return false;
}
return true;
}
public static void main(String[] args) {
File file = null;
Scanner scanner = null;
try{
file = new File("data.csv");
scanner = new Scanner( file );
}
catch(Exception e){
System.out.println("Error opening file!");
System.exit(1);
}
//citation of idea for sorting method in 2D array: http://stackoverflow.com/questions/23283655/bubble-sort-on-2d-array-java
//I'm using bubble sort on a 2D array
//this is his code
/*
private static void bubblesort(Integer[] array) {
for (int i = 0; i < array.length; i++) {
for(int j = 0; j < array.length - 1; j++) {
if(array[j].compareTo(array[j+1]) > 0) {
swap(j, j+1, array);
}
}
}
}
private static void swap(Integer int1, Integer int2, Integer[] array) {
if(int1 == int2)return;
Integer temp = new Integer(array[int2]);
array[index2] = array[int1];
array[int1] = temp;
}
*/
//here's my idea for bubble sort on a 2D array
/*
for (int i = 0; i < numOfRows; i++){
for(int j = 0; j < numOfRows - 1; j++) {
if(table[j][0].compareTo(array[j+1][0]) > 0) {
swap(j, j+1, table);
}
}
//this didn't work well either
//Now, I have to try another for-loop
*/
//Count the number of lines in the file
int size_of_file = 0;
while (scanner.hasNextLine()){
scanner.nextLine();
size_of_file++;
}
table = new int[size_of_file][2];
//reset scanner
try{
file = new File("data.csv");
scanner = new Scanner( file );
}
catch(Exception e){
System.out.println("Error opening file!");
System.exit(1);
}
//save the title
String titleLine = scanner.nextLine();
System.out.println(titleLine);
//for each line in the file, store and total it.
numOfRows=0;
while (scanner.hasNextLine()){
String ln = scanner.nextLine();
String[] row = ln.split(",");
System.out.println(row[0] + ", " + row[1]);
if (contains(Integer.parseInt(row[0]))){
//This is the location in the table where the product id exists already.
int location = lookfor(Integer.parseInt(row[0]));
//add the units to what we have in the table
table[location][1] += Integer.parseInt(row[1]);
}
else{
table[numOfRows][0]= Integer.parseInt(row[0]);
table[numOfRows][1]= Integer.parseInt(row[1]);
numOfRows++;
}
}
//output
try{
PrintWriter output = new PrintWriter("output.csv");
output.println(titleLine);
for(int i=0;i<numOfRows;i++){
output.println(table[i][0] + "," + table[i][1]);
}
output.close();
}
catch(Exception e){
System.out.println("Error writing file");
}
}
}
I want to understand how to use FileReader better. I read a little bit about it here:
https://www.caveofprogramming.com/java/java-file-reading-and-writing-files-in-java.html
https://bytes.com/topic/java/answers/585814-reading-data-into-array-file
Although I don't think I understand from that how to store it into an array. Could someone explain how I can store values from FileReader class into an array? I want it in a 2D array where the number of rows is just however many product IDs I have and there is always 2 columns.
Excel File to read from:
Product ID Units
10002 4
10004 6
10008 2
10010 3
10010 3
output I get right now:
Product ID Units
10002 20
10004 72
10008 12
10010 37
10007 28
20003 42
30019 56
30020 29
10006 36
20005 32
etc.
I apologize if this update should be posted as a different question. Let me know so I can go by community standards. The piece of output I posted, you'll notice isn't sorted by productID. That's the last thing I want to do. Other than that, it basically works. I am apologizing in case someone wants to vote me down for not posting the answer, since technically it would be the same answer to the initial question. If this update should be a different thread, again, let me know and I'll make the edit.

Exception in thread "main" java.lang.NullPointerException? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am a beginner in java programming. I am trying to recreate a simplified version of the card game war. I ran my program which is posted below and it came back with this error:
Exception in thread "main" java.lang.NullPointerException
at cardgame.BuildDeck(cardgame.java:36)
at cardgame.main(cardgame.java:60)
I have been trying to solve this issue on my own through research, but I could not solve it. I was wondering if anyone can help me. If you do need any other information about my program, please just ask. Thanks in advance!
-FGxMatta
public class cardgame
{
static class TheCard
{
// Java getter & setter
private String CardName;
private int CardRank;
private int Chosen;
public TheCard(int rank, String name)
{
this.CardName = name;
this.CardRank = rank;
this.Chosen = 0;
}
}
#SuppressWarnings("null")
private static TheCard[] BuildDeck()
{
TheCard[] TheDeck = null;
String[] Cards = {"2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"};
String[] Suits = {"Spades","Hearts","Diamonds","Clubs"};
int[] Rank = {2,3,4,5,6,7,8,9,10,11,12,13,14};
int cardnumber = 0;
for (int i = 0; i < Cards.length; i++)
{
for (int j = 0; j < Suits.length; j++)
{
String deckcard = Cards[i];
String suitcard = Suits[j];
String cardname = deckcard + "-" + suitcard;
TheDeck[cardnumber] = new TheCard(Rank[i], cardname);
cardnumber++;
}
}
return TheDeck;
}
private static TheCard GetRandomCard(TheCard[] OrderedDeck)
{
TheCard thecard;
int random = (int) (51*Math.random ());
thecard = OrderedDeck[random];
if (thecard.Chosen == 0 ) // if available...
{
thecard.Chosen = 1; // mark it taken...
return thecard;
}
else
{
return GetRandomCard(OrderedDeck);
}
}
public static void main(String args[])
{
TheCard[] OrderedDeck = BuildDeck();
System.out.println ("Welcome, Prepare for War!");
int decksize = OrderedDeck.length;
int player1wincount = 0;
int player2wincount = 0;
int tiecount = 0;
for (int cardcount = 0; cardcount < decksize;)
{
TheCard Player1 = GetRandomCard(OrderedDeck);
cardcount++;
TheCard Player2 = GetRandomCard(OrderedDeck);
cardcount++;
System.out.println ("Player 1's card is: " + Player1.CardName);
System.out.println ("Player 2's card is: " + Player2.CardName);
if (Player1.CardRank > Player2.CardRank)
{
System.out.println("Player 1 wins this hand");
player1wincount++;
}
if (Player1.CardRank < Player2.CardRank)
{
System.out.println("Player 2 wins this hand");
player2wincount++;
}
if (Player1.CardRank == Player2.CardRank)
{
System.out.println("Player 1 and Player 2 played the same valued card");
tiecount++;
}
}
System.out.println ("Player 1 won " + String.valueOf(player1wincount) + " hands");
System.out.println ("Player 1 won " + String.valueOf(player2wincount) + " hands");
System.out.println ("There were " + String.valueOf(tiecount) + " ties");
}
}
Replace:
TheCard[] theDeck = null;
with:
TheCard[] theDeck = new TheCard[Cards.length * Suits.length];
and move it to below the declarations for Cards and Suits.
Null Pointer Exception is a situation in code where you try to access/ modify an object which has not been initialized yet. It essentially means that object reference variable is not pointing anywhere and refers to nothing or ‘null’. A simple example can be:
package au.com.copl;
public class Demo{
public static void main(String[] args) {
String d = null;
System.out.println(d.toString()); // d is un-initialized and is null
}
}
right here
TheDeck[cardnumber] = new TheCard(Rank[i], cardname);
you never initialized TheDeck. You probably want something like
TheDeck = new TheCard[52];
before you start putting things in the array.
as a note, java convention is that variable names be camel cased. So "CardName" should be cardName. Just a convention.
TheCard[] theDeck = null; ?
dont you need to inialize it?
You should also use new in main method:
TheCard[] OrderedDeck = BuildDeck();
should be replaced by:
TheCard[] OrderedDeck = new BuildDeck();

Categories