This is probably a stupidly easy question but it's been a long day.
I'm trying to remove the comments from a java program. To do this i'm trying to use replaceAll, but I'm not sure how to run all 3 of the statements on the file at the same time. Is there a way besides regex that I should be using here? Or is there an easy fix? Here is my code:
import java.io.*;
import java.util.*;
public class Ex13Ch6 {
public static void main(String args[]) throws FileNotFoundException {
File file = new File("killComment.txt");
Scanner s = new Scanner(file);
stripComments(s);
}
public static void stripComments(Scanner s) {
while(s.hasNext()) {
String input = s.nextLine();
String regex = "/*";
// Removes /* from the file
String change = input.replaceAll("/\\*", "");
// Removes */ from the file
String change2 = input.replaceAll("\\*/", "");
// Removes // from the file
String change3 = input.replaceAll("//", "");
System.out.println(change2);
}
}
}
Here is the text file:
// Name: Conner Murowchick
// Email: conner.murowchick#bellevuecollege.edu
// Program description:
/*
Write a method called flipLines that accepts a Scanner for an input
file and writes to the console the same file's contents with each
pair of lines reversed in order. If the file contains an odd number
of lines, leave the last line unmodified.
*/
// importing file and Scanner
import java.io.*;
import java.util.*;
import java.io.FileNotFoundException;
public class Ex7Ch6 {
public static void main(String[] args) throws FileNotFoundException{
// Calling the flipLines method
flipLines();
}
public static void flipLines() throws FileNotFoundException {
// Calls a new file, "jabberwocky.txt"
File file = new File("jabberwocky.txt");
// Scans the file "jabberwocky.txt" and creates a Scanner s to read it.
Scanner s = new Scanner(file);
// creates a new variable "noOfLines" that is an integer equal to 0
int noOfLines = 0;
// A while loop that checks if there is another line to scan.
while(s.hasNextLine()) {
// If there is another line to scan, the scanner goes to the next line
s.nextLine();
// The variable noOfLines increments while this loop runs.
noOfLines++;
}
// Creates a new scanner called s2 that reads the file "jabberwocky.txt"
Scanner s2 = new Scanner(file);
// A for loop that runs when i is less than half of the variable noOflines
for (int i=0; i < (noOfLines / 2); i++) {
// String called line1 that equals scanner s2 reading the next line of text
String line1 = s2.nextLine();
// String called line2 that equals scanner s2 reading the next line of text
String line2 = s2.nextLine();
// Prints the Second line first
System.out.println(line2);
// Prints the First line second
System.out.println(line1);
}
}
}
Your solution cannot work because it's losing the changes everytime.
Try:
// Removes /* from the file
String change = input.replaceAll("/\\*", "");
// Removes */ from the file
String change2 = change.replaceAll("\\*/", "");
// Removes // from the file
String change3 = change2.replaceAll("//", "");
You can even concat in one statement:
String change = input.replaceAll("/\\*", "").replaceAll("\\*/", "").replaceAll("//", "");
Anyway, this won't remove the comments, it will just "uncomment" some comments. As user202729 is suggesting, you need a parser to remove the multi line comments. As for the commented single lines, you need a regular expression more specific, like:
"/^[\s]*[/]+.*/"
Related
I'm having trouble properly getting one line of text at a time from a file onto a queue without taking the whole file into the queue. For example, I'd like only Write a program that reads a Java source file as an argument and produces an index of all identifiers in the file. For each identifier, print all lines in which it occurs. For simplicity, we will consider each string consisting only of letters, numbers, and underscores an identifier.
Declare a Scanner in for reading from the source file and call in.useDelimiter("[^A-Za-z0-9_]+") Then each call to next returns an identifier.
public class Main { to get added to the queue but instead the whole file text is put into the queue instead of a line at a time. Sorry if my question is unclear
// Write a program that reads a Java source file as an argument and produces an index of all
// identifiers in the file. For each identifier, print all lines in which it occurs. For simplicity,
// we will consider each string consisting only of letters, numbers, and underscores an identifier.
// Declare a Scanner in for reading from the source file and call in.useDelimiter("[^A-Za-z0-9_]+").
// Then each call to next returns an identifier.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class E_15 {
public static void main(String[] args) throws FileNotFoundException
{
// get scanner input from file
Scanner fileInput = new Scanner(new File ("C:/Users/ramir/IdeaProjects/PA_7/src/Main.java"));
Queue<String> test = new LinkedList<String>();
ArrayList<String> phrase = new ArrayList<String>();
/*
List<String> result = new ArrayList<String>();
Scanner s = new Scanner(is);
s.useDelimiter(delimiter);
*/
// Iterates till end of file
while (fileInput.hasNextLine())
{
// Here is the issue. Data will end up
// containing the whole file instead of only that line
String data = fileInput.nextLine();
Scanner in = new Scanner(data);
in.useDelimiter("[^A-Za-z0-9_]+");
// I believe around here or before is the issue that I'm having.
// It adds all the file instead of only that line
// Also trying to figure out how to display each line that it's displayed on
// What the first one should look like for example
// 0: public occurs in:
// public class Main {
// public static void main(String[] args) {
//System.out.println(data);
test.add(data);
while(in.hasNext())
{
// Getting each phrase/word into ArrayList
String token = in.next();
phrase.add(token);
}
in.close();
}
int index = 0;
// This part works fine
for(String num : phrase)
{
// printing the key
System.out.println(index + ": " + num + " occurs in:");
// printing the values
// This to print out what
for(String line : test)
{
System.out.println(line);
}
System.out.println();
++index;
}
}
}
// Just java class get file front
// This is fine
public class Main {
public static void main(String[] args) {
int a_1 = 100;
System.out.println(a_1);``
}
}
I'd like it to only show System.out.println(a_1) because the line that's it's on See This
. I'm also have trouble printing it in all the lines that occur.
import java.io.*;
import java.util.Scanner;
public class ReadLineByLineExample2
{
public static void main(String args[])
{
try
{
//the file to be opened for reading
FileInputStream fis=new FileInputStream("Demo.txt");
Scanner sc=new Scanner(fis); //file to be scanned
//returns true if there is another line to read
while(sc.hasNextLine())
{
System.out.println(sc.nextLine()); //returns the line that was skipped
}
sc.close(); //closes the scanner
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Try studying the above code. I hope it will help. Otherwise, you might need to open this link for more detail.
I am currently working on a personal project outside of class and am running into some issues while reading in a text file into a linked list. When reading in the first double I get a
java.lang.NumberFormatException: empty String
error. I added a print line into the program to print out what I am trying to parse into a double and the variable is in fact, not empty, and is in fact a double.
Like I said above, I added a print line to print out the string I am trying to parse into a double and it seems to be okay. Here is the String that is read in and split into the array I am printing from:
500.0 % 04/05/2019 % This is paycheck 1 % true % 49.5
I have to parse two strings into doubles and I only run into problems with the first one. When I comment out the first double being parsed, the program runs with no problems. Here is the full output from running to program
*File loading*
*500.0*
*Exception in thread "main" java.lang.NumberFormatException: empty String*
*at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)*
*at sun.misc.FloatingDecimal.parseDouble(Unknown Source)*
*at java.lang.Double.parseDouble(Unknown Source)*
*at fileHandling.readPaycheck(fileHandling.java:194)*
*at UserMenu.main(UserMenu.java:20)*
The problems happens in the "Splitting the array into its appropriate temp variables" section in this line of code:
payCheckAmount = Double.parseDouble(tempArray[0]);
Here is the code for the method this is in
public void readPaycheck(LinkedList<PayCheck> paycheck) throws IOException {
// Declare Variables
Scanner sc = new Scanner(payChecks); // Scanner used to read in from the payChecks text file
String temp; // A string used to hold the data read in from the file temporarily
String[] tempArray; // A String array used to temporarily hold data from the text file
double payCheckAmount; // A double holding the amount of the paycheck
String paycheckDate; // A string holding the date of the paycheck
String description; // A string holding a description of the paycheck
boolean payCheckSplit; // A boolean stating if the paycheck has been split or not
double amountUnSplit; // A double
// A while loop that runs while the text file still has data in it
while (sc.hasNextLine()) {
// Reading in a new line from the paycheck file
temp = sc.nextLine();
// Splitting the line into an array
tempArray = temp.split(" % ");
// Temp output used for testing of the issue at hand
System.out.println(tempArray[0]);
// Splitting the array into its appropriate temp variables
payCheckAmount = Double.parseDouble(tempArray[0]);
paycheckDate = tempArray[1];
description = tempArray[2];
payCheckSplit = Boolean.parseBoolean(tempArray[3]);
amountUnSplit = Double.parseDouble(tempArray[4]);
// putting the temp variables into a temp paycheck object
PayCheck tempCheck = new PayCheck(payCheckAmount, paycheckDate, description, payCheckSplit, amountUnSplit);
paycheck.add(tempCheck);
}
}
Edit:
Here is a Minimal, Complete, and Verifiable example of the problem I am running into:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class test {
public static void main(String[] args) throws IOException {
// Declare Variables
File payChecks = new File("C:\\Users\\zwtw\\Documents\\paychecks.txt");
Scanner sc = new Scanner(payChecks);
while (sc.hasNextLine()) {
String temp = sc.nextLine();
String[] tempArray = temp.split(" % ");
System.out.println(tempArray[0]);
// Splitting the array into its appropriate temp variables
double payCheckAmount = Double.parseDouble(tempArray[0]);
String paycheckDate = tempArray[1];
String description = tempArray[2];
boolean payCheckSplit = Boolean.parseBoolean(tempArray[3]);
double amountUnSplit = Double.parseDouble(tempArray[4]);
}
}
}
Here is the content of the text file mentioned in the code above:
500.0 % 04/05/2019 % This is paycheck 1 % true % 49.5
450.0 % 04/09/2019 % This is paycheck 2 % true % 49.75
Your text file likely contains empty lines. You can either remove the new lines in the text file, change how the text file is created, or just skip the empty lines when you read it.
This is how you skip the empty lines:
while (sc.hasNextLine()) {
String temp = sc.nextLine();
if (temp.equals("")) { continue; } // <--- notice this line
String[] tempArray = temp.split(" % ");
System.out.println(tempArray[0]);
// Splitting the array into its appropriate temp variables
double payCheckAmount = Double.parseDouble(tempArray[0]);
String paycheckDate = tempArray[1];
String description = tempArray[2];
boolean payCheckSplit = Boolean.parseBoolean(tempArray[3]);
double amountUnSplit = Double.parseDouble(tempArray[4]);
}
}
Using command line, I am supposed to enter a file name that contains text and search for a specific word.
foobar file.txt
I started writing the following code:
import java.util.*;
import java.io.*;
class Find {
public static void main (String [] args) throws FileNotFoundException {
String word = args[0];
Scanner input = new Scanner (new File (args[1]) );
while (input.hasNext()) {
String x = input.nextLine();
}
}
}
My program is supposed to find word and then print the whole line that contains it.
Please be specific since I am new to java.
You are already reading in each line of the file, so using the String.contains() method will be your best solution
if (x.contains(word) ...
The contains() method simply returns true if the given String contains the character sequence (or String) you pass to it.
Note: This check is case sensitive, so if you want to check if the word exists with any mix of capitalization, just convert the strings to the same case first:
if (x.toLowerCase().contains(word.toLowerCase())) ...
So now here is a complete example:
public static void main(String[] args) throws FileNotFoundException {
String word = args[0];
Scanner input = new Scanner(new File(args[1]));
// Let's loop through each line of the file
while (input.hasNext()) {
String line = input.nextLine();
// Now, check if this line contains our keyword. If it does, print the line
if (line.contains(word)) {
System.out.println(line);
}
}
}
Firest you have to open file and then read it line by line and check that word is in that line on not. see the code below.
class Find {
public static void main (String [] args) throws FileNotFoundException {
String word = args[0]; // the word you want to find
try (BufferedReader br = new BufferedReader(new FileReader("foobar.txt"))) { // open file foobar.txt
String line;
while ((line = br.readLine()) != null) { //read file line by line in a loop
if(line.contains(word)) { // check if line contain that word then prints the line
System.out.println(line);
}
}
}
}
}
I have a with the hentAntall method in my code below. It's supposed to find the search word inside a txt file. I don't get any sort of error. It just won't print out any of the two possible lines.
This method has to access a constructor first to get the search word, and then it has to find that search word in the txt file and add to count. The constructor gets the search word from another class. Like this new lolz("searchword").hentAntall();
(I apologize for the stupid naming in this program, but it's just a copy of one of my programs, and I'm just trying to correct it without screwing up the original.)
import java.io.File;
import java.util.Scanner;
public class lolz {
private String sokeord=null;
private int antall = 0;
// Constructor
lolz(String searchword) throws Exception{
this.sokeord = searchword;
}
//toString method, to print in the same format.
#Override
public String toString(){
return "\nSokeordet er: " + sokeord+ "\n";
}
// Gets the ammount of the searchword
public int hentAntall() throws Exception{
File file = new File("Hvorfor.txt");
Scanner readfile = new Scanner(file);
while (readfile.hasNextLine()){
String nextline = readfile.nextLine();
if (nextline.equalsIgnoreCase(sokeord)) {
antall ++;
System.out.println("Antallet av:" + sokeord + "er " + antall);
}
else {System.out.println("Error no such search word in the given text");}
}
return antall;
}
// void methode to increase the count of a searcheword.
void oekAntall() {
antall++;
}
}
This is the other class that calls on this method, and also give information to the constructor.
public class Main {
public static void main(String[] args) throws Exception {
new lolz("fungerer").hentAntall();
}}
Also tried some of the suggestions and they did not work, I only get a the message Process finished with exit code 0.
Your Issue:
You are trying to compare a Scanner variable with a String Variable?!!!
Explanation:
you try to compare content of Scanner which is
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=0][match
valid=true][need input=false][source
closed=false][skipped=false][group separator=\,][decimal
separator=.][positive prefix=][negative prefix=\Q-\E][positive
suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]
with content of a String variable.
You do not read the each line with following
if (readfile.equals(sokeord)) {
You Should have
if (readfile.nextLine().equals(sokeord)) {
Instead of:
readfile.equals(sokeord)
Which is comparing an instance of type Scanner with a String (never going to be true). You need to read a line and compare that.
String line = readfile.nextLine();
if(line.equals(sokeord)){
Add a main method to your class:
public static void main(String[] args)
{
hentAntall();
}
You will have to make hentAntall() static or create an instance of lolz class and call it that way.
Also change:
while (readfile.hasNext()){
if (readfile.nextLine().contains(sokeord)) {
You need to actually read the input and then check if sokeord exists in the line or not.
Your hentAntall method should be like this:
public int hentAntall() throws Exception {
File file = new File("Hvorfor.txt");
Scanner readfile = new Scanner(file);
while (readfile.hasNextLine()) {
String word = readfile.next();
if (word.contains(sokeord)) {
antall++;
System.out.println("Antallet av:" + sokeord + "er " + antall);
} else {
System.out
.println("Error no such search word in the given text: ");
}
}
readfile.close();
return antall;
}
Don't forget to close the Scanner resource to avoid leaks.
I'm trying to append any lines in a text file which contain a given set of strings. I created a test file, in which I put one of those strings. My code is supposed to print any line in the text file containing one of these strings on the same line as the previous line in the text file. Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class AppendIfFromFileScanner {
public static void main(String args[]) {
File file = new File("C:\\Users\\frencke\\workspace\\Testing Stuff\\Append Tetsing\\file3.txt");
ArrayList<String> lines = new ArrayList<String>();
String delima = "\\s+\\s+\\s+\\s+\\s+&\\s+";
String delimb = "\\s+\\s+\\s+\\s+\\s+\\+\\s+";
String delimc = "\\s+\\s+\\s+\\s+\\s+z\\s+";
String delimd = "\\s+\\s+\\s+\\s+\\s+1\\s+";
String delime = "\\s+\\s+\\s+\\s+\\s+2\\s+";
String delimf = "\\s+\\s+\\s+\\s+\\s+3\\s+";
String delimg = "\\s+\\s+\\s+\\s+\\s+4\\s+";
String delimh = "\\s+\\s+\\s+\\s+\\s+5\\s+";
String delimi = "\\s+\\s+\\s+\\s+\\s+6\\s+";
String delimj = "\\s+\\s+\\s+\\s+\\s+7\\s+";
String delimk = "\\s+\\s+\\s+\\s+\\s+8\\s+";
String deliml = "\\s+\\s+\\s+\\s+\\s+9\\s+";
String delimm = "\\s+\\s+\\s+\\s+\\s+a\\s+";
String delimn = "\\s+\\s+\\s+\\s+\\s+b\\s+";
String delimo = "\\s+\\s+\\s+\\s+\\s+c\\s+";
String delimp = "\\s+\\s+\\s+\\s+\\s+d\\s+";
String delimq = "\\s+\\s+\\s+\\s+\\s+e\\s+";
String delimr = "\\s+\\s+\\s+\\s+\\s+f\\s+";
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
lines.add(scanner.nextLine());}
for(int i=0; i<lines.size(); i++){
for(String s=null; i<lines.size(); i++){
s = lines.get(i);
if(!s.contains(delima)||
!s.contains(delimb)||
!s.contains(delimc)||
!s.contains(delimd)||
!s.contains(delime)||
!s.contains(delimf)||
!s.contains(delimg)||
!s.contains(delimh)||
!s.contains(delimi)||
!s.contains(delimj)||
!s.contains(delimk)||
!s.contains(deliml)||
!s.contains(delimm)||
!s.contains(delimn)||
!s.contains(delimo)||
!s.contains(delimp)||
!s.contains(delimq)||
!s.contains(delimr))
System.out.print("\r\n" + s);
else if(s.contains(delima)||
s.contains(delimb)||
s.contains(delimc)||
s.contains(delimd)||
s.contains(delime)||
s.contains(delimf)||
s.contains(delimg)||
s.contains(delimh)||
s.contains(delimi)||
s.contains(delimj)||
s.contains(delimk)||
s.contains(deliml)||
s.contains(delimm)||
s.contains(delimn)||
s.contains(delimo)||
s.contains(delimp)||
s.contains(delimq)||
s.contains(delimr))
System.out.print(s);}
}
}catch (FileNotFoundException e) {
System.out.println("Cannot find file.");
}
}
}
The contents of my text file are:
first line
text & append this line
So basically, I know that my text file has one of these strings (in this case, delima) in it. Yet, my output is:
first line
text & append this line
Which is not supposed to happen. The output I want is:
first line text & append this line
Does anyone know why it's interpreting the second line of my text file as though it does not contain delima, even though it clearly does? Any help would be appreciated. I'm fairly sure that the problem is something to do with my if statement, but I'm obviously not the expert here.
The String.contains() method matches an exact string, not a regular expression.
Instead, you may wish to try using String.matches(). You may need to adjust your pattern to obtain similar behaviour to contains() (see this page for some examples).