NullPointerException error in search through array - java

I'm trying to run this code. It reads the file successfully, but breaks at the word search itself.
The error:
Exception in thread "main" java.lang.NullPointerException
at WordSearch.main(WordSearch.java:30)
Here's the code:
import javax.swing.JOptionPane;
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class WordSearch{
public static void main(String[] args) throws FileNotFoundException{
String searchWord, fileName; int i=0, j=0;
fileName = JOptionPane.showInputDialog(null, "Please enter the name of the file to be processes: ");
File textFile = new File(fileName);
Scanner scanner = new Scanner(textFile);
String[] file = new String[500];
String[] found = new String[500];
while(scanner.hasNextLine()){
file[i]=scanner.next();
i++;
}
file[i+1]="EoA"; i=0;
searchWord = JOptionPane.showInputDialog(null, "Please input the string to search for: ");
while(!file[i].equals("EoA")){
if (file[i].equals(searchWord)){
if(i==0){
found[j]=file[i]+file[i+1]+"\n";
}
else if(i==500){
found[j]=file[i-1]+file[i]+"\n";
}
else {
found[j]=file[i-1]+file[i]+file[i+1]+"\n";
}
j++;
}
i++;
}
JOptionPane.showMessageDialog(null, found);
}
}

Change
file[i+1]="EoA";
to
file[i]="EoA";
Otherwise, you'll have a null entry in the position that precedes the "EoA" entry, which causes the NullPointerException.
Of course, you can get rid of the "EoA" entry, and just change the loop's condition to :
while (file[i] != null)
That's much more readable.
One last thing, how do you guarantee that your input won't be larger than the 500 length of your array?

This is happening because of your i++ expression. In each iteration i is being incremented and the result gets stored in previous index pointed by the value of i
Possible solution is to use i-1 in the while loop.

Related

First and last name buffered reader giving me troubles

I've fixed many other issues but after fixing one that I thought was the last error, I came a Null pointer exception.
package com.Text.Scanner.java;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class TextScanner {
public static void main(String ...args) throws IOException{
Scanner sc = new Scanner(System.in);
System.out.println("Enter names for parsing");
String input = sc.nextLine();
ArrayList<String> names = new ArrayList<String>();
for (int i = 0;i<=input.length();i++) {
names.add(input.substring(0, input.indexOf(",")));
input = input.substring(input.indexOf(",")+1);
}
System.out.println(names);
// handles the string import to arraylist
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader("sample.txt"));
//finds file
String line = reader.readLine();
//reads line
while (line != null) {
for (int i = 0; i <= line.length(); i++) {
if (line.contains(names.get(i))) {
//gets name from array to scan line for
System.out.println(line.substring(4, line.indexOf(names.get(i)) + names.get(i).length()));
//controls length
line = reader.readLine();
}
}
}
reader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
The goal here is to scan each line for a name (first and last) then print the number aside their name on the text file.
first line: 1234 Billy Smith
second line: 5678 John Smith
what you input: Billy Smith,John Smith,
The point of it is to scan the file for the list of first and last names in an arraylist and then output the numbers and name. The program works if I go in order in the whole list, but if I don't then it gives me this. I have tried to put reader.reset() if the if statement finds a match and then if it doesn't it reads another line, but that doesn't work
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:373)
at java.base/java.util.ArrayList.get(ArrayList.java:426)
at com.Text.Scanner.java.TextScanner.main(TextScanner.java:32)
for (int i = 0; i <= line.length(); i++) {
if (line.contains(names.get(i))) {
So basically i goes from O to line.length() (number of char in the line) and you use it to accces your names with name.get(i) that absolutely no reason to be the same size (it is more the number of lines on the first line)
But why don't you debug your code ? The error you got says the error is in TestScanner line 32 calling the method get. It already say where the error !
You could even rerun that program with the debugger, and ask it to stop when an exception is raised so it would stop exactly at the right place and you be able to look at the various variables.

Reading data from a table & parsing it

My code is designed to read the contents of a text file and check if the contents are entered in a format that is as follows:
john : martin : 2 : 1
and if that format is followed then it will output it in the format:
john [2] | martin [1]
or else it will be counted as an invalid result and the total numbers will not be added to it whereas if the results are in the format then they will get added to the total so with the example it would display the number of vaild results as 1, invalid as 0 and total number as 3.
My question is that my code doesn't work properly as I get this error:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at reader.main(reader.java:33)
So how would I go about fixing this and reading and displaying the data in thee way that I want? Thanks in advance.
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Locale;
import java.util.Scanner;
public class reader {
/**
* #param args
* #throws FileNotFoundException
* #throws FileNotFoundException
* #throws FileNotFoundException when the file cannot be loaded
*/
public static void main(String[] args) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
Scanner s = new Scanner(new BufferedReader(new FileReader("results2.txt"))).useDelimiter(":");
// create a scanner which scans from a file and splits at each colon
while ( s.hasNext() ) {
hteam = s.next(); // read the home team from the file
ateam = s.next(); // read the away team from the file
hscore = s.nextInt(); //read the home team score from the file
ascore = s.nextInt(); //read the away team score from the file
System.out.print(hteam); // output the line of text to the console
System.out.print(hscore);
System.out.print(ateam);
System.out.println(ascore);
}
System.out.println("\nEOF"); // Output and End Of File message.
}
}
You're looking for s.next() instead of s.nextLine().
hteam = s.nextLine() reads the entire line "john : martin : 2 : 1", leaving nothing left for ateam.
Edit:
As you've said this still isn't working, I'd guess that you have an extra newline at the end of your input file, which is causing s.hasNext() to evaluate to true. This would cause the Scanner to trip up when it's getting the next input line.
Try Scanner s = new Scanner(System.in).useDelimiter("\\s*:\\s*|\\s*\\n\\s*"); to read multiple lines.
See implementation: http://ideone.com/yfiR2S
To verify that a line is in the correct format, I'd (with inspiration from osoblanco's answer) check that there are 4 words and that the last two are integers:
public static boolean verifyFormat(String[] words) {
// see endnote for isInteger()
return words.length == 4 && /*isInteger(words[2]) && isInteger(words[3])*/;
}
public static void main(String[] args) throws FileNotFoundException {
String hteam;
String ateam;
int hscore;
int ascore;
Scanner s = new Scanner(new BufferedReader(
new FileReader("results2.txt"))).useDelimiter("\\s*:\\s*|\\s*\\n\\s*");
while (s.hasNext()) {
String line = s.nextLine();
String[] words = line.split("\\s*:\\s*");
if(verifyFormat(words)) {
hteam = words[0]; // read the home team
ateam = words[1]; // read the away team
hscore = Integer.parseInt(words[2]); //read the home team score
ascore = Integer.parseInt(words[3]); //read the away team score
System.out.print(hteam); // output the line of text to the console
System.out.print(hscore);
System.out.print(ateam);
System.out.println(ascore);
}
}
System.out.println("EOF");
}
isInteger() can be found here.
I think scanning isn't quite what you want here. I would just use a BufferedReader and do ReadLine to handle 1 line each time through the for loop.
Then verify each line by the following:
1) String.split(":") and verify 4 pieces.
String [] linePieces = nextLine.split(":");
if(linePieces.length!=4)
{
//mark invalid, continue loop
}
2) Trim each piece
for(int i =0; i<4; i++)
linePieces[i] = linePieces[i].trim();
3) Verify piece 3 and piece 4 are numbers, Integer.parseInt with try/catch. In the catch block, count that the line is invalid.
try
{
name1=linePieces[0];
name2=linePieces[1];
score1=Integer.parseInt(linePieces[2]);
score2=Integer.parseInt(linePieces[3]);
//count as success and do logic
}catch(NumberFormatException e){
//invalid line
}

