I am developing a program to read the keywords from a Java file. My goal is to display the total number of keywords excluding the keywords from the strings and comments.
My attempt
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Set;
import java.io.File;
import java.util.Arrays;
public class Exercise21_03 {
public static void main(String args[]){
String filename = args[0];
// Step 1: read the file.
File file = new File(filename);
if(file.exists()){
try {
System.out.println("The number of keywords in "+ filename + " is "+ countKeywords(file));
} catch (Exception e) {
System.out.print(e.getMessage());
}
}
else {
System.out.println("File "+ filename + " does not exist");
}
}
public static int countKeywords(File file) throws Exception {
// Array of all Java keywords + true, ffalse and null
String[] keywordString = {"abstract", "assert", "boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","for","final","finally","float","goto","if","implements","import","instanceof","int","interface","long","native","new","package","private","protected","public","return","short","static","strictfp","super","switch","synhronized","this","throw","throws","transient","try","void","volatile","while","true","false","null"};
Set<String> keywordSet = new HashSet<>(Arrays.asList(keywordString));
int count = 0;
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while((st = br.readLine()) != null){
String[] words = st.split(" ");
for(String word : words)
if(keywordSet.contains(word))
count++;
}
return count;
}
}
Welcome.java
public class Welcome {
public static void main(String[] args) {
// Display message Welcome to Java! on the console
// abstract
System.out.println("Welcome to Java!");
}
}
Expected:
java Exercise21_03 Welcome.java
The number of keywords in Welcome.java is 5
Actual
java Exercise21_03 Welcome.java
The number of keywords in Welcome.java is 6
How can I process this?
I believe this will do the trick
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Set;
import java.io.File;
import java.util.Arrays;
public class Exercise21_03 {
public static void main(String args[]){
String filename = args[0];
// Step 1: read the file.
File file = new File(filename);
if(file.exists()){
try {
System.out.println("The number of keywords in "+ filename + " is "+ countKeywords(file));
} catch (Exception e) {
System.out.print(e.getMessage());
}
}
else {
System.out.println("File "+ filename + " does not exist");
}
}
public static int countKeywords(File file) throws Exception {
// Array of all Java keywords + true, ffalse and null
String[] keywordString = {"abstract", "assert", "boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","for","final","finally","float","goto","if","implements","import","instanceof","int","interface","long","native","new","package","private","protected","public","return","short","static","strictfp","super","switch","synhronized","this","throw","throws","transient","try","void","volatile","while","true","false","null"};
Set<String> keywordSet = new HashSet<>(Arrays.asList(keywordString));
int count = 0;
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
while((st = br.readLine()) != null){
String[] words = st.split(" ");
if(Arrays.asList(words).contains("//"))
continue;
for(String word : words)
if(keywordSet.contains(word))
count++;
}
return count;
}
}
I am new to java, but not coding. I am trying to figure out java because it's part of my class this term and I am having a really hard problem grasping the idea of it and implementing things in java.
my problem Is that I am not sure if I am correctly using the arraylist to grab data from the scan of the file and input it into a arraylist to sort and print at a later time. I am just having issues picking up on java any help would be great since I am new to java.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.*;
public class MissionCount
{
private static ArrayList<String> list = new ArrayList<String>();
// returns an InputStream that gets data from the named file
private static InputStream getFileInputStream(String fileName) throws Exception {
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(fileName));
}
catch (FileNotFoundException e) { // no file with this name exists
inputStream = null;
throw new Exception("unable to open the file -- " + e.getMessage());
}
return inputStream;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("USage: MissionCount <datafile>");
//System.exit(1);
}
try {
System.out.printf("CS261 - MissionCount - Chad Dreher%n%n");
int crewcount = 0;
int misscount = 0;
InputStream log = getFileInputStream(args[0]);
Scanner sc = new Scanner(log);
sc.useDelimiter(Pattern.compile(",|\n"));
while (sc.hasNext()) {
String crewMember = sc.next();
list.add(crewMember);
String mission = sc.next();
list.add(mission);
}
sc.close();
// Add code to print the report here
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
InputStream log = getFileInputStream(args[0]);
Change that line to as follows :-
File log = new File(args[0])
that should work!
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]));
}
I have two text files namely - item.txt (file 1) and temp.txt (file 2). My goal is to search for a name in the file 1 and if found then replace it with a different name and write the updated line to file 2. Also, I have a method that checks for the lines for the string I searched in file 1. The lines that do not contain that string will be added to file 2.
So, here is where I'm stuck. Everything works fine except the part where I want to delete file 1 and rename file 2 by file 1 (i.e item.txt). Can someone please help me with any correction? I am still a beginner in Java, so my code might not be the best looking code as one might expect but this is what I tried so far. Thanks
The problem is when i compile the code the updated data is written to file2 and file1 which was supposed to get deleted doesn't delete. So, what could be the problem?
package project4;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class kitkat {
PrintWriter out,in;
Scanner in;
Scanner temp;
File file1 = new File("item.txt");
File file2 = new File("temp.txt");
public void write() throws FileNotFoundException {
out = new PrintWriter(file1);
out.println("User1"+ "\t"+"639755"+"\t"+"400");
out.println("User2"+ "\t"+"639725"+"\t"+"800");
out.close();
}
public void nfile() throws IOException {
n = new PrintWriter(new FileWriter(file2,true));
}
Scanner input = new Scanner(System.in);
String replacement = "User3";
String search;
String total;
public void search() {
System.out.println("Enter your search name");
search = input.nextLine();
total = search;
}
public void lolipop() throws IOException {
in = new Scanner(file1);
search();
while(in.hasNext()) {
String a,b,c;
a = in.next();
b = in.next();
c = in.next();
if(a.contains(search)) {
System.out.println("Your match is found"+search);
a = replacement;
System.out.println(a+b+c);
n.file();
n.println(a+"\t"+b+"\t"+c);
n.close();
}
}
}
public void jellybeans() throws IOException {
temp = new Scanner(file1);
while(temp.hasNext()) {
String p,q,r;
p = temp.next();
q = temp.next();
r = temp.next();
if(!(p.contains(total))) {
System.out.println(p+q+r);
n.file();
n.println(p+"\t"+q+"\t"+r);
n.close();
renamefile();
}
}
}
public void renamefile() {
file1.delete();
file2.renameTo(file1);
}
}
package project4;
import java.io.FileNotFoundException;
import java.io.IOException;
public class tuna {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
kitkat kt = new kitkat();
kt.lolipop();
kt.jellybeans();
}
}
Change this:
public void renamefile() {
String file1Path = file1.getAbsolutePath();
file1.delete();
file2.renameTo(new File(file1Path));
}
According to the Javadoc of File.renameTo(…) the behavior of this method is platform dependent. If the rename does not succeed it simply returns false without throwing an exception. So I guess this would be the case here.
You can try the newer (since Java 7) Files.move(…). This method is platform independent and has propper error handling, throwing exceptions with a problem description.
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[]>()