Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Getting NullPointerException when it tries to access stones[0].length.
Please Help. I have already Initialized Stones Object.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Solution
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
int times = sc.nextInt();
String stones[] = new String[times];
int score = 0;
int counter;
for(int tcase = 0; tcase < times; tcase++)
stones[tcase] = br.readLine();
int s = stones[0].length();
for (int i = 0; i < s ; i++) {
char j = stones[0].charAt(i);
counter = 0;
for (int k = 1; k < times; k++) {
char aa[] = stones[k].toCharArray();
for (int l = 0; l <aa.length ; l++) {
if(aa[l]==j)
{
counter++;
break;
}
}
if (counter==times-1) {
score++;
}
}
}
System.out.println(score);
}
}
Getting NullPointerException when I try to access stones[0].length(). Please help
When you submit your code through some automated service, it's running your code and it's failing because there's no System.in stream to provide any valid data. If you attempt to check for valid data before doing anything, it will catch this condition, and should let you submit, while still working properly on your laptop.
Try this:
Scanner sc = new Scanner(System.in);
int times = 0;
if ( sc.hasNext() ) { // check to make sure there's valid input first
times = sc.nextInt();
String stones[] = new String[times];
int score = 0;
int counter;
for(int tcase = 0; tcase < times; tcase++)
stones[tcase] = br.readLine();
if ( stones[0] != null ) { // check to make sure your array object exists
int s = stones[0].length();
for (int i = 0; i < s ; i++) {
char j = stones[0].charAt(i);
counter = 0;
for (int k = 1; k < times; k++) {
char aa[] = stones[k].toCharArray();
for (int l = 0; l <aa.length ; l++) {
if(aa[l]==j)
{
counter++;
break;
}
}
if (counter==times-1) {
score++;
}
}
}
}
}
The best way to make sense of these sort of problems is to use a debugger. But just for fun, let's do some code analysis...
int s = stones[0].length();
What can be generating a NullPointerException on this line? Well, the stones variable could be referring to null. We can easily rule this out, however, as the stones variable was assigned a new array instance further up in the code, and was never reassigned before reaching the problem line. The only other possibility is that the array component variable stones[0] refers to null.
Why might stones[0] be null? Well, for starters, it's initialized that way, so if you never assign to that component, then it will be null. However, the for loop that you have between array initialization and the problem line is iterating over all of the array components and initializing them, so every component will be assigned to. What else might be the problem?
The loop is assigning to each array component the value returned by br.readLine(). Could that return value possibly be null? Let's take a look at the javadocs...indeed, we find (emphasis added):
Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
And there you have it, it is certainly possible for stones[0] to be null! Now, if that is true, what does it mean? Well, it means that the very first call to br.readLine() returned null, signalling that it had reached the end of the stream. Which fits with what other answerers have noted - if System.in() is not available to provide any data, it would make sense to encounter the 'end of stream' condition right out of the gate.
It works with me, although I would not use two stream readers(a Scanner and a BufferedReader) for the same input.
What is the input that causes the exception?
PS. You should close the Scanner when it is not used.
Related
I'm writing some code to read an input file of book titles, and putting the read lines into an array and trying to print out the array. But when I try to print out the array, it just returns 'null' for each read line. I'm not sure what I'm doing wrong or what my code is doing. Any suggestions? Thanks!
Code:
import java.io.*;
import java.util.*;
public class LibraryInputandOutputs {
public static void main(String args[]) throws IOException{
int lineCount = 0;
File inputFile = new File("bookTitles.inp.txt");
Scanner reader = new Scanner(inputFile);
while(reader.hasNextLine()) {
reader.nextLine();
lineCount++;
}
String[] bookArray = new String[lineCount];
while (reader.hasNextLine()) {
for (int i = 0; i < lineCount; i++) {
bookArray[i] = reader.next();
}
}
for (int k = 0; k < lineCount; k++) {
System.out.println(bookArray[k]);
}
reader.close();
inputFile.close();
}
}
My text file I'm reading from is 20 book titles, all on different lines.
My output on the terminal is 20 lines of null.
Lets break this down:
This reads every line of the input file, counts each one, and then discards them:
while(reader.hasNextLine()) {
reader.nextLine();
lineCount++;
}
You are now at the end of file.
Allocate a string array that is large enough.
String[] bookArray = new String[lineCount];
Attempt to read more lines. The loop will terminate immediately because reader.hasNextLine() will return false. You are already at the end of file.
So you the statement assigning to bookArray[i] won't be executed.
while (reader.hasNextLine()) {
for (int i = 0; i < lineCount; i++) {
bookArray[i] = reader.next();
}
}
Since bookArray[i] = ... was never executed above, all of the array elements will still be null.
for (int k = 0; k < lineCount; k++) {
System.out.println(bookArray[k]);
}
One solution is to open and read the file twice.
Another solution is to "reset" the file back to the beginning. (A bit complicated.)
Another solution would be to use a List rather than an array so that you don't need to read the file twice.
Another solution is to search the javadocs for a method that will read all lines of a file / stream as an array of strings.
(Some of these may be precluded by the requirements of your exercise. You work it out ... )
The nested loop in step 3 is also wrong. You don't need a for loop inside a while loop. You need a single loop that "iterates" the over the lines and also increments the array index (i). They don't both need to be done by the loop statement itself. You could do one or the other (or both) in the loop body.
Stephen C has already pointed out the main problems with your logic. You're trying to loop twice through the file but you've already reached the end of the file the first time. Don't loop twice. "Merge" both the while loops into one, remove that for loop inside the while loop and collect all the book titles. You can then use the size of the list to print them later on. My Java might be rusty but here it goes -
import java.io.*;
import java.util.*;
public class LibraryInputandOutputs {
public static void main(String args[]) throws IOException {
// int lineCount = 0; - You don't need this.
File inputFile = new File("bookTitles.inp.txt");
Scanner reader = new Scanner(inputFile);
// Use an array list to collect book titles.
List<String> bookArray = new ArrayList<>();
// Loop through the file and add titles to the array list.
while(reader.hasNextLine()) {
bookArray.add(reader.nextLine());
// lineCount++; - not needed
}
// Not needed -
// while (reader.hasNextLine()) {
// for (int i = 0; i < lineCount; i++) {
// bookArray[i] = reader.next();
// }
// }
// Use the size method of the array list class to get the length of the list
// and use it for looping.
for (int k = 0; k < bookArray.size(); k++) {
System.out.println(bookArray[k]);
}
reader.close();
inputFile.close();
}
}
I agree with Stephen C. In particular, using a List is usually better than an array because it's more flexible. If you need an array, you can always use toArray() after the List is filled.
Are your book titles on separate lines? If so you might not need a Scanner class, and could use something like a BufferedReader or LineNumberReader.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
does anyone know whats wrong with my code? it keep getting error output in java GUI
the loop 2 and loop 3 getting error after debug, and i dont know whats wrong
private void butActionPerformed(java.awt.event.ActionEvent evt) {
String input1 = txtInput.getText();
String input2 = input1.toLowerCase();
char[] word1 = new char[input2.length()];
char[] word2 = new char[26];
for (int i = 0; i < word2.length; i++) {
word2[i] = (char) (97 + i);
}
int[] x = new int[26];
for (int i = 0; i < word1.length; i++) {
input1[i] = input2.charAt(i);
}
for (int i = 0; i < word2.length; i++) {
for (int j = 0; j < word1.length; j++) {
if (word2[i])==word1[j]) {
x[i]++;
}
}
}
txtOutput1.setText(Arrays.toString(word2));
txtOutput2.setText(Arrays.toString(x));
}
The first problem:
input1 is a string, but with input1[i] = input2.charAt(i); you are treating it as an array - this is not allowed in Java.
From your logic I think the corresponding line should be
word1[i] = input2.charAt(i);
The second problem: on the line
if (word2[i])==word1[j]) {
there is a closing parenthesis to much (after word2[i]), the line should read
if (word2[i]==word1[j]) {
input1 is a String variable and therefore immutable, which means it can only be assigned a new value and can not be changed otherwise.
The following line causes a problem:
input1[i] = input2.charAt(i);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
so I have to write a program for an assignment, and for that i have to accept a string, make sure it's got the right number of sentences and print the frequency of each word. I've got this almost completely right, but at the end, when I print the words (which I've stored in an array), each word is preceeded by Ljava.lang.String; #xyznumber. I have no idea why this is happening and I can't find a solution on the net. Here's my code:
import java.util.Arrays;
import java.io.*;
class frequency
{
public static void main(String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of sentences");
int cS = Integer.parseInt(br.readLine());
System.out.println("Enter sentences");
String s = br.readLine();
int cS1 = 0;
int cW = 0;
for(int i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
if (ch=='.'||ch=='?')
{
cW++;
cS1++;
}
if (ch==' ')
{
cW++;
}
}
if (cS1!=cS)
{
System.out.println("You have entered the wrong number of sentences. Please try again.");
}
else
{
int c = 0;
int d = 0;
String a[] = new String[cW];
System.out.println("Total Number of words: "+cW);
for (int i= 0;i<s.length();i++)
{
char ch=s.charAt(i);
if (ch==' '||ch=='?'||ch=='.')
{
a[c++]=a+s.substring(d,i);
d = i+1;
}
}
int length=0;
firstFor: for(int i=0;i<a.length;i++)
{
for(int j=0;j<i;j++)
{
if (a[j].equalsIgnoreCase(a[i]))
{
continue firstFor;
}
else
{
length++;
}
}
}
String words[] = new String[length];
int counts[] = new int[length];
int k=0;
secondFor: for (int i =0;i<a.length;i++)
{
for(int j = 0; j<i;j++)
{
if (a[j].equalsIgnoreCase(a[i]))
{
continue secondFor;
}
}
words[k]=a[i];
int counter = 0;
for (int j =0;j<a.length;j++)
{
if(a[j].equalsIgnoreCase(a[i]))
{
counter++;
}
}
counts[k]=counter;
k++;
}
for (int i=0;i<words.length;i++)
{
System.out.println(words[i]+"\n"+(counts[i]));
}
}
}
}
The problem stems from this line here:
a[c++]=a+s.substring(d,i);
Since a is a String array, what this does is assigns one of the elements in a to be equal to the String representation of the entire array, plus a substring of s. Arrays don't have a very useful String representation though, which is where the Ljava.lang.String;#xyznumber you see is coming from.
Depending on what you want the first part of a[c] to be, either use an index into the array, or convert the array to a String
Sounds Pretty Straightforward, but for me it's quite strange. I'm trying to import a data file (which I've done successfully), and use this and compare each and every word to see which one is the longest. So far, it is not working (index out of bounds), and when I did manipulate it to work (incorrectly), it gave me the wrong word as the longest one.
This is what I have so far...
Main File:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Collections;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import static java.lang.System.*;
public class FancyWordsRunner
{
private static int max = 0;
public static void main( String args[] ) throws IOException
{
ArrayList<String> wordList = new ArrayList<String>();
{
String ray = "";
Scanner welcome = new Scanner(new File("fancywords.dat"));
while(welcome.hasNext())
{
ray = welcome.next();
wordList.add(ray);
for(int i = 0; i<wordList.size(); i++)
{
int j = i+1;
if(wordList.get(j).length()>wordList.get(i).length())
max = j;
}
}
}
String maximum = wordList.get(max);
out.println(maximum);
}
}
fancywords.dat:
2013 UIL STATE CONTEST
PROGRAMMING IS FUN
TODAY IS SATURDAY
Current Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at FancyWordsRunner.main(FancyWordsRunner.java:35)
How about replacing your while loop with something like this.
String longestSoFar = "";
while (welcome.hasNext()) {
String current = welcome.next();
if (current.length() > longestSoFar.length()) {
longestSoFar = current;
}
}
I realize that your bug has been identified by other answers, but, you do realize that this problem can be solved in a much simpler way?
public static void main( String args[] ) throws IOException {
String max = "";
Scanner welcome = new Scanner(new File("fancywords.dat"));
while(welcome.hasNext()) {
String ray = welcome.next();
if (ray.length() > max.length()) {
max = ray;
}
}
System.out.println(max);
}
In your first iteration, you've only added one item to the list, so the size is 1 meaning only an index of 0;
int j = i+1;
if(wordList.get(j)
This is trying to access index 1
Walk through:
1)
ArrayList<String> wordList = new ArrayList<String>();
// wordlist.size() = 0; available indices - none
2)
wordList.add(ray);
// wordlist.size() = 1; available indices - 0
3)
int j = i+1; // i = 0; j = 1
if(wordList.get(j) // access index j
// oops!; There is no index j
This causes an IndexOutOfBoundsException.
EDIT: Alternative - you really don't need a list to perform this task
String maxWord = "";
String current = "";
while(welcome.hasNext()){
current = welcome.next();
if (current.length() > maxWord.length()){
maxWord = current;
}
}
System.out.println(maxWord);
for(int i = 0; i<wordList.size(); i++)
{
int j = i+1;
You're setting up your for loop to make sure i is never out of bounds, but then you set j equal to one larger than i, so on the last run of the loop, when i is at the last index, j is one larger than the last index (and out of bounds).
Try this:
for(int i=0; i<(wordList.size()-1); ++i)
Solution to the logic error:
for(int i = 0; i<wordList.size();++i) {
if(wordList.get(i).length() >= wordList.get(max).length()) {
max = i;
}
}
(This also gets rid of the j that was causing the IndexOutOfBoundsException in the first place.)
And as others have pointed out, there is some redundancy in your program. Changing your for loop to my suggestion will fix your logic problem and make your program output the correct result. The other answers all get rid of the ArrayList, which isn't totally necessary, but if you want to simplify your solution and keep the ArrayList, your while loop could look something like this:
String longestWord = "";
Scanner welcome = new Scanner(new File("fancywords.dat"));
while(welcome.hasNext()) {
ray = welcome.next();
wordList.add(ray);
if(ray.length() > longestWord.length()) {
longestWord = ray;
}
}
This solution simplifies your answer, saves some time in the program and keeps the ArrayList (you still have every word saved in memory).
Your for loop was running a LOT and checking every word numerous times. Once we know that CONTEST is the longest of the first four words, we don't need to see whether PROGRAMMING is longer than the first three or not, just whether it's longer than CONTEST, and we don't need to compare SATURDAY to any word other than PROGRAMMING, which was established as the longest word when it was read and continued to be the longest word between then and reading SATURDAY, etc. If all we care about is the longest word, we only need to compare each word to the current longest word.
And because your ArrayList is still in memory, you can recreate the original words you read in, find the shortest word, find the average word length, etc., whatever you want to do with it.
I'm a Java beginner and this is my first post.
I couldn't find anything exactly like my problem although this post seemed similar:
Why is this print line command executing twice?
but the answers didn't help me solve it.
I know it's probably something stupid but was hoping one of you folks might be able to point out to me why the last entry in the array named "matches" prints out twice.
Thanks in advance,
Robert.
Here is my code:
public String buildMatchList(Match[] matches)
{
fixtures = "";
int i = 0;
for ( i = 0; i < numMatches; i++)
{
if (matches[i] != null)
{
fixtures += String.format("\n%-10.10s %10.9s %15.14s", matches[i].getTeamA(), " Vs ", matches[i].getTeamB());
}
}
System.out.println(fixtures);
}
// -EDIT -
// numMatches set in this method
public void fillMatchArray(Team[] sortedTeams, int numTeams)
{
int homeTeam = 0;
int awayTeam = 0;
goalsA = 0;
goalsB = 0;
fixtures = "";
boolean played = false;
matches = new Match[MAX_NUM_GAMES];
for (homeTeam = 0; homeTeam < sortedTeams.length; homeTeam++)
for (awayTeam = homeTeam+1; awayTeam < sortedTeams.length; awayTeam++ )
{
String teamA = sortedTeams[homeTeam].getTeamName();
String teamB = sortedTeams[awayTeam].getTeamName();
matchFixtures = new Match(teamA, teamB, goalsA, goalsB, played);
{
fixtures += String.format("\n%-10.10s %10.9s %15.14s",
matchFixtures.getTeamA(), " Vs ", matchFixtures.getTeamB());
}
int i = 0;
matches[i] = matchFixtures;
numMatches++;
buildMatchList(matches);
}
}
If it prints out twice, the most likely explanation is that the last two entries are the same. There is a common bug where you add a mutable objects to a collection twice and while you think they are different, they are not.
I suggest you try stepping through the code in your debugger to see what it doing?
this is where stepping through the code would be helpful. You are setting the first element of the array each time as i is always 0
int i = 0;
matches[i] = matchFixtures;
numMatches++;
change it to
matches[numMatches++] = matchFixtures;
Match is an object, so matches is a called a reference type. When you compare those to null, it will compare the reference to null, which it never is, so it will always return true.
If you want it to compare the contents of the object to null, you should replace matches[i] != null with matches[i].equals(null).