Adding new objects to a list; (For loop not working properly)

So I'm trying to add a names to a new list from a file called directory.txt that has 1000 objects that contain a first name, last name, and a phone number; something like this (Dodge, Nick 765-123-2312). When I run the program below without a "for loop" I can add the first object off the .txt file successfully and it prints it out. However when I add a for loop like, for(int i =0; i < 1000; i++), it for some reason jumps to the end off the list and inputs the 1000 object in the first spot and skips the rest. I can't figure this out! Thanks for the help.
new code;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import bsu.edu.cs121.names.Names;
import bsu.edu.cs121.quickSort.QuickSort;
public class NameTester {
public static void main(String[] args)throws FileNotFoundException {
ArrayList<Names> namelist= new ArrayList<Names>();
Scanner file = new Scanner(System.in);
System.out.println("Please enter the name of the phone book file: ");
String newFile = file.next();
File inputFile = new File("/Users/Latif/Desktop/workspace/CS121 Project4/src/" + newFile);
Scanner readFile = new Scanner(inputFile);
while (readFile.hasNextLine()){ //start while
String lastName = readFile.next();
String firstName = readFile.nextLine();
String phoneNumber = readFile.nextLine();
namelist.add(new Names(firstName, lastName, phoneNumber));
}
QuickSort newSort = new QuickSort(namelist);
System.out.println(namelist.get(1) + " " + namelist.get(2));
}
}
Because you are inserting the name data into index [0] of your nameslist array every time, so every loop you are replacing your previous data and at the very end you end up with one item that equals your last entry. You need to assign the proper array index to each.
nameslist[i] = new Names(first, last, number);

Count Word Pairs Java

