Counting { and } braces in program JAVA - java

I have to read an input file that contains codes and produce an output that matches the corresponding braces ({ and })
example of how output will look
import java.util.scanner;
public class Tester {1
public static void main(String[] args) {2
Scanner in = new Scanner (System.in);
int price = in.nextInt;
if (price < 10)
System.out.println("Good price");
System.out.println ("Buy it");
}2
}1
}0
}0
0 will represent extra braces that has no matches.
What is the most efficient way to approach this?
Should I just process line by line with Strings?

You can keep a count. Iterate the characters in every line, increment (or decrement) the count and (output the count) for { and } respectively. Don't forget to close your Scanner with a finally block or a try-with-resources. Assuming your file Tester.java is in the user's home folder you could do something like,
File f = new File(System.getProperty("user.home"), "Tester.java");
try (Scanner scan = new Scanner(f)) {
int count = 0;
while (scan.hasNextLine()) {
String line = scan.nextLine();
for (char ch : line.toCharArray()) {
System.out.print(ch);
if (ch == '{') {
System.out.print(++count);
} else if (ch == '}') {
if (count > 0) {
System.out.print(--count);
} else {
System.out.print(count);
}
}
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}

You can find the extra braces by making use of stack as below:
public static void main(final String[] args) {
Stack<String> stack = new Stack<String>();
File file = new File("InputFile");
int lineCount = 0;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
lineCount++;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '{') {
stack.push("{");
} else if (line.charAt(i) == '}') {
if (!stack.isEmpty()) {
stack.pop();
} else {
System.out.println("Extra brace found at line number : " + lineCount);
}
}
}
}
if (!stack.isEmpty()) {
System.out.println(stack.size() + " braces are opend but not closed ");
}
} catch (Exception e) {
e.printStackTrace();
}
}

Related

Manipulate this code so that it counts the # of digits in a file

