This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
**
I want to get text from the user and find the number of words in the text according to the word searched. BufferedReader sets the readLine method to get all rows with while, but the program gives a null pointer exception error
.
The program worked fine when I used a single readline.
I think the problem is in the while loop but I do not understand the problem.**
Please Write Path : C:\Users\Soul Collector\Desktop\yazi okuma
Please Write the Name of Text : buffer
Text File :
hi hello my name is suat
hello there
Hello
Write the key word :
hi
Exception in thread "main" java.lang.NullPointerException
at project2.Count.SingleWord(Count.java:83)
at project2.Project2.main(Project2.java:45)
C:\Users\Soul Collector\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 18 seconds)
if(press == 2 )
{
System.out.print("Please Write Path : ");
scan.nextLine();
path = scan.nextLine();
System.out.print("Please Write the Name of Text : ");
txtname = "\\"+ scan.nextLine() + ".txt";
finalpath = path + txtname;
File dosya = new File(finalpath);
FileReader fr = new FileReader(dosya);
BufferedReader br = new BufferedReader(fr);
String dizi;
while((dizi = br.readLine()) != null){
System.out.println(dizi);
}
br.close();
/* StringTokenizer st = new StringTokenizer(dizi);
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}*/
String search=null;
System.out.println("Write the key word : ");
search = scan.nextLine();
Scanner s = new Scanner(dizi.toLowerCase());
while (s.hasNext()) {
toplamkelime++;
if (s.next().equals(search))
kelime ++;
}
System.out.println("Key Word : " + search);
System.out.println("Count of key word : " + kelime);
System.out.println("\n\n\n Total Count of Words : " + toplamkelime );
}
You are assigning value to 'dizi' within while conditions, so it was overwritten everytime. When there is something to read, 'dizi' has a value and get printed inside the while loop.
When nothing else to read 'dizi' is then has null value. So when you call 'dizi.toLowerCase()' later down the line, you get null pointer exception.
To fix the issue you need to keep track of all read dizi by using List or append them to another String.
Related
Question:
I have this set of number in a .txt document, I want to use java.util.Scanner to detect the line feed in between 123, 456, and 789, print out the numbers in between the line feeds, is there any way to do so?
1 2 3
// \n here
4 5 6
// \n here
7 8 9
Output:
456
===========================================================================
Solutions that I tried:
(1) I tried using hasNextLine() method, however, it seems like hasNextLine() will tell me are there tokens in the next line and return a boolean instead of telling me is there \n. if (scan.hasNextLine()) { \\ do something }
(2) I also tried using: (However, using such condition will say "Syntax error on token 'Invalid Character'")
Scanner scan = new Scanner(new File("test.txt"));
// create int[] nums
while (scan.hasNext()) {
String temp = scan.next();
if (temp == \n) {
// nums.add(); something like this
}
}
System.out.print(nums); // something like this
I am thinking using \n as delimiters
ps. I did google and most of the results tell me to use .hasNextLine(), but I want it to identify a line feed (\n)
Scanner scans the next element by using new-line or whitespace as a delimiter by default. To let it read the whole content use scan.useDelimiter("\\Z").
Scanner scan = new Scanner(new File("test.txt"));
scan.useDelimiter("\\Z");
final String content = scan.next(); // content: "1 2 3\r\n\r\n4 5 6"
int index = 0;
System.out.println("Index of \\n");
while (index != -1) {
index = content.indexOf("\n", index);
if (index != -1) {
System.out.println(index);
// Or do whatever you wish
index++;
}
}
Output:
Index of \n
5
7
I'm not sure I understand 100% your question. So I'm assuming your file always will have 2 lines separated by ONLY ONE new line(\n). If I'm wrong please tell it.
String charsAfterNewLine = null;
//try-catch block with resources
//Scanner need to be closed (scan.close()) after finish with it
//this kind of block will do `scan.close()` automatically
try(Scanner scan = new Scanner(new File("test.txt"))){
//consume(skip) first line
if(scan.hasNextLine()){
scan.nextLine();
}else{
throw new Exception("File is empty");
}
//get second line
if(scan.hasNextLine()){
charsAfterNewLine = scan.nextLine();
}else{
throw new Exception("Missing second line");
}
}catch(Exception e){
e.printStackTrace();
}
System.out.println("charsAfterNewLine: " + charsAfterNewLine);
If you want simple way, without try-catch:
String charsAfterNewLine = null;
//throws FileNotFoundException
Scanner scan = new Scanner(new File("test.txt"));
if(scan.hasNextLine()){
//consume(skip) first line
scan.nextLine();
if(scan.hasNextLine()){
//get second line
charsAfterNewLine = scan.nextLine();
}else{
System.out.println("Missing second line");
}
}else{
System.out.println("File is empty");
}
scan.close();
System.out.println("charsAfterNewLine: " + charsAfterNewLine);
Results(for both):
Input:
(empty file)
Output:
File is empty
charsAfterNewLine: null
-----
Input:
1 2 3 4 5 6
Output:
Missing second line
charsAfterNewLine: null
-----
Input:
1 2 3\n4 5 6
Output:
charsAfterNewLine: 4 5 6
while (scanner.hasNext()) {
String data = scanner.nextLine();
System.out.println("Data: " + data);
if (data.isEmpty()) {
System.out.println("Found it");
break;
}
}
This question already has answers here:
Java: How to read a text file
(9 answers)
Closed 6 years ago.
I just got stuck with this BufferedReader and I can't make it to read the whole txt file..it reads only the first line!
FileReader fr = new FileReader("/Users/esson/Desktop/sonnets/sonnet3.txt");
BufferedReader br = new BufferedReader(fr);
String input = br.readLine();
List<String> output= (List) Arrays.asList(input.split(" "));
for(String word: output) {
int times = Collections.frequency(output, word);
System.out.println("" + word+ " -- "+times);
and the output is:
When -- 1
most -- 1
I -- 1
wink -- 1
then -- 1
do -- 1
mine -- 1
eyes -- 1
best -- 1
see, -- 1
You need to put BufferedReader.readLine() in a loop. For example:
while((text = BufferedReader.readLine()) != null)
Also, I think you should tag the question as Java and not Javascript
int lineNum;
for(String word: output) {
lineNum++;
int times = Collections.frequency(output, word);
System.out.println("" + word+ " -- "+times);
}
System.out.println("Line Number is " + lineNum);
This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 6 years ago.
I'm having some trouble trying to read a String and a Double from a txt file.
Here is my txt file:
Mike 300.50
John 260
Lisa 425.33
And here is the code I am using to read them:
reader = new Scanner();
while(reader.hasNext()){
name= reader.next();
salary = reader.nextDouble();
System.out.println(name + " " + salary + "\r\n");
}
Whenever I run this code, Exception in thread "main" java.util.InputMismatchException appears telling me the problem is in nextDouble().
Does anybody know how to solve this?
reader = new Scanner();
while(reader.hasNext()){
name= reader.next();
salary = reader.nextDouble();
System.out.println(name + " " + salary + "\r\n");
reader.nextLine();
}
Try this. What's happening is that the scanner is reading the empty line after every double, so name will be the empty line, and it will read (for example) John as the salary, and give you that exception.
So what I did was add that little line of code: reader.nextLine(); so it could skip that empty line. Hope this helps.
You could try this way:
while(reader.hasNextLine()){
String[] values = reader.nextLine().split("\\s+");
name= values[0];
salary = Double.valueOf(values[1]);
System.out.println(name + " " + salary + "\r\n");
}
you can use java.io.StreamTokenizer to read String and double.
StreamTokenizer split file into tokens with suitable datatype.
and by using some constants you can identify the token type.
like TT_NUMBER,TT_WORD
File f=new File("path of file");
StreamTokenizer st=new StreamTokenizer(new FileInputStream(file));
while(st.nextToken()!=StreamTokenizer.TT_EOF) //getting contents of file{
switch(st.ttype)
{
case StreamTokenizer.TT_EOF: break;
case StreamTokenizer.TT_NUMBER://it will read number always in double data type
no=st.nval;
break;
case StreamTokenizer.TT_WORD:
name=st.nval;
break;
}}
I'm taking in strings from a file and places them into a LinkedList. The program works fine when the .txt file has data in it.
However, when no data is in the .txt file it seems to throw an error...
exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1347)
at task.main.main(main.java:85)
Would an if/else statement fix this??
here's the code I'm using, which works if the .txt file has data.
//read in task data and place task data in a LL
String contentComplete = new Scanner(new File("completeData.txt")).useDelimiter("\\Z").next();
LineNumberReader lnr4 = new LineNumberReader(new FileReader(new File("completeData.txt")));
lnr4.skip(Long.MAX_VALUE);
lnr4.close();
realSize = lnr4.getLineNumber();
sizeOfIn = ((lnr4.getLineNumber() + 1) / 4); //divide by two because every 4 lines is equal to one input
//-----TEST number of data entries
System.out.println("Number of data entries from progressData.txt: " + sizeOfIn);
//-----Number of lines
System.out.println("Number of lines from progressData: " + realSize);
//splits userData.txt input 2 parts
String[] completeContent = contentComplete.split("\n");
//loads taskData into a LL
//update: changed i < sizeOfIn to i < realSize and it appears to be loading correctly
for(int i = 0; i < realSize; i++) {
task tempTask = new task(completeContent[i], completeContent[i+1], completeContent[i+2], completeContent[i+3]);
completeLL.add(tempTask);
i = i + 3;
You did not share all your code but considering the error message it seems you did not check if the scanner still had some tokens in its input before asking for the next token
for this purpose you should use scanner.hasNext() method:
hasNext()
Returns true if this scanner has another token in its input.
so do something like
while (scanner.hasNext()) {
// Process here the input from the scanner
// for example String data = scanner.next();
}
It could also be that you don't need to implement it in a loop but just with a if like:
if (scanner.hasNext()) {
// Process here....
}
I've saved a good few tweets in a text file with the following format:
Country:Brazil_result.txt Date: \r\n09/19/14 TweetTextExtract: #Brazil on track to becoming the leader of #wind #energy production in Latin America http://t.co/MFJjNPxodf
Country:Brazil_result.txt Date: \r\n09/19/14 TweetTextExtract: #ConceptOfficial FOLLOW ME GUYS PLEASE I LOVE YOU SO MUCH 💕BRAZIL LOVE YOU💙💚💛x16
Country:Brazil_result.txt Date: \r\n09/19/14 TweetTextExtract: #JamesFenn90 plenty teams travelled far more in Brazil from their bases to each game.I'm sure eng can manage a trip to Amsterdam etc etc
Now what I look to do is read in line by line from the text file and then split the line by "TweetTextExtract: " but for some reason I keep getting an ArrayIndexOutOfBoundsException:1 error and I can't see why as every line has the "TweetTextExtract: " term. Here is the error in the console:
Country:Brazil_result.txt Date: \r\n09/19/14 #ConceptOfficial FOLLOW ME GUYS
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at WhatToThink.main(WhatToThink.java:28)
The line with this tweet has the "TweetTextExtract: " term and so does the line succeeding it. I'm not to sure why this is breaking. Here is the code:
String folderPath = "C:/Users/me/workspace/Sentiment Analysis/Good Data";
File fin = new File(folderPath + "/Brazil_result" + ".txt");
FileInputStream fis = new FileInputStream(fin);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String line = null;
while ((line = br.readLine()) != null) {
String[] stringline = line.split("TweetTextExtract: ");
System.out.println(stringline[0] + stringline[1]);
//System.out.println(line);
}
br.close();
Your problem is almost surely a bad text encoding for your file. Save your file as UTF-8 (or UTF-16), then use
new InputStreamReader(fis, "UTF-8") //or UTF-16
If the encoding you use in the above constructor does not match the one of the text file, you will get gibberish and then the split won't work even on the first line.
If you want to keep the original encoding for you text file, just find out what it is and use it instead.
it actually doesn't give the exception for me when i run it.but how ever you can avoid this error by dynamically print element inside splited String.the following enhanced loop will gives you the same result ..
String[] stringline = line.split("TweetTextExtract: ");
for (String s : stringline) {
System.out.print(s);
}
System.out.println("");
and you can find your self how much element exist inside the stringline array by looking at the result.
You can use something like that:
if (line.contains("TweetTextExtract: ")){
String[] stringline = line.split("TweetTextExtract: ");
System.out.println(stringline[0] + stringline[1]);
}
else{
System.out.println("Line doesn't't contain \"TweetTextExtract: \"");
}