Java: Counter Indentation - java

I am very new to java and trying to create a java app which (when ran inside a terminal) will copy what text is inside and if there is a curly { bracket then add 3 spaces, when there is a curly } bracket then remove 3 spaces. There should be a counter to indent another 3 spaces each time a { appears (see example)
Example:
File1.txt:
Hello{StackOverflow}{Users}
The output should be File2.txt:
Hello
{
StackOverflow
}
{
Users
}
What I currently get outputed to File2.txt is:
Hello
{
StackOverflow
}
{
Users
I am missing my last bracket (how do I fix this?) and don't know how to loop my indentation based on the counter. Please help
My current code:
import java.io;
import java.util.Scanner;
public class myapp {
public static void main(String[] argv) throws IOException {
File InputFile = new File(argv[0]);
Scanner FileScanner = new Scanner(InputFile);
FileWriter Writer = new FileWriter(argv[1]);
BufferedWriter OutputWriter = new BufferedWriter(Writer);
while (FileScanner.hasNextLine() == true) {
String a = FileScanner.nextLine();
try {
int indent = 0;
{
if (a.contains("{")) {
indent++;
}
for (int i = 0; i < indent; i++) {
OutputWriter.write(" ");
}
OutputWriter.write(a);
}
if (a.contains("}")) {
indent--;
}
} catch (Exception e) {
System.out.println("Error:" + e.getMessage());
}
OutputWriter.write("}");
}
}
}
p.s in Terminal (to run/test) I use the following command:
$java myapp File1.txt File2.txt
Thank you :)

Try closing OutputWriter at the end of the method via OutputWriter.close(). It will flush the stream which is likely the cause of the missing }.
As far as your indentation issue, declare and initialize the indent counter outside the loop. Otherwise, it will get reset to 0 with each iteration.

Try this one:
public static void main(String[] args) throws IOException {
File InputFile = new File(argv[0]);
Scanner FileScanner = new Scanner(InputFile);
FileWriter Writer = new FileWriter(argv[1]);
BufferedWriter OutputWriter = new BufferedWriter(Writer);
while (FileScanner.hasNextLine() == true) {
String a = FileScanner.nextLine();
String b = "";
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == '{') {
b += "\n{\n ";
} else if (a.charAt(i) == '}') {
b += "\n}\n";
} else {
b += a.charAt(i);
}
}
OutputWriter.write(b);
OutputWriter.close();
}}}

Try this it's ok I add the finally block.`
finally{
OutputWriter.close();
}

Related

Adding a substring to omit a part of the output

Below is my code...
The code below is taking a .txt file of some radiation read outs. My job is to find the max number of counts per minute in the file within 5 counts.
I'e got it working, but I need to omit the part of the line, so I thought I could make this piece of the code:
/* String temp = new String(data)
* temp=list.get(i);
* System.outprintln(temp.substring(0,16) +" ");
*/
and integrate it in. I keep trying several cases, and am not thinking. Any advice?
`import java.util.*;
//Import utility pack, *look at all classes in package.
import java.io.*;
//Good within directory.
public class counterRadiation {
private static String infile = "4_22_18.txt";
//Input
private static String outfile = "4_22_18_stripped.txt";
private static Scanner reader;
//Output
public static void main(String[] args) throws Exception{
//throw exception and then using a try block
try {
//Use scanner to obtain our string and input.
Scanner play = new Scanner(new File(infile));
/* String temp = new String(data)
* temp=list.get(i);
* System.outprintln(temp.substring(0,16) +" ");
*/
Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outfile), "utf-8"));
String lineSeparator = System.getProperty("line.separator");
play.useDelimiter(lineSeparator);
while (play.hasNext()) {
String line = play.next();
if (line.matches(dataList)) {
writer.write(line + "\r\n");
}
}
writer.close();
play.close();
try {
reader = new Scanner(new File(infile));
ArrayList<String> list = new ArrayList<String>();
while (reader.hasNextLine()) {
list.add(reader.nextLine());
}
int[] radiCount = new int[list.size()];
for (int i = 0; i < list.size();i++) {
String[] temp = list.get(i).split(",");
radiCount[i] = (Integer.parseInt(temp[2]));
}
int maxCount = 0;
for (int i = 0; i < radiCount.length; i++) {
if (radiCount[i] > maxCount) {
maxCount = radiCount[i];
}
}
for (int i = 0;i < list.size() ;i++) {
if(radiCount[i] >= maxCount - 4) {
System.out.println(list.get(i)+" "+ radiCount[i]);
}
}
}catch(FileNotFoundException e){
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}`
Although it is not quite clear what you want to get rid of you could use .indexOf(String str) to define the first occurrence of the sub-string you want to exclude. For example in your code:
String data = "useful bit get rid of this";
int index = data.indexOf("get rid of this");
System.out.println(data.substring(0,index) + "are cool");
//Expected result:
//"useful bits are cool"
from Java doc