I need to manipulate this code so that it will read the # of digits from a file.
I am honestly stumped on this one for some reason. Do i need to tokenize it first?
Thanks!
import java.io.*;
import java.util.*;
public class CountLetters {
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Synopsis: Java CountLetters inputFileName");
System.exit(1);
}
String line = null;
int numCount = 0;
try {
FileReader f = new FileReader(args[0]);
BufferedReader in = new BufferedReader(f);
while ((line = in.readLine()) != null) {
for (int k = 0; k < line.length(); ++k)
if (line.charAt(k) >= 0 && line.charAt(k) <= 9)
++numCount;
}
in.close();
f.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(numCount + " numbers in this file.");
} // main
} // CountNumbers
Use '' to indicate a char constant (you are comparing chars to ints), also I would suggest you use try-with-resources Statement to avoid explicit close calls and please avoid using one line loops without braces (unless you are using lambdas). Like
public static void main(String args[]) {
if (args.length != 1) {
System.err.println("Synopsis: Java CountLetters inputFileName");
System.exit(1);
}
String line = null;
int numCount = 0;
try (BufferedReader in = new BufferedReader(new FileReader(args[0]))) {
while ((line = in.readLine()) != null) {
for (int k = 0; k < line.length(); ++k) {
if ((line.charAt(k) >= '0' && line.charAt(k) <= '9')) {
++numCount;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(numCount + " numbers in this file.");
} // main
Also, you could use a regular expression to remove all non-digits (\\D) and add the length of the resulting String (which is all-digits). Like,
while ((line = in.readLine()) != null) {
numCount += line.replaceAll("\\D", "").length();
}
Use if(Charachter.isDigit(char)) replace char with each char, this will count each number, and I believe arabic numbers as well.

How to count number occurrences of a word in a file using BufferedReader in Java

the task is to find number of occurrences of a particular word in a file
that person wrote herself.
public void reader() {
BufferedReader myR = myReader("enter the name of a file: ");
int count = 0;
String substring = readLine("enter the string to count for entry: ");
try {
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
for(int j=0; j<s.length(); j++){
if(s.contains(substring)){
count++;
}
}
}
myR.close();
} catch (IOException e) {
throw new ErrorException(e);
}
println("number of words is: " + count);
}
private BufferedReader myReader(String prompt) {
BufferedReader rd = null;
while (rd == null) {
try {
String name = readLine(prompt);
rd = new BufferedReader(new FileReader(name));
} catch (FileNotFoundException e) {
println("wrong file entered");
// e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return rd;
}
So the problem is that i can't figure out what to do if in my text file number of word i was checking is 4, but the code prints 671
the problem lies in this loop:
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
for(int j=0; j<s.length(); j++){
if(s.contains(substring)){
count++;
}
}
}
now suppose your bufferedReader reads a line "hie i am user".
the size of this string is 13 so string.length(); would return 13.
that means you would be checking the same line for 13 iterations for your match.
So, suppose if you are looking for a match say "user" then checking for "user" on the same line for 13 times would make your count go up to 13.
you can replace the above code with this code:
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
String[] slist = s.split(" ");
for(int j=0; j<slist.length(); j++){
if(slist[j].contains(substring)){
count++;
}
}
}
ohh!! you should have mentioned that you wanna do it without using an array.
this snippet should help you:
while (true) {
String s = null;
s = myR.readLine();
if (s == null)
break;
for(int j=0; j<s.length(); j++){
if(s.equals(" ")){
String temp = s.substring(j+1, s.length());
String word = temp.substring(0,temp.indexOf(" ")-1);
if(temp.equalsIgnoringCases(word)){
count++;
}
}
}
}
now what i am doing here is first of all i am looking for a space in the whole string and upon finding one, I am extracting a substring starting from the index next to the index of space to the end of the string.
Now from this extracted substring, I am further extracting a substring from index zero up till the first space. this string is essentially a word suitable for comparison.

Making changes to every line in a file - Java

I am working on a program that reads 5 different files containing code that is improperly indented. I have to write a method that properly indents the code and prints it to the console and a new file, given a tab size and the names of the input and output files as parameters. My code so far runs through and indents every line and then tries to determine when to indent another tab or unindent.
public static void justifyJava( String inputFileName, String outputFileName,
int tabSize ) throws FileNotFoundException {
String one_tab = "";
for (int i = 0; i < tabSize; i++) {
one_tab += " ";
}
Scanner input = new Scanner( new File (inputFileName));
PrintStream out = new PrintStream ( new File (outputFileName));
int lineCount = 0;
while ( input.hasNextLine() ) {
String line = input.nextLine();
line = one_tab + line.trim();
lineCount++;
if (lineCount == 1){
line = line.substring(tabSize);
}
else if (lineCount == 2){
Scanner lineScan = new Scanner(line);
while (lineScan.hasNext()) {
String token = lineScan.next();
if (token.length() <= 2) {
line = line.substring(tabSize);
}
}
}
else if (line.contains("{") && lineCount > 2){
System.out.println(line);
out.println(line);
line = one_tab + input.nextLine();
while(!(line.contains("}"))){
line = one_tab + line;
System.out.println(line);
out.println(line);
line = input.nextLine();
}
line = one_tab + line;
}
else if (line.contains("}") && input.hasNextLine()){
line = one_tab + line;
}
else if (!(input.hasNextLine())) {
line = line.substring(tabSize);
}
System.out.println(line);
out.println(line);
}
}
This way is becoming very tedious because of how many situations i have to account for especially since the code in these files use different curly brace styles. Essentially all I'm trying to do is indent every line that follows an opening curly brace by one tab and unindent every line that follows a closing curly brace by one tab. Is there an easier way to do this?
Determining "how many times" you have to indent a line is the same as knowing how many blocks of code opened before this line. To this end, you detect a new block of code if:
The string contains an opening bracket {.
The string contains a control statement, e.g. if.
The second approach is harder, since you have to determine if the string is actually a control statement and not part of a variable name.
Hence, a simple program, that does not cover every possible coding standard, but will work pretty decently works like this:
Search for an opening bracket that does not belong to a comment.
When you find it, recursively call the method passing the new indentation size.
Return after finding the end of the code block.
Here goes a MWE that works for most simple cases. It is able to detect opening and closing brackets outside strings, and does not search inside comment lines.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class JavaIndent {
public static void main(String[] args) {
try {
JavaIndent.justify("path/to/input.java", "path/to/output.java", 4);
} catch (FileNotFoundException ex) {
System.out.println("File not found...");
}
}
public static void justify(String inputFileName, String outputFileName,
int tabSize) throws FileNotFoundException {
String one_tab = "";
for (int i = 0; i < tabSize; i++) {
one_tab += " ";
}
Scanner input = new Scanner(new File(inputFileName));
PrintStream out = new PrintStream(new File(outputFileName));
JavaIndent.justifyRecursion(one_tab, "", input, out);
}
private static String justifyRecursion(String base_tab, String tab, Scanner input, PrintStream out) {
String line;
boolean flag_open, flag_close, flag_comment, flag_empty;
while (input.hasNextLine()) {
line = input.nextLine().trim();
flag_open = JavaIndent.contains(line, "{");
flag_close = JavaIndent.contains(line, "}");
flag_empty = line.length() == 0;
flag_comment = (flag_empty) ? false : line.charAt(0) == '/';
if (flag_comment || flag_empty) {
out.println(tab + line);
} else if (flag_close) {
return line;
} else if (flag_open) {
out.println(tab + line + "ENTERED OPEN");
line = JavaIndent.justifyRecursion(base_tab, tab + base_tab, input, out);
out.println(tab + line);
// Handles statements like } else { and sequences of these.
flag_open = JavaIndent.contains(line, "{");
while (flag_open) {
line = JavaIndent.justifyRecursion(base_tab, tab + base_tab, input, out);
out.println(tab + line);
flag_open = JavaIndent.contains(line, "{");
}
} else {
// Just a regular line, nothing special
out.println(tab + line);
}
}
return "";
}
private static boolean contains(String line, String sequence) {
String current = "";
char ch, last_ch = ' ';
int count_quotation = 0;
ArrayList<String> code_without_strings = new ArrayList<>();
for (int k = 0; k < line.length(); ++k) {
ch = line.charAt(k);
if (ch == '"' && count_quotation == 0 && last_ch != '\'') {
code_without_strings.add(current);
current = "";
++count_quotation;
} else if (ch == '"' && count_quotation == 1) {
if (last_ch != '\\') {
count_quotation = 0;
}
}
if (count_quotation == 0) {
current += ch;
}
last_ch = ch;
}
code_without_strings.add(current);
for (String code : code_without_strings) {
if (code.contains(sequence))
return true;
}
return false;
}
}
However, one still needs to consider statements such as this:
if (condition)
System.out.println("This should be indented, but it won't be...");
and this:
/**
* This is just a comment, but the program will indent from here on {.
*/
Try using JavaIndent to indent JavaIndent.java and verify that at the very end you will get
if (code.contains(sequence))
return true;
instead of
if (code.contains(sequence))
return true;

Guess A word (Java)

Hello I have to create a program that lets the player guess a word. The code I have works fine but I have to write a condition that allows the player 7 tries, if the player does not guess the word on the 7th try he/she losses. I don't know how to write this condition. Here is my code:
package javaapplication5;
import java.io.*;
import java.lang.*;
import java.util.*;
public class NewClass2{
public static int ReadWordsFromFile(String[] words)
{
try
{
FileReader fr = new FileReader("Guess_words.txt");
BufferedReader br = new BufferedReader(fr);
int count = 0;
for (int i = 0; i <87; i++)
{
String s = br.readLine();
if (s == null)
break;
words[count++] = s;
}
fr.close();
return count;
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
return -1;
}
catch (IOException err)
{
System.out.println(err.getStackTrace());
return -1;
}
}
static public String ReadString()
{
try
{
String inpString = "";
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
return reader.readLine();
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
public static void main(String[] args)
{
System.out.println("Welcome to Guess a Word\n");
String[] words = new String[87];
int count = ReadWordsFromFile(words);
if (count < 0)
{
System.out.println("No words found in the file");
return;
}
if (words == null)
return; // Exception message was already shown
int x = (int)(Math.random() * 87);
int guessX = (x % count);
String secretWord = words[guessX];
int numChars = secretWord.length();
System.out.print("Your secret word is: ");
for(int i = 0; i < numChars; i++)
System.out.print("*");
System.out.println();
boolean bGuessedCorrectly = false;
System.out.println("Guess now (To stop the program, enter #) : ");
while (true)
{
String choice = ReadString();
if (choice.startsWith("#"))
break;
if (choice.compareTo(secretWord) == 0)
{
bGuessedCorrectly = true;
break;
}
for (int i = 0; i < numChars; i++)
{
if (i < secretWord.length() &&
i < choice.length())
{
if (secretWord.charAt(i) == choice.charAt(i))
System.out.print(choice.charAt(i));
else
System.out.print("*");
}
else
System.out.print("*");
}
System.out.println();
}
if (bGuessedCorrectly == false)
System.out.println("Unfortunately you did not guess it correctly. The secret word is: " + secretWord);
else
System.out.println("Congrats! You have guessed it correctly");
}
}
Why not simply change your loop from this:
while (true) {
}
To this:
for (int nrOfGuesses = 0; nrOfGuesses < 7; nrOfGuesses++) {
// do stuff
}

Counting the number of errors in a text file

I've written a program that reads in a text file to show football scores, now the text file is arranged so that it has errors included and I'm trying to write a program to count these errors. The text file is arranged like so:
Hull City : Sunderland : 2 : 3
Chelsea : Manchester City :1
Fulham : Leeds United : 1 : 2
Wigan : Tottenham : 1 : x
: :2:0
So the above has missing team names, missing scores and some scores replaced with an X. I can't for the life of me figure out how to introduce a counter to count the number of errors, any idea on a starting point/solution would be much appreciated, thanks!
Here is my full code:
Main:
public class main {
public static void main(String[] args) {
String userInput;
readFile readScores = new readFile();
do
{
userInput = readScores.getUserInput();
if(userInput.equalsIgnoreCase("S"))
readScores.printScores();
readScores.totalGoals();
readScores.errorCount();
} while (!userInput.equalsIgnoreCase("E"));
System.out.println("****************Exiting application****************");
System.exit(0);
}
}
Readfile Class:
public class readFile {
String [] stringArr;
Scanner scan = new Scanner(System.in);
public String getUserInput()
{
String userInput;
System.out.println("Select your option:\nS - Show Scores \nE - Exit");
userInput = scan.nextLine();
return (userInput);
}
public void printScores()
{
String sep = ":";
File inputfile = new File ("P:/SD/Assignment1/results2.txt");
String line = "";
try {
Scanner filescan = new Scanner(inputfile);
while(filescan.hasNext())
{
line = filescan.nextLine();
stringArr = line.split(sep);
if(stringArr.length == 4)
{
System.out.println(stringArr[0]+"\t [" +stringArr[2]+"]\t|" + stringArr[1]+"\t["+ stringArr[3]+" ]\n");
}
else
{
throw new IllegalArgumentException("String " + line + " does not contain " + sep);
}
}
filescan.close();
}
catch (FileNotFoundException e)
{
System.out.println("problem " +e.getMessage());
}
}
public void totalGoals()
{
int[] num = new int[stringArr.length];
int count = 0;
for (int i = 0; i<stringArr.length; i++)
{
System.out.println(stringArr[i]);
num[i] = Integer.parseInt(stringArr[i]);
count = count + num[i];
System.out.println(count);
}
}
public void errorCount()
{
String line;
int errorCount=0;
String[] strArr;
try
{
BufferedReader br = new BufferedReader(new FileReader("P:/SD/Assignment1/results2.txt"));
while(line = br.readLine() != null)
{
strArr = line.split(":");
if(strArr.length==4){
if(strArr[1].trim().isEmpty()) errorCount++;
if(strArr[2].trim().isEmpty()) errorCount++;
if(strArr[3].trim().indexOf("x")>=0) errorCount++;
if(strArr[4].trim().indexOf("x")>=0) errorCount++;
}
}
}
catch(Exception e){
//error handling
}
System.out.println("Error count: "+errorCount);
}
}
UPDATE::
public void errorCount()
{
String line;
int errorCount=0;
String[] strArr;
String[] parts = line.split(":"); <--- ERROR IS HERE
if (parts.length != 4) {
errorCount++;
}
for (String part : parts) {
if (part.trim().isEmpty()) {
errorCount++;
break;
}
}
if (!(isNumeric(parts[2].trim()) && isNumeric(parts[3].trim()))) { //counts one error, otherwise, check each one of them and if both are not numeric, count this as two errors
errorCount++;
// continue with the following line
}
}
I would suggest something like that:
String line;
int errorCount=0;
String[] strArr;
try{
BufferedReader br = new BufferedReader(new FileReader(yourTextFile));
while((line = br.readLine()) != null){
strArr = line.split(":");
if(strArr.length==4){
if(strArr[0].trim().isEmpty()) errorCount++;
if(strArr[1].trim().isEmpty()) errorCount++;
if(strArr[2].trim().indexOf("x")>=0) errorCount++;
if(strArr[3].trim().indexOf("x")>=0) errorCount++;
}
else errorCount++;
}
}
catch(Exception e){
//error handling
}
System.out.println("Error count: "+errorCount);
You could check the lines against a regular expression. Each non matching line contains an error.
A starting point for the regular expression :
/(.+) : (.+) : (\d+) : (\d+)/
The parenthesis allow you to get the team names and the scores.
int errorCounter = 0; //initialize the errorCounter to zero
try{
BufferedReader br = new BufferedReader(new FileReader(yourTextFile));
while((line = br.readLine()) != null){ //read the file line by line
//Check that each line is split into 4 parts (delimited by ':')
String[] parts = line.split(":");
if (parts.length != 4) {
errorCounter++;
continue; //continue with the following line
}
// Then, check if some of the parts are null, like that:
for (String part : parts) {
if (part.trim().isEmpty()) {
errorCounter++;
}
}
//Finally, you can check if the last two parts contain numbers, using [this `isNumeric()` method][2], like that:
if (!(isNumeric(parts[2].trim())) { //checks if the third part is a number
errorCounter++;
}
if (!(isNumeric(parts[3].trim())) { //checks if the last part is numeric
errorCounter++;
}
} catch(IOException ex) {
System.err.println(ex);
}
The isNumeric() method can be found here.
Note that this solution counts multiple errors on the same line. If you want to count one error per line, you could simply use the one-liner that Lorenz Meyer suggests.

Categories