This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I'm learning about BufferedReaders and a few other classes and am making a small program that takes a text file with information about courses I've taken and calculates my GPA. Here's what I have so far:
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class GradeFormatter {
public static ArrayList<String[]> courses;
public static double unitsAttempted;
public static double unitsPassed;
public static double gradePoints;
public static double gpa;
public static void main(String[] args) {
try {
FileReader fileReader = new FileReader("grades.txt");
BufferedReader reader = new BufferedReader(fileReader);
while (true) {
String line = reader.readLine();
if (line == null) {
break;
} else {
processLine(line);
}
}
reader.close();
} catch (IOException e) {
System.out.println("File does not exist.");
}
}
public static void processLine(String line) {
String[] newCourse = line.split("\\t");
courses.add(newCourse);
}
}
I'm getting the following output when I try to run the program:
Exception in thread "main" java.lang.NullPointerException
at GradeFormatter.processLine(GradeFormatter.java:34)
at GradeFormatter.main(GradeFormatter.java:23)
Could anyone help me out with why I'm getting this null pointer exception? I cannot seem to figure out where it's coming from.
You should initilize the ArrayList courses ArrayList<String[]> courses = new ArrayList<String[]>()
Related
Stacktrace
Can't figure out why I'm receiving NoSuchElement errors as the build works perfectly on my PC but my Mac doesn't.
Not sure if it's an error with my code - referring to the issue where the Scanner is trying to read a line that doesn't exist. But surely it can't be as my PC runs it perfectly.
package equipment;
import java.util.*;
import java.io.*;
public class Equipment
{
public static void main(String[] args)
{
String line;
String description;
int quantity;
double value;
try
{
Scanner scFile = new Scanner (new File("Stock.txt"));
System.out.println("Product\tQuantity\tPrice");
System.out.println("-------\t--------\t------");
while (scFile.hasNext())
{
line = scFile.nextLine();
Scanner scTokens = new Scanner(line).useDelimiter("&");
description = scTokens.next();
quantity = scTokens.nextInt();
value = scTokens.nextDouble();
System.out.println(description + quantity + value);
}
scFile.close();
}
catch (FileNotFoundException f)
{
System.out.println("Error - File Not Found");
}
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have a small assignment for uni which I seem to be stuck with. The application is suppose to be a quiz program which reads questions and answers from a text files and stores them like a flash card. My problem is that my buffered reader seems to be returning the nullPointer exception when it tries to read from the file. I'm unsure why this is. I will provide all code and highlight the error in bold. After doing a bit of debugging I found that the readLine method was returning null. Any thoughts? Thanks a lot. Error is at String[] line = getLine().split(":");
text file is in the format question:answer
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class Quiz {
private ArrayList<FlashCard> flashCards;
public static void main(String[] args){
Quiz quiz1 = new Quiz();
}
public Quiz(){
FlashCardReader cardReader = new FlashCardReader();
try {
if(cardReader.isReady()==true){
flashCards = cardReader.getFlashCards();
play();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void play(){
Scanner userInput = new Scanner(System.in);
String answer = userInput.nextLine();
for(FlashCard card: flashCards){
System.out.println(card.getQuestion());
System.out.println("********************");
sleep(10000);
System.out.println("Enter your answer:");
answer = userInput.nextLine();
if(card.getAnswer() == answer){
System.out.println("Correct.");
}else{
System.out.println("Incorrect. The correct answer is " + card.getAnswer() + ".");
}
}
}
private void sleep(int x){
try {
Thread.sleep(x);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class FlashCardReader {
BufferedReader reader;
public FlashCardReader(){
try {
reader = new BufferedReader(new FileReader("Questions.txt"));
} catch (FileNotFoundException e) {
System.err.println(e.toString());
}
}
public String getLine() throws IOException{
return reader.readLine();
}
public Boolean isReady() throws IOException{
return reader.ready();
}
public ArrayList<FlashCard> getFlashCards(){
ArrayList<FlashCard> flashcards = new ArrayList<FlashCard>();
try {
for(int i = 1; i <= reader.lines().count(); i++){
**String[] line = getLine().split(":");**
System.out.println(line[0]);
flashcards.add(new FlashCard(line[0],line[1]));
}
} catch (IOException e) {
System.err.println(e);
e.printStackTrace();
}
return flashcards;
}
}
public class FlashCard {
private String question;
private String answer;
public FlashCard(String question, String answer){
this.question = question;
this.answer = answer;
}
public String getQuestion(){
return question;
}
public String getAnswer(){
return answer;
}
}
How about changing the for loop to while loop to avoid null condition. As you cannot be sure that your code starts from line one as you expect by assigning i to 1.
String lines ;
while((lines = getLine()) != null){
String[] lineArray = lines.split(":");
System.out.println(lineArray[0]);
flashcards.add(new FlashCard(lineArray[0],lineArray[1]));
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
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.
Closed 7 years ago.
Improve this question
Hi I am getting this error on my Java code
Syntax error on token "(", ; expected
I am trying to make a function, maybe my syntax is not correct.
this is my code:(I point where the error is)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
String ruta = "C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt";
File archivo = new File(ruta);
String linea = null;
try {
FileReader lector = new FileReader(archivo);
BufferedReader buff = new BufferedReader(lector);
while( ( linea = buff.readLine() ) != null ) {
System.out.println(linea);
}
buff.close();
lector.close();
} catch(FileNotFoundException ex) {
} catch(IOException ex) {
}
final int countWord(String codigo, File archivo)<-------Error Here
{
int count = 0;
Scanner scanner = new Scanner("C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt");
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(codigo))
count++;
}
return count;
}
}
}
Sorry if it is something really simple, this is all in my main class.
Move the } from the bottom of your code to the end of the main method.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
String ruta = "C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt";
File archivo = new File(ruta);
String linea = null;
try {
FileReader lector = new FileReader(archivo);
BufferedReader buff = new BufferedReader(lector);
while( ( linea = buff.readLine() ) != null ) {
System.out.println(linea);
}
buff.close();
lector.close();
} catch(FileNotFoundException ex) {
} catch(IOException ex) {
}
}
final int countWord(String codigo, File archivo){
int count = 0;
Scanner scanner = new Scanner("C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt");
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(codigo))
count++;
}
return count;
}
}
You're missing a closing brace on your main method, just before the line that's giving you the error message. Unfortunately, sometimes syntax errors that are not obvious at the point they occur end up making something later appear wrong, and so the compiler's error message can be misleading.
What can help is using a good editor that understands the language. You might already be doing that. If so, the fact that your editor placed the first line of your countWord definition at the same level as your main method body is a hint that you didn't properly close out the latter.
I re-formated your code, so the error gets more obvious
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class HelloWorld {
public static void main(String... args) {
String ruta = "C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt";
File archivo = new File(ruta);
String linea = null;
try {
FileReader lector = new FileReader(archivo);
BufferedReader buff = new BufferedReader(lector);
while ((linea = buff.readLine()) != null) {
System.out.println(linea);
}
buff.close();
lector.close();
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
} // Moved this parenthesis up
final int countWord(String codigo, File archivo) { // <-------Error Here
int count = 0;
Scanner scanner
= new Scanner("C:\\Users\\HernanEi\\Desktop\\contadoresInternet.txt");
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(codigo)) {
count++;
}
}
return (count);
}
}
Some remarks on your code:
you should take a look at the try-with-resources.
you should definitely write your code with english variable-/attribute names
even if you can neglect some parenthesis (i.e. ifs with only a single line of code), you should write them for clarity
This question already has answers here:
Java: Check if command line arguments are null
(6 answers)
Closed 7 years ago.
Pretty much the program I am writing has a 'Usage' method which gets called if args[0] contains nothing. Here is the program, When ever I try something of the sort such as (args[0].isEmpty()...) I get an ArrayIndexOutOfBounds.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class Desk {
public static void main(String[] args) throws FileNotFoundException {
if(args[0].isEmpty()){
Usuage();
}
try{
count(new TreeSet<String>(), new File("C:\\Users\\Ceri\\workspace1\\Cw2Task2\\src\\" + args[0]));
}catch(FileNotFoundException e){
System.out.println("Error: File not found");
}
}
private static void count(TreeSet<String> treeSet, File file) throws FileNotFoundException {
// TODO Auto-generated method stub
Scanner in = new Scanner(file);
while(in.hasNext()){
String temp = in.next();
treeSet.add(temp);
}
System.out.println("There are " + treeSet.size() + "Unique words in the text file ");
}
private static void Usuage(){
System.out.println("Not entered");
}
}
You should check :
if(args.length < 1) {
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
I want to convert my names.rtf file which contains (the names of people(String) names.rtf = ("ABHISHEK","ANKIT",........"ASHISH") ) into single String[] name such that name={"ABHISHEK","ANKIT",......"ASHISH"}
Following is my code suggest please.
import java.io.*;
import java.util.Scanner;
public class FileScan {
public static void main(String[] args) throws IOException {
Scanner s = null;
String thestring ="";
try {
s = new Scanner(new BufferedReader(new FileReader("/Users/abhishekkumar/Desktop/names1.rtf")));
while (s.hasNextLine()) {
thestring+=(s.nextLine());
thestring+="\n";
}
} finally {
if (s != null) {
s.close();
}
}
System.out.println(thestring);
}
}
First of all, why are you using the scanner class in this way to read file ,with bufferedReader,fileReader etc ? Use :-
File file = new File("filename.fileformat");
Scanner scanner = new Scanner(file);
A possible solution looking at your file in the comments would be:-
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// Location of file to read
File file = new File("data.rtf");
String line="";
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
//System.out.println(line);
}
String[] nameArray=line.split(",");
for(String s:nameArray){
System.out.print(s+" "); //parse the array to verify entries
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}