Java get all class and id names from css file

I am trying to get all the classes and ids from a css file in arrays. the arrays should look like this:
UsedIds: {"#id1, "#id2" etc.etc.etc.}
UsedClasses: {".class1", ".class2" etc.etc.etc.}
how do i get these results without getting the stuff with "." inside the curly braces? I tried to remove every "{code inside}" segment but there are mediaqueries and stuff conflicting with it. My first attempt is below here, but i am not proud of it... It only removes the curly codes, but i'm stuck with this right now. Do you guys know a easier solution?
private void getCssClasses(String fileName) {
File cssFile = new File(fileName);
Scanner sc;
try {
sc = new Scanner(cssFile);
while (sc.hasNextLine()) {
String cssLine = sc.nextLine();
int firstCurly = 0;
int lastCurly = 0;
while (cssLine.contains("{")) {
for (int i = 0; i < cssLine.length(); i++) {
String character = "" + cssLine.charAt(i);
//System.out.println(character);
if (character.contains("{")) {
//System.out.println("IN");
firstCurly = i;
}
if (character.contains("}")) {
if(firstCurly != 0){
System.out.println("OUT");
lastCurly = i;
}
}
if (firstCurly != 0 && lastCurly != 0) {
StringBuilder sb = new StringBuilder(cssLine);
sb.delete(firstCurly, lastCurly);
cssLine = sb.toString();
System.out.println("YES");
break;
}
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

Saving an ArrayList to .txt file

So, I was wondering if it's possible to save values from an ArrayList to a file, such as "inputs.txt". I've seen a question similar to this: save changes (permanently) in an arraylist?, however that didn't work for me, so I'm wondering if I'm doing something wrong. Here are my files:
Main.class
package noodlegaming.geniusbot.main;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import java.util.logging.Logger;
public class Main {
public static Random rand = new Random();
public static void readFileByLine(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
SentencesToUse.appendToInputtedSentences(scanner.next().toString());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
static File inputsFile = new File("inputs.txt");
static PrintWriter printWriter = new PrintWriter(inputsFile);
public static void main(String[] args) throws IOException, InterruptedException {
if(!inputsFile.exists()) {
inputsFile.createNewFile();
}
readFileByLine("inputs.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Hello, welcome to GeniusBot. Shortly, you will be speaking with a computer that learns from what you say.");
System.out.println("Because of this circumstance, we ask that you do not type any curses, swear words, or anything otherwise considered inappropriate,");
System.out.println("as it may come back to the light at a time you don't want it to.");
System.out.println("Please note that your responses won't be saved if you close the program.");
System.out.println("If you type printInputsSoFar, a list of all the stuff you've typed will be printed.");
System.out.println("If you type printInputsLeft, the number of inputs you have left will be printed.");
System.out.println("If you type clearInputs, the program will be closed and the inputs.txt file deleted, " +
"\nand recreated upon startup.");
System.out.println("Starting up GeniusBot.");
Thread.sleep(3000);
System.out.println("Hello! I am GeniusBot!");
br.readLine();
System.out.println("" + SentencesToUse.getBeginningSentence() + "");
for (int i = 0; i < 25; i++) {
String response = br.readLine();
if (response.equals("printInputsSoFar")) {
for (int j = 1; j < SentencesToUse.inputtedSentences.size(); j++) {
System.out.println(SentencesToUse.inputtedSentences.get(j));
}
i--;
} else if (response.equals("printInputsLeft")) {
int inputsLeft = 25 - i;
System.out.println("You have " + inputsLeft + " inputs left.");
i--;
} else if (response.equals("clearInputs")) {
printWriter.close();
inputsFile.delete();
Thread.currentThread().stop();
} else {
SentencesToUse.appendToInputtedSentences(response);
printWriter.println(response);
printWriter.flush();
int inputtedSentence = Main.rand.nextInt(SentencesToUse.inputtedSentences.size());
String inputtedSentenceToUse = SentencesToUse.inputtedSentences.get(inputtedSentence);
System.out.println(inputtedSentenceToUse);
}
if (i == 24) {
System.out.println("Well, it was nice meeting you, but I have to go. \nBye.");
Thread.currentThread().stop();
printWriter.close();
}
}
}
}
SentencesToUse.class:
package noodlegaming.geniusbot.main;
java.util.ArrayList;
import java.util.List;
public class SentencesToUse {
public static String[] beginningSentences = {"What a lovely day!", "How are you?", "What's your name?"};
static int beginningSentence = Main.rand.nextInt(beginningSentences.length);
static String beginningSentenceToUse = beginningSentences[beginningSentence];
public static String getBeginningSentence() {
return beginningSentenceToUse;
}
public static List<String> inputtedSentences = new ArrayList<String>();
public static void appendToInputtedSentences(String string) {
inputtedSentences.add(string);
}
public static void clearInputtedSentences() {
inputtedSentences.clear();
}
}
As stated in the comments, use a PrintWriter to write the values to a file instead:
PrintWriter pw = new PrintWriter(fos);
for (int i = 0; i < SentencesToUse.inputtedSentences.size(); i++) {
pw.write(SentencesToUse.inputtedSentences.get(i)+"\n"); // note the newline here
}
pw.flush(); // make sure everything in the buffer actually gets written.
And then, to read them back again:
try {
Scanner sc = new Scanner(f);
while (sc.hasNext()) {
SentencesToUse.inputtedSentences.ass(sc.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
The pw.flush(); is incredibly important. When I was first learning java, I can't tell you how many hours I spent debugging because I didn't flush my streams. Note also the "\n". This ensures that there will be a newline, and that your sentences don't just run together in one giant blob. If each one already has a newline, then that's not necessary. Unlike print vs println, there is no writeln. You must manually specify the newline character.

Java - store elements of ArrayList into separate blocks

so here is ALL of my code, which, in summary, standardises two text files then prints out the result.
import java.io.*;
import java.util.*;
public class Plagiarism {
public static void main(String[] args) {
Plagiarism myPlag = new Plagiarism();
if (args.length == 0) {
System.out.println("Error: No files input");
}
else if (args.length > 0) {
try {
for (int i = 0; i < args.length; i++) {
BufferedReader reader = new BufferedReader (new FileReader (args[i]));
List<String> foo = simplify(reader);
for (int j = 0; j < foo.size(); j++) {
System.out.print(foo.get(j));
}
}
}
catch (Exception e) {
System.err.println ("Error reading from file");
}
}
}
public static List<String> simplify(BufferedReader input) throws IOException {
String line = null;
List<String> myList = new ArrayList<String>();
while ((line = input.readLine()) != null) {
myList.add(line.replaceAll("[^a-zA-Z0-9]","").toLowerCase().trim());
}
return myList;
}
}
The next bit I want to implement is this: Using the command line, the 3rd argument will be any integer(size of blocks) which the user enters. I have to use this then to store the elements of that array into separate blocks which overlap. EG: The cat sat on the mat, block size 4. Block 1 would be: Thec Block 2: heca Block 3: ecat, and so on, until it reaches the end of the array.
Any ideas?
Thanks in advance guys.
To get the block size use this :
if(args.length != 4)
return;
int blockSize = Integer.valueOf(args[3]);
This an example that could help you
import java.util.*;
public class Test {
public static void main(String[] args) {
String line = "The dog is in the house";
line = line.replace(" ", "");
List<String> list = new ArrayList<String>();
for (int i = 0; i <= line.length() - 4; i++)
list.add(line.substring(i, i + 4));
System.out.println(list);
}
output :
[Thed, hedo, edog, dogi, ogis, gisi, isin, sint, inth, nthe, theh, heho, ehou, hous, ouse]
Is that what you want to do
WE can code it in mulitple ways, here is one example.
Input 3 arguments first 2 are files and 3rd one is the block size:
File1 contain: this is a boy
File2 contain: this is a girl
block size: 4
Expected Output:
this hisi isis sisa isab sabo aboy boyt oyth ythi this hisi isis sisa isag sagi agir girl
Program:
import java.io.;
import java.util.;
public class Plagiarism {
public static void main(String[] args) {
//Plagiarism myPlag = new Plagiarism();
/*args = new String[3];
Scanner s = new Scanner(System.in);
System.out.println("Enter the 1st file path");
args[0] = s.next();
System.out.println("Enter the 2nd file path");
args[1] = s.next();
System.out.println("Enter size of block");
args[2] = s.next();*/
int blockSize = Integer.valueOf(args[2]);
StringBuilder wholeContent = new StringBuilder("");
if (args.length == 0) {
System.out.println("Error: No files input");
}
else if (args.length > 0) {
try {
for (int i = 0; i < args.length-1; i++) {
BufferedReader reader = new BufferedReader (new FileReader (args[i]));
List<String> foo = simplify(reader);
for (int j = 0; j < foo.size(); j++) {
//System.out.print(foo.get(j));
wholeContent.append(foo.get(j));
}
}
System.out.println("The content of Line is = "+ wholeContent);
System.out.println("The content of line based on the block size = "+ blockSize + " is:");
for(int j=0; j<=(wholeContent.length()-blockSize); j++){
System.out.print(wholeContent.substring(j, j+4));
System.out.print(" ");
}
}
catch (Exception e) {
e.printStackTrace();
System.err.println ("Error reading from file");
}
}
}
public static List<String> simplify(BufferedReader input) throws IOException {
String line = null;
List<String> myList = new ArrayList<String>();
while ((line = input.readLine()) != null) {
if(!" ".equals(line))
myList.add(line.replaceAll("[^a-zA-Z0-9]","").toLowerCase().trim());
}
return myList;
}
}
All you are asking to do can be done with string manipulation. First use replaceAll() to remove your spaces, then use a for loop and substring() to create your blocks.
for your for loop you need to modify it so that it reads the two texts, then uses the 3rd argument as the block size so you would change your for loop from:
for(int i = 0; i<args.length;i++)
to:
for(int i = 1; i<3; i++)
this reads the first two arguments but not the third

Method to find string inside of the text file. Then getting the following lines up to a certain limit

So this is what I have so far :
public String[] findStudentInfo(String studentNumber) {
Student student = new Student();
Scanner scanner = new Scanner("Student.txt");
// Find the line that contains student Id
// If not found keep on going through the file
// If it finds it stop
// Call parseStudentInfoFromLine get the number of courses
// Create an array (lines) of size of the number of courses plus one
// assign the line that the student Id was found to the first index value of the array
//assign each next line to the following index of the array up to the amount of classes - 1
// return string array
}
I know how to find if a file contains the string I am trying to find but I don't know how to retrieve the whole line that its in.
This is my first time posting so If I have done anything wrong please let me know.
You can do something like this:
File file = new File("Student.txt");
try {
Scanner scanner = new Scanner(file);
//now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if(<some condition is met for the line>) {
System.out.println("ho hum, i found it on line " +lineNum);
}
}
} catch(FileNotFoundException e) {
//handle this
}
Using the Apache Commons IO API https://commons.apache.org/proper/commons-io/ I was able to establish this using FileUtils.readFileToString(file).contains(stringToFind)
The documentation for this function is at https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#readFileToString(java.io.File)
Here is a java 8 method to find a string in a text file:
for (String toFindUrl : urlsToTest) {
streamService(toFindUrl);
}
private void streamService(String item) {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.filter(lines -> lines.contains(item))
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
When you are reading the file, have you considered reading it line by line? This would allow you to check if your line contains the file as your are reading, and you could then perform whatever logic you needed based on that?
Scanner scanner = new Scanner("Student.txt");
String currentLine;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Perform logic
}
}
You could use a variable to hold the line number, or you could also have a boolean indicating if you have passed the line that contains your string:
Scanner scanner = new Scanner("Student.txt");
String currentLine;
int lineNumber = 0;
Boolean passedLine = false;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Do task
passedLine = true;
}
if(passedLine)
{
//Do other task after passing the line.
}
lineNumber++;
}
This will find "Mark Sagal" in Student.txt. Assuming Student.txt contains
Student.txt
Amir Amiri
Mark Sagal
Juan Delacruz
Main.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
final String file = "Student.txt";
String line = null;
ArrayList<String> fileContents = new ArrayList<>();
try {
FileReader fReader = new FileReader(file);
BufferedReader fileBuff = new BufferedReader(fReader);
while ((line = fileBuff.readLine()) != null) {
fileContents.add(line);
}
fileBuff.close();
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println(fileContents.contains("Mark Sagal"));
}
}
I am doing something similar but in C++. What you need to do is read the lines in one at a time and parse them (go over the words one by one). I have an outter loop that goes over all the lines and inside that is another loop that goes over all the words. Once the word you need is found, just exit the loop and return a counter or whatever you want.
This is my code. It basically parses out all the words and adds them to the "index". The line that word was in is then added to a vector and used to reference the line (contains the name of the file, the entire line and the line number) from the indexed words.
ifstream txtFile;
txtFile.open(path, ifstream::in);
char line[200];
//if path is valid AND is not already in the list then add it
if(txtFile.is_open() && (find(textFilePaths.begin(), textFilePaths.end(), path) == textFilePaths.end())) //the path is valid
{
//Add the path to the list of file paths
textFilePaths.push_back(path);
int lineNumber = 1;
while(!txtFile.eof())
{
txtFile.getline(line, 200);
Line * ln = new Line(line, path, lineNumber);
lineNumber++;
myList.push_back(ln);
vector<string> words = lineParser(ln);
for(unsigned int i = 0; i < words.size(); i++)
{
index->addWord(words[i], ln);
}
}
result = true;
}
Here is the code of TextScanner
public class TextScanner {
private static void readFile(String fileName) {
try {
File file = new File("/opt/pol/data22/ds_data118/0001/0025090290/2014/12/12/0029057983.ds");
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("usage: java TextScanner1"
+ "file location");
System.exit(0);
}
readFile(args[0]);
}
}
It will print text with delimeters

Categories