Error:Exception in thread "main" java.lang.NullPointerException - java

The readfile class is a class i made so i can read some strings from file.txt and then print them in the console:
package mainpackage;
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile(){
try {
x = new Scanner(new File("file.txt"));
} catch (Exception e) {
System.out.println("Could not find file");
}
}
public void readFile(){
while(x.hasNext()){
System.out.print(x.nextLine()+"\n");
}
}
public void closeFile(){
x.close();
}
}
But when i call the methods of the class in the main i get an error like this:
Exception in thread "main" java.lang.NullPointerException. This is the call in main:
public static void main(String [] args)
{
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
}
Any ideas? thank you

You should not catch exception in openFile() or if catch it, throw new exception if you got exception in openFile() method Scanner will be null and in other method got null pointer exception.
package mainpackage;
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile() throws Exception{
try {
x = new Scanner(new File("file.txt"));
} catch (Exception e) {
//in here throw (this/another) exception to caller or don't catch this exption
System.out.println("Could not find file");
throw new Exception("Could not find file");
}
}
public void readFile(){
while(x.hasNext()){
System.out.print(x.nextLine()+"\n");
}
}
public void closeFile(){
x.close();
}
}
And main driver for testing:
public static void main(String [] args)
{
try {
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
} catch (Exception e) {
e.printStackTrace();
System.out.println("got exception");
}
}

If exception is thrown, what value is under "x"?
What happend next?
(You should use debugger to check readFile() func)
I need to clarify: Questions were asked to make #Marios P sit up and think.

Related

How do I throw an exception and scan again if the input is not bigDecimal?

I want to scan bigDecimal but if the input scanned is not bigdecimal it should throw an custom exception and scan it again?
I am trying the below code but not able to reach conclusion.
Code:
import java.util.*;
import java.io.*;
class WrongInputException extends Exception{
WrongInputException(String s){
super(s);
}
}
public class Main
{
public static void main(String[] args) throws WrongInputException
{
try
{
int number;
Scanner sc = new Scanner(System.in);
while (!sc.hasNextBigDecimal())
{
throw new WrongInputException("Wrong data type of input.....");
}
number = sc.nextInt();
System.out.println(number);
} catch(NumberFormatException e) {
System.out.println(e.getMessage());
}
}
}
The problem is that you are not handling the Exception you throw
You should add a try catch block to handle it inside thw while an also add a sc.next(); to avoid the endless loop
while (!sc.hasNextBigDecimal())
{
try {
throw new WrongInputException("Wrong data type of input.....");
}catch (WrongInputException e) {
e.printStackTrace();
}finally {
sc.next();
}
}
Note that your try catch has no sence since you have your exception to throw
Sacnner#hasNextBigDecimal does not make sense while scanning input from the keyboard. It can be used while scanning values from a file or a Scanner on a String object.
You can do it as follows:
import java.math.BigDecimal;
import java.util.Scanner;
class WrongInputException extends Exception {
public WrongInputException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) throws WrongInputException {
BigDecimal number;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a BigDecimal: ");
try {
number = sc.nextBigDecimal();
System.out.println(number);
} catch (Exception e) {
throw new WrongInputException("Wrong data type of input.....");
}
}
}
A sample run:
Enter a BigDecimal: 1234
1234
Another sample run:
Enter a BigDecimal: xyz
Exception in thread "main" WrongInputException: Wrong data type of input.....
at Main.main(Main.java:19)
A demo of Scanner on a String object:
import java.math.BigDecimal;
import java.util.Scanner;
class WrongInputException extends Exception {
public WrongInputException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) throws WrongInputException {
BigDecimal number = null;
Scanner sc = new Scanner("123 987654321 12.34");
try {
while (sc.hasNextBigDecimal()) {
number = sc.nextBigDecimal();
System.out.println(number);
}
} catch (Exception e) {
throw new WrongInputException("Wrong data type of input.....");
}
}
}
Output:
123
987654321
12.34

error related to exception handling in java

How to resolve this error? I have tried using throws to throw FileNotFoundException but still same error.
Compile-Time Error : "Default constructor cannot handle exception type Exception thrown by the implicit super constructor. Must define an explicit constructor "
CODE :
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileOne {
Scanner sc = new Scanner(System.in);
String file_name = sc.nextLine();
File obj = new File(file_name);
Scanner reader_obj = new Scanner(obj); // <--- error in this line
public static void main(String args[]) {
FileOne f = new FileOne();
f.create();
f.writeFile();
f.readFile();
}
void create() {
try {
System.out.println("Enter a file name");
if (obj.createNewFile()) {
System.out.println("file name is" + obj.getName());
} else {
System.out.println("Already exists");
}
} catch (IOException e) {
System.out.println("error occured while creating");
}
}
//method to write in file
void writeFile() {
try {
FileWriter w = new FileWriter(obj);
w.write("Learning files now");
w.close();
} catch (IOException e) {
System.out.println("Exception occured while writing a file");
}
}
//method to read
/* use the Scanner class to read the contents of the text file created */
void readFile() {
while (reader_obj.hasNextLine()) {
String data = reader_obj.nextLine();
System.out.println(data);
}
reader_obj.close();
}
}
The line Scanner reader_obj=new Scanner(obj);, which is implicitly called by the default constructor, may throw a FileNotFoundException, which is a checked exception and must be handled.
One way of doing so is explicitly defining a no-arg constructor:
public FileOne() throws FileNotFoundException {
}
Although, if you're going to do that, you should consider moving the members' initialization in to it for clarity's sake.
Errors Resolved:
I used throws to throw exceptions in main() and reading() method.
Used FileReader class to read the data from the given input file
Final Code:
public class FileOne {
Scanner sc=new Scanner(System.in);
String file_name=sc.nextLine();
File obj=new File(file_name);
//method for creating a file
void create(){
try{
if(obj.createNewFile()){
System.out.println("file name is"+obj.getName());
}
else{
System.out.println("Already exists");
}
}
catch(IOException e){
System.out.println("error occured while creating");
}
}
//method to write in file
void writeFile(){
try{
FileWriter w=new FileWriter(obj);
w.write("Learning files now");
w.close();
}
catch(IOException e){
System.out.println("Exception occured while writing a file");
}
}
void reading() throws FileNotFoundException,IOException{
FileReader reader=new FileReader(file_name);
int i;
while((i=reader.read())!=-1){
System.out.print((char)i);
}
reader.close();
}
public static void main(String args[])throws FileNotFoundException,IOException{
FileOne f=new FileOne();
f.create();
f.writeFile();
f.reading();
}
}
Add the constructor as below :
public FileOne () throws FileNotFoundException {
}
Edit your void main () as below (You need to throw the exception from main as well) :
public static void main(String args[]) throws FileNotFoundException {
FileOne f = new FileOne();
f.create();
f.writeFile();
f.readFile();
}

How do I fix Illegal Start of Expressions with all of my methods?

I have my code. I think it's all right, but it is not. It keeps telling me at the beginning of each method that there is a ';' expected and it's also an 'illegal start of expression' with the void. I do not know how to fix it. Can someone please help me fix these errors?
Here's an example of the Errors:
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:203: error: ';' expected
void arrayList **()** throws FileNotFoundException();
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: illegal start of expression
**void** output()
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: ';' expected
void output **()**
My code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp{
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// scrubber();
//Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
void arrayList() throws FileNotFoundException();
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
//Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
// void scrubber()
// {
//
// }
//
//
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
}
You should use a Java IDE like Eclipse when programming Java, it would point out to you the most obvious mistakes in your code.
You missed a } after the while loop for your readFile() method (thanks to Sweeper for this one).
The syntax in your arrayList() method is wrong.
void arrayList() throws FileNotFoundException(); {
No semicolon at the end of this defintion, no parenthesis at the end too, you are describing the class, not a method. Here is the correct way:
void arrayList() throws FileNotFoundException {
1 useless } at the end of your class file.
Find below your code, with a proper layout and without syntax errors. Please use an IDE next time, that would avoid you an awful lot of trouble.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam ?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
}
void arrayList() throws FileNotFoundException
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
// Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
throws FileNotFoundException();
This should be
throws FileNotFoundException
and similarly in all cases.
Rather trivial. Don't just make up the syntax. Look it up.

error: exception java.io.FileNotFoundException

Can anyone tell me why I have this error: exception java.io.FileNotFoundException is never thrown in body of corresponding try statement.
I try to save text from a file in an ArrayList.
import java.io.*;
import java.util.*;
public class EditMembership
{
public static void main(String[] args) throws java.io.FileNotFoundException
{
ArrayList<String> member = readFromFile("database.txt");
System.out.println(Arrays.toString(member.toArray()));
}
public static ArrayList readFromFile(String fileName) throws java.io.FileNotFoundException
{
Scanner x = new Scanner(new File(fileName));
ArrayList<String> memberList = new ArrayList<String>();
try {
while (x.hasNextLine())
{
memberList.add(x.nextLine());
}
x.close();
}
catch(FileNotFoundException e)//here is the error
{
e.printStackTrace();
}
return memberList;
}
}
Because you aren't doing anything to open a file within the try block it's impossible to throw a File Not Found. Move the Scanner declaration down within the try block and I would expect that'll fix it. At that point you can remove the "throws" declaration from your method signature.

How can I read a file from a path relative of my Main class in Java?

On the same directory of my Main.java file, I have a package/folder named database, and inside the database package I have a file named Data.txt.
This is my code of Main.java, but it is throwing this error:
java: exception java.io.FileNotFoundException
How can I get the file from a relative file? I'm used to web development, and usually something with a . dot like "./folder/file.txt" works.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
readFile();
}
public static void readFile() {
File file = new File("./database/Data.txt");
Scanner scanner = new Scanner(file);
try {
while (scanner.hasNextLine()) {
int i = scanner.nextInt();
System.out.println(i);
}
scanner.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You are not importing FileNotFoundException class. also, scanner statement throws the exception which should inside try. Solution is as below.
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
readFile();
}
public static void readFile() {
File file = new File("database/Data.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
int i = scanner.nextInt();
System.out.println(i);
}
scanner.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Only check if those content can read using scanner or not. Content having int properly. otherwise it will throw java.util.InputMismatchException.
Are you working on a mac or windows system.
I am on windows and ".\database\Data.txt" would most probably work depending on where the file is in your file structure.

Categories