I have this programming assignment and it is the first time in our class that we are writing code in Java. I have asked my instructor and could not get any help.
The program needs to count word pairs from a file, and display them like this:
abc:
hec, 1
That means that there was only one time in the text file that "abc" was followed by "hec". I have to use the Collections Framework in java. Here is what I have so far.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ArrayList;
// By default, this code will get its input data from the Java standard input,
// java.lang.System.in. To allow input to come from a file instead, which can be
// useful when debugging your code, you can provide a file name as the first
// command line argument. When you do this, the input data will come from the
// named file instead. If the input file is in the project directory, you will
// not need to provide any path information.
//
// In BlueJ, specify the command line argument when you call main().
//
// In Eclipse, specify the command line argument in the project's "Run Configuration."
public class Assignment1
{
// returns an InputStream that gets data from the named file
private static InputStream getFileInputStream(String fileName)
{
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(fileName));
}
catch (FileNotFoundException e) { // no file with this name exists
System.err.println(e.getMessage());
inputStream = null;
}
return inputStream;
}
public static void main(String[] args)
{
// Create an input stream for reading the data. The default is
// System.in (which is the keyboard). If there is an arg provided
// on the command line then we'll use the file instead.
InputStream in = System.in;
if (args.length >= 1) {
in = getFileInputStream(args[0]);
}
// Now that we know where the data is coming from we'll start processing.
// Notice that getFileInputStream could have generated an error and left "in"
// as null. We should check that here and avoid trying to process the stream
// data if there was an error.
if (in != null) {
// Using a Scanner object to read one word at a time from the input stream.
#SuppressWarnings("resource")
Scanner sc = new Scanner(in);
String word;
System.out.printf("CS261 - Assignment 1 - Matheus Konzen Iser%n%n");
// Continue getting words until we reach the end of input
List<String> inputWords = new ArrayList<String>();
Map<String, List<String>> result = new HashMap<String, List<String>>();
while (sc.hasNext()) {
word = sc.next();
if (!word.equals("---")) {
// do something with each word in the input
// replace this line with your code (probably more than one line of code)
inputWords.add(word);
}
for(int i = 0; i < inputWords.size() - 1; i++){
// Create references to this word and next word:
String thisWord = inputWords.get(i);
String nextWord = inputWords.get(i+1);
// If this word is not in the result Map yet,
// then add it and create a new empy list for it.
if(!result.containsKey(thisWord)){
result.put(thisWord, new ArrayList<String>());
}
// Add nextWord to the list of adjacent words to thisWord:
result.get(thisWord).add(nextWord);
}
//OUTPUT
for(Entry e : result.entrySet()){
System.out.println(e.getKey() + ":");
// Count the number of unique instances in the list:
Map<String, Integer>count = new HashMap<String, Integer>();
List<String>words = (List)e.getValue();
for(String s : words){
if(!count.containsKey(s)){
count.put(s, 1);
}
else{
count.put(s, count.get(s) + 1);
}
}
// Print the occurances of following symbols:
for(Entry f : count.entrySet()){
System.out.println(" " + f.getKey() + ", " + f.getValue());
}
}
}
System.out.printf("%nbye...%n");
}
}
}
The problem that I'm having now is that it is running through the loop below way too many times:
if (!word.equals("---")) {
// do something with each word in the input
// replace this line with your code (probably more than one line of code)
inputWords.add(word);
}
Does anyone have any ideas or tips on this?
I find this part confusing:
while (sc.hasNext()) {
word = sc.next();
if (!word.equals("---")) {
// do something with each word in the input
// replace this line with your code (probably more than one line of code)
inputWords.add(word);
}
for(int i = 0; i < inputWords.size() - 1; i++){
I think you probably mean something more like this:
// Add all words (other than "---") into inputWords
while (sc.hasNext()) {
word = sc.next();
if (!word.equals("---")) {
inputWords.add(word);
}
}
// Now iterate over inputWords and process each word one-by-one
for (int i = 0; i < inputWords.size(); i++) {
It looks like you're trying to read all the words into inputWords first and then process them, while your code iterates through the list after every word that you add.
Note also that your condition in the for loop is overly-conservative, so you'll miss the last word. Removing the - 1 will give you an index for each word.

regext copying second, third and fourth word

I am trying to get the 2nd, 3rd, and 4th word from a file into another file, so far I know how to read a file and I have been trying different things but I don't get it right the code to get the words. This program will read the file.
import java.util.Scanner;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
class PrintLines{
public static void main(String[] args) throws FileNotFoundException {
Scanner me = new Scanner(System.in);
System.out.print("File Name: ");
String s = me.next();
File inFile = new File(s);
Scanner in = new Scanner(inFile);
while(in.hasNextLine()){
String line = in.nextLine();
System.out.print(line + "\n");
}
in.close();
}
}
I have tried:
int i=0;
while(!Character.isDigit(in.charAt(i))){
i++;
}
to skip the first numbers, and then get the next three words, but I don't get it right:
986 Nasir 829 0.0040 Janine 1352 0.0069
I would appreciate any advice. Thank you
You can use String.split method
String[] split = line.split(" "); // split by space
System.out.println(split[1] + split[2] + split[3]); // watch out for the array's bounds

Categories