NullPointerException when trying to read from a text file - java

I'm trying to read these names from a text file, but getting an error. Here's the relevant part of my main method, and the method in question:
public class Prog4
{
int mostVoteCount = 0;
int mostVotes = 0;
int mostVotesIndex = 0;
int fewestVoteCount = 0;
int fewestVotes = 0;
int fewestVotesIndex = 0;
String[] candidateArray;
int[] votesArray;
public static void main(String args[]) throws Exception
{
//Scanner stdin = new Scanner(System.in);
Scanner stdin = new Scanner(new File("test.txt"));
int num_votes, num_candidates, election_num = 1;
System.out.println("Welcome to Prog4!\n");
Prog4 p4 = new Prog4();
while (stdin.hasNextLine())
{
System.out.println("Results for election " + election_num);
p4.read_candidates(stdin, p4.candidateArray);
p4.read_votes(stdin, p4.votesArray);
System.out.println("Total votes: " + p4.votesArray.length);
}
System.out.println("Done. Normal termination of Prog4.");
}
and the method in question:
public void read_candidates(Scanner stdin, String candidates[])
{
int candidateCount = 0;
candidateCount = (stdin.nextInt());
for (int i = 0; i < candidateCount; i++)
candidates[i] = (stdin.next());
}
Here's my test data used in the "test" text file:
4
Owen
Jack
Scott
Robbie
15 0 1 1 2 3 1 0 0 0 0 1 2 2 1 1
Is this the stack trace?
java.lang.NullPointerException
at Prog4.read_candidates(Prog4.java:75)
at Prog4.main(Prog4.java:35)

You're never instantiating your candidateArray and votesArray, so they are null when you pass them to the read_candidates method. I'm guessing it is failing on the line:
candidates[i] = (stdin.next());
You're basically attempting to do something with a null object (the candidates object in this case). At some point in your code you'll have to do something like candidateArray= new String[], and same thing for the votesArray, before you attempt to use them.

You need to initialize your array "candidates" before you do the assignment
public void read_candidates(Scanner stdin, String candidates[]) {
int candidateCount = 0;
candidateCount = (stdin.nextInt());
candidates = new String[candidateCount]; // here initialize your array
for (int i = 0; i < candidateCount && stdin.hasNext(); i++){
String data = stdin.next();
System.out.print(data + " ");
candidates[i] = data;
}
}

it can be an outfobound exaception so please be careful with the line candidateCount = (stdin.nextInt());
you may get exception here so calculate length correctly candidateCount = candidates.length;

Check the location of test.txt. Based the trace, your Scanner object being passed to read_candidates is null. Be sure that you can read the file from the specified location.

Related

Running my world generation code ends up in 2 or more ArrayIndexOutOfBoundsExceptions

So I'm coding my text-based game with world generation and my friend coded the world generation. He's away right now so I have to ask this.
The code should generate an array with the X and Y positions of chests that spawn in random positions. The packages used are: java.util.Scanner,
java.util.Arrays,
java.util.Random,
Class is declared but I'm not including it in this snippet.
The Code for the method worldgen():
static double[] worldgen() {
//coded by *my friend, name censored*
int random_int_1 = 0;
int random_int_2 = 0;
int x;
int y;
int chest_x;
int chest_y;
double[] chest_x_values;
double[] chest_y_values;
int mineral_x;
int mineral_y;
// chest_x_and_y_values[something (or else)] = chest_x_values[something];
// chest_x_and_y_values[something else] = chest_y_values[something];
Random rand1 = new Random();
int num_of_chests = rand1.nextInt(100);
chest_x_values = new double[num_of_chests];
chest_y_values = new double[num_of_chests];
while (random_int_1 <= num_of_chests)
{
Random rand2 = new Random();
chest_x = rand2.nextInt(301);
System.out.println(chest_x);
chest_x_values[random_int_1] = chest_x;
System.out.println(Arrays.toString(chest_x_values));
if(random_int_1 <= num_of_chests) {
random_int_1++;
System.out.println(random_int_1);
}
}
while (random_int_2 <= num_of_chests)
{
Random rand3 = new Random();
chest_y = rand3.nextInt(301);
chest_y_values[random_int_2] = chest_y;
random_int_2 = random_int_2 + 1;
}
int random_int_3 = num_of_chests;
random_int_1 = 0;
random_int_2 = 0;
double[] chest_x_and_y_values = new double[random_int_3 = random_int_3*2+1];
while (random_int_1 <= random_int_3) {
chest_x_and_y_values[random_int_1] = chest_x_values[random_int_1];
random_int_1 = random_int_1 + 1;
}
chest_x_and_y_values[random_int_1+1] = -1;
while (random_int_2 <= random_int_3) {
chest_x_and_y_values[random_int_1 + 1 + random_int_2] = chest_y_values[random_int_2];
random_int_2 = random_int_2 + 1;
}
return chest_x_and_y_values;
}
public static void main(String[] args) {
//coded by EnZon3
Scanner uIn = new Scanner(System.in);
System.out.println("-------------------------------");
System.out.println(" *game name censored* ");
System.out.println(" 1: Generate new world.. ");
System.out.println(" 2: Generate w/ custom seed.. ");
System.out.println(" 3: See world data ");
System.out.println(" 4: Exit ");
System.out.println("-------------------------------");
int option = uIn.nextInt();
if (option > 4) {
System.err.println("Error 0x1: Not an option");
}
while (option != 4) {
if (option == 1) {
double[] world = worldgen();
System.out.println(Arrays.toString(world));
}
}
}
The error I get is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 77 out of bounds for length 77 at
.worldgen(.java:35) at .main(.java:86)
I've tried tweaking the values but that didn't work
while (random_int_1 <= num_of_chests)
This should be < (strictly less than), remember arrays are 0 indexed.
while (random_int_2 <= num_of_chests)
Same thing here
while (random_int_1 <= random_int_3) {
chest_x_and_y_values[random_int_1] = chest_x_values[random_int_1];
random_int_1 = random_int_1 + 1;
}
random_int_3 is 2 * num_of_chests +1, and chest_x_values is a list of length num_of_chests. In this part, random_int_1 can go all the way up to 2 * num_of_chests +1 which is higher than chest_x_values.

Unable to calculate discount

Hey everyone so I'm new to programming and recently I've been introduced to array's I've been having some problems in my current project. Essentially I am getting an array out of bounds exception when trying to calculate the discount price (afterDiscount located at the bottom) however when I run the program I get this error. I'm not sure how to fix it as I have not dealt with arrays before.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at StarterJ52PartPriceDiscount.main(StarterJ52PartPriceDiscount.java:108)
import java.io.*;
import java.util.*;
public class StarterJ52PartPriceDiscount
{
public static void main(String[] args) throws FileNotFoundException
{
// Constants
final int MAX = 30; // max records on parts.dat
final int SENTINEL = 999;
// File Objects - Parts and Trans files
Scanner inPartsFile = new Scanner(new FileReader("parts.dat"));
Scanner inTransFile = new Scanner(new FileReader("trans.dat"));
// Part file Variables
int stkPartNo;
double stkPartPrice; // ???
// Tx file Variables
int txPartNo;
int txQuantity;
int txDiscountCode;
// Arrays
int[] partNos = new int[MAX];
double[] prices = new double[MAX];
int[] discounts = {0,5,10,15,20,25,30,40,50}; // Discount Percentages
// Other Variables
Scanner console = new Scanner(System.in);
int recCount; // no records on file
int cnt, foundPosition,i,pos; // index
double beforeDiscount, afterDiscount, totalDiscount, cost;
boolean found;
// Initialise
recCount = 0;
foundPosition = 0;
totalDiscount = 0;
found = false;
pos =-1;
// Output Part No and Prices (for)
System.out.println("Part No Part Price");
for(i=0; i <MAX; i++)
{
stkPartNo = inPartsFile.nextInt();
stkPartPrice = inPartsFile.nextDouble();
//System.out.printf("%2d %4.2f %n",stkPartNo,stkPartPrice );
partNos[i] = stkPartNo;
prices[i] = stkPartPrice;
System.out.printf("%6d %7.2f %n",partNos[i],prices[i]);
}//for
// Initial Tx read of first record
txPartNo=inTransFile.nextInt();
System.out.println("Part Quantity Disc Code");
while(txPartNo != SENTINEL)
{
txQuantity = inTransFile.nextInt();
txDiscountCode = inTransFile.nextInt();
System.out.printf("%4d %4d %4d %n",txPartNo,txQuantity,txDiscountCode );
txPartNo=inTransFile.nextInt();
}//While
// Verify Tx trans.dat contents (initially)
inTransFile.close();
inTransFile = new Scanner(new FileReader("trans.dat"));
System.out.println("xxxxxxx");
txPartNo=inTransFile.nextInt();//initial Read
while(txPartNo != SENTINEL)
{
txQuantity = inTransFile.nextInt();
txDiscountCode = inTransFile.nextInt();
System.out.printf("%4d %4d ",txPartNo,txQuantity );
found = false;
pos = -1;
while (pos < partNos.length -1 && found == false)
{
++pos;
if (partNos[pos] == txPartNo){
found = true;
}
else if (partNos[pos] > txPartNo){ // Ordered
pos = partNos.length; // break;
}
} // inner while
if (found) { // == true
beforeDiscount = prices[pos];
//Throws out of bounds exeption
afterDiscount = beforeDiscount - (beforeDiscount * discounts[txDiscountCode]);
System.out.printf("%4.2f %n",beforeDiscount);
System.out.printf("%4.2f %n",afterDiscount);
}
else {
System.out.println("NOT Found");
}//if
txPartNo=inTransFile.nextInt();//Sub Read
}//While
} // main
}
ThankYou for your comments I was able to rectify the problem, my discount array was beginning at position 1 rather than position 2, therefore, cause the out of bounds exception
changed the code from this
afterDiscount = beforeDiscount - (beforeDiscount * discounts[txDiscountCode]);
to this
afterDiscount = beforeDiscount - (beforeDiscount * discounts[txDiscountCode-1]);

How can I find Histogram using arrays?

Build/Output Histograms using Arrays Where i'm wrong?
This code takes 5 inputs from user in array and show the number of stars for example if user enter 3 then *** would be shown and so on .Where i'm wrong ?
public class P20 {
public static void main(String[] args) {
int[] anArray;
int Number;
//setup variable value
anArray = new int [10];
System.out.println("Enter some numbers between 1 and 100.");
for (int i = 0; i < 10; i++) {
System.out.println(i);
anArray[0] = 1-9;
anArray[1] = 10-19;
anArray[2] = 20-29;
anArray[3] = 30-39;
anArray[4] = 40-49;
anArray[5] = 50-59;
anArray[6] = 60-69;
anArray[7] = 70-79;
anArray[8] = 80-89;
anArray[9] = 90-100;
if(anArray > 0) {
System.out.println("*"+Number );
else if(anArray > 20)
{
System.out.println("**"+Number );
}
else if (anArray > 30)
{
System.out.println("***"+Number );
}
else if (anArray > 40)
{
System.out.println("****"+Number );
}
else if (anArray > 50)
{
System.out.println("*****"+Number ); }
}}
This code takes 5 inputs from user in array and show the number of stars for example if user enter 3 then *** would be shown and so on .Where i'm wrong ?
This code doesn't take inputs from the user.
You want the user to input a value and then you print the number of stars he/she wrote. You could do this like that:
public class P20 //Why don't you try giving names that are easier to remember
{
public static void main(String[] args)
{
for (int i=0; i<args[0]; i++)
{
System.out.print("*");
}
}
Where args[0] is the first argument given to the program when called:
java P20 3
Anyway, let me try to point out what some of the mistakes of your code are:
When you wrote:
anArray[0] = 1-9;
Did you really want to write that wich means "Let the 0th element of the array be the number 1 minus 9" (=-8)?
Or did you intent to input an interval? (Meaning the numbers from 1 to 9).
Then later on you say
if(anArray > 0)
Which doesn't make sense to me since anArray is an int[] variable and not an int variable. This means that anArray is not a variable which points directly to a number, but one pointing to an array object which holds several int values.
if(anArray > 0) {
you always will be > 0 so you always get only 1 x *
you hve to modify your if clause like that:
if (anArray > 0 && anArray < 20){
and so on...
edit:-----------------------------------------------------------
like you requested:
public String stars(int n) {
if (n == 1){
return "*";
}else{
return "*" + stars(n-1);
}
}

Setting the counter to 0, then adding counters with methods are keeping it 0

I have a guessing program, and Im trying to add a counter. In the bolded parts I have a counter. When you get a guess wrong, it adds 1 to the counter. But when it prints it, it just prints as 0 no matter what.
public static void firstGame(String Answer, String userGuess, int counter)
{
userInput = new Scanner(System.in);
boolean playgame = true;
while(playgame == true)
{
Answer = "Sam";
lnPrint(" ");
lnPrint("Take a guess at my name! It starts with an S...");
sPrint(":");
userGuess = userInput.next();
if(userGuess.equalsIgnoreCase(Answer))
{
lnPrint("You got it! Its " + Answer);
lnPrint(" ");
break;
}
else if(userGuess != Answer)
{
lnPrint("Good guess, keep trying!");
counter++;
}
}
}
That is my game method with the counter.
public static void main(String[] args)
{
Scanner userInput = new Scanner(System.in);
int Start, counter = 0;
String Answer, userGuess, middleAnswer, middleUserGuess;
Answer = null;
userGuess = null;
middleAnswer = null;
middleUserGuess = null;
Start = 0;
while(Start !=2)
{
lnPrint("(1) Start Game");
lnPrint("(2) Exit");
sPrint(":");
Start = userInput.nextInt();
if(Start == 1)
{
firstGame(userGuess, Answer, counter);
lnPrint("Now, how about my middle name?");
nlnPrint(counter);
middleGame(middleAnswer, middleUserGuess);
}
This is the code that prints it
This looks like a common pass by value / reference problem. When using counter as an argument for firstGame, it's the value of counter that is used in the firstGame method, as opposed to passing a reference to the counter variable; you can read about this here, for example: http://www.javacoffeebreak.com/faq/faq0066.html
There are ways of passing integers by reference to methods (see Java : Best way to pass int by reference) but in this case I think you should simply declare counter as a global variable.
Have you initialized "counter" earlier?
Heres an example where it works:
$.Guess = function() {
var parent = this;
var counter = 0;
this.guess = function(val) {
if ( val != 5 ) {
parent.guessedWrong();
}
}
this.guessedWrong = function() {
counter++;
}
this.guessed = function() {
return counter;
}
this.resetCounter = function() {
counter = 0;
}
}
var game = new $.Guess();
game.guess(1);
game.guess(2);
alert( game.guessed() );
game.guess(3);
game.guess(4);
game.guess(5);
// Alerts 4, because there is 5 guesses and one of them (the one with value 5) is correct
alert( game.guessed() );
// Reset counter to 0
game.resetCounter();
game.guess(6);
game.guess(7);
game.guess(8);
alert( game.guessed() );
..the code above can be tested here: http://jsfiddle.net/jcpjr9dc/

Issue with NullPointerException

I am continuing to get this error. Now I have gotten it for my SortSearchUtil. I've tried to do some debugging but can fix the issue. The error reads:
----jGRASP exec: java PostOffice
Exception in thread "main" java.lang.NullPointerException
at SortSearchUtil.selectionSort(SortSearchUtil.java:106)
at PostOffice.sortLetters(PostOffice.java:73)
at PostOffice.main(PostOffice.java:15)
----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.
line 106 of selection Sort is:
if (array[indexSmallest].compareTo(array[curPos]) > 0)
I don't know what could be wrong with my method. It's a standard method that was given to me by my instructor. I've tried to debug my program but I'm pretty stuck. Here is the method that the error is originating from, selectionSort:
public static void selectionSort(Comparable[] array)
{
int curPos, indexSmallest, start;
Comparable temp;
for (start = 0; start < array.length - 1; start++)
{
indexSmallest = start;
for (curPos = start + 1; curPos < array.length; curPos++)
if (array[indexSmallest].compareTo(array[curPos]) > 0)
{
indexSmallest = curPos;
}
// end for
temp = array[start];
array[start] = array[indexSmallest];
array[indexSmallest] = temp;
} // end for
}
The sort method is at the bottom which calls SortSearchUtil.selectionSort of this Post Office Method:
import java.util.*;
import java.io.*;
public class PostOffice
{
private final int max = 1000;
private Letter [] ltrAra = new Letter[max];
private int count;
public static void main(String [] args)
{
PostOffice postOffice = new PostOffice();
postOffice.readLetters("letters.in");
postOffice.sortLetters();
postOffice.printLetters();
}
public PostOffice()
{
Letter [] Letters = ltrAra;
this.count = 0;
}
public void readLetters(String filename)
{
int count = 0;
int iWork = 0;
Scanner fin = new Scanner(filename);
String toName, toStreet, toCity, toState, toZip;
String fromName, fromStreet, fromCity, fromState, fromZip, temp;
double weight;
String sWork;
fin = FileUtil.openInputFile(filename);
if (fin != null)
{
while (fin.hasNext())
{
toName = fin.nextLine();
toStreet = fin.nextLine();
sWork = fin.nextLine();
iWork = sWork.indexOf(",");
toCity = sWork.substring(0, iWork);
iWork = iWork + 2;
toState = sWork.substring(iWork, iWork + 2);
iWork = iWork + 3;
toZip = sWork.substring(iWork);
fromName = fin.nextLine();
fromStreet = fin.nextLine();
sWork = fin.nextLine();
iWork = sWork.indexOf(",");
fromCity = sWork.substring(0, iWork);
iWork = iWork + 2;
fromState = sWork.substring(iWork, iWork + 2);
iWork = iWork + 3;
fromZip = sWork.substring(iWork);
sWork = fin.nextLine();
weight = Double.parseDouble(sWork);
ltrAra[count] = new Letter(toName, toStreet, toCity, toState, toZip, fromName, fromStreet, fromCity, fromState, fromZip, weight);
count++;
}
fin.close();
}
}
public void sortLetters()
{
SortSearchUtil.selectionSort(ltrAra);
}
public void printLetters()
{
for (Letter ltr : ltrAra)
{
System.out.println(ltr);
System.out.println();
}
}
}
My file looks like this "letters.in":
Stu Steiner
123 Slacker Lane
Slackerville, IL 09035
Tom Capaul
999 Computer Nerd Court
Dweebsville, NC 28804-1359
0.50
Tom Capaul
999 Computer Nerd Court
Dweebsville, NC 28804-1359
Chris Peters
123 Some St.
Anytown, CA 92111-0389
1.55
Obviously you get a NPE because:
You initialize ltrAra as array of 1000 items, but you read in less than 1000 items within method readLetters(). So at the end of this array some null references remain un-initialized (remember array-creation does itself not set the single items to any objects). Therefore following sorting-method gets some null-references => NPE.
Suggested solution:
You should use an ArrayList instead of an array because that will automatically prevent you from accessing too much items due to internal range check.
In addition to the above answer that Meno has well stated, you need to understand when you get a Null pointer Exception.
your error-line : if (array[indexSmallest].compareTo(array[curPos]) > 0)
If we get NPE in this line, it is obvious that array[indexSmallest] is null
And when you invoke an action on null, you get NPE. Hope this helps you to debug, down the line.
Also, One of the main reasons when we choose ArrayList over Arrays is when we do not know the length of the array.
One more suggestion, you can create an ArrayList and then convert to Arrays if you want to stick with Arrays
To convert ArrayList of any class into array, Convert T to the respective class. For eg: if you want String array, convert T to 'String'
List<T> list = new ArrayList<T>();
T [] students = list.toArray(new T[list.size()]);

Categories

Resources