I am trying to create a program which will read a file and check whether the text is a palindrome or not. The code compiles, but doesnt really work.
The problem is I dont know how to break a complete token into characters or assign it to a string in order to use string's length to push(enqueue) each letter or digit into the stack(queue). Can anyone suggest a solution for this?
public static void main(String [] args) throws IOException{
StackReferenceBased stack = new StackReferenceBased();
QueueReferenceBased queue = new QueueReferenceBased();
Scanner s = null;
String fileName=args[0]+".txt";
int symbols = 0;
int lettersAndDigits =0;
int matches = 0;
try{
s = new Scanner(new File(fileName));
while(s.hasNext()){
String current = s.next();
for(int i=0;i<current.length();i++){
char temp = s.next().charAt(i);
if(Character.isLetterOrDigit(temp)){
stack.push(temp);
queue.enqueue(temp);
lettersAndDigits++;
}
else {
symbols++;
}
}
}
System.out.println("There are: " + " "+ symbols + " " +"symbols and " + " "+lettersAndDigits + " "+ "digits/letters");
}
catch (FileNotFoundException e) {
System.out.println("Could not open the file:" + args[0]);
} //catch (Exception e) {
//System.out.println("ERROR copying file");
finally {
if(s != null){
s.close();
}
}
while (!stack.isEmpty()){
if(!stack.pop().equals(queue.dequeue())){
System.out.println("not pali");
break;
}
else {
++matches;
}
}
if(matches==lettersAndDigits){
System.out.print("pali");
}
}
Instead of
char temp = s.next().charAt(i);
you need
char temp = current.charAt(i);
By calling s.next() you read the next token from the file and try to access the ith element of that token based on the first string's (current) length, which will lead to exceptions if the tokens read are shorter than the first stoken
Related
public static void componiPoesia(String outputFile, String[] frasi) {
try (PrintWriter pw = new PrintWriter(
new FileOutputStream(new File(outputFile), true))) {
int count = 0;
for (String frase : frasi) {
pw.print(frase + ". ");
count++;
pw.print("\n" + count);
}
pw.close();
} catch (IOException e) {
System.out.println("Error writing into the outputFile: " + outputFile);
e.printStackTrace();
}
}
*This is what should come out
ChiHaRobaInMareNonHaNulla. TuttiIPiuGrandiPensieriSonoConcepitiMentreSiCammina.
2, 1
This is what comes out of me
ChiHaRobaInMareNonHaNulla.
1TuttiIPiuGrandiPensieriSonoConcepitiMentreSiCammina.
2
try this one, As your code pw.print("\n" + count); brek your line so i make it outside loop and done some changes in your code for expecting output.
try (PrintWriter pw = new PrintWriter( new FileOutputStream(new File(outputFile), true))) {
int count = 0;
String temp="";
for (String frase : frasi) {
pw.print(frase + ". ");
if(count==0)
temp=(frasi.length-count)+"";
else
temp=temp+","+(frasi.length-count);
count++;
}
pw.print("\n" + temp);
pw.close();
} catch (IOException e) {
//System.out.println("Error writing into the outputFile: " + outputFile);
e.printStackTrace();
}
According to the expected output, I suppose, that you have to print the phrases to the file (from the String[] frasi array) in the for each loop and count the number of phrases. You don't have to print counter in for-each loop. After the loop you can do something like:
while(counter > 0)
{
pw.print(counter);
counter--;
if(counter > 0)
pw.print(", ");
}
I'm supposed to create a program that counts the number of words and the average number of characters(without spaces) from a text file. I've created the program I'm just having one problem. My total number of characters counters counts the characters "-" and "." when counting words, I don't want this to happen. Currently I'm getting 300 characters counted. There are four "." and one "-" that should be removed from the counter so I can get the total value of 295. I tried using char but I get stuck with errors that don't allow me to compare string to char. My friend recommended I compare I should try to incorporate a way to compare char to Unicode but I don't know how to begin to code that.
public class Count {
public static void main(String[] args) {
File sFile = new File("s.txt");
FileReader in;
BufferedReader readFile;
String sourceCode;
int amountOfWords = 0;
int amountOfChars = 0;
try {
in = new FileReader(sFile);
readFile = new BufferedReader(in);
while ((sourceCode = readFile.readLine()) != null) {
String[] words = sourceCode.split(" ");
amountOfWords = amountOfWords + words.length;
for (String word : words) {
amountOfChars = amountOfChars + word.length();
}
}
System.out.println("Amount of Chars is " + amountOfChars);
System.out.println("Amount of Words is " + (amountOfWords + 1));
System.out.println("Average Word Length is "+ (amountOfChars/amountOfWords));
readFile.close();
in.close();
} catch (FileNotFoundException e) {
System.out.println("File does not exist or could not be found.");
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.out.println("Problem reading file.");
System.err.println("IOException: " + e.getMessage());
}
}
}
Before doing
String[] words = sourceCode.split(" ");
get rid of all the chars you do not want using replace
e.g.
sourceCode = sourceCode.replace ("-", "").replace (".", "");
String[] words = sourceCode.split(" ");
Or you could use all 3 characters "","." and ";" in the spilt I guess.
Here is the answer to your question...
public static int numberOfWords(File someFile) {
int num=0;
try {
String line=null;
FileReader filereader=new FileReader(someFile);
try (BufferedReader bf = new BufferedReader(filereader)) {
while((line=bf.readLine()) !=null) {
if (!line.equals("\n")) {
if (line.contains(" ") {
String[] l=line.split(" ");
num=num+l.length;
} else {
num++;
}
}
}
}
} catch (IOException e) {}
return num;
}
public static int numberOfChars(File someFile) {
int num=0;
try {
String line=null;
FileReader filereader=new FileReader(someFile);
try (BufferedReader bf = new BufferedReader(filereader)) {
while((line=bf.readLine()) !=null) {
if (!line.equals("\n")) {
if (line.contains(" ") {
String[] l=line.split(" ");
for (String s : l) {
s=replaceAllString(s, "-", "");
s=replaceAllString(s, ".", "");
String[] sp=s.split("");
num=num+sp.length;
}
} else {
line=replaceAllString(line, "-", "");
line=replaceAllString(line, ".", "");
String[] sp=line.split("");
num=num+sp.length;
}
}
}
}
} catch (IOException e) {}
return num;
}
public static String replaceAllString(String s, String c, String d){
String temp = s.replace(c ,d);
return temp;
}
I am trying to read data from a text file and then store it to an array. I assume that there is one word per line. I am getting a NoSuchElementException here:
while (s.hasNextLine())
{
text = text + s.next() + " ";
}
This is my code:
public class ReadNote
{
public static void main(String[]args)
{
String text = readString("CountryList.txt");
System.out.println(text);
String[] words = readArray("CountryList.txt");
for (int i = 0; i < words.length; i++)
{
System.out.println(words[i]);
}
}
public static String readString(String file)
{
String text = "";
try{
Scanner s = new Scanner(new File(file));
while (s.hasNextLine())
{
text = text + s.next() + " ";
}
} catch(FileNotFoundException e)
{
System.out.println("file not found ");
}
return text;
}
public static String[] readArray(String file)
{
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine())
{
ctr = ctr+1;
s1.next();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for ( int i = 0; i < ctr; i++)
{
words [i] = s2.next();
}
return words;
} catch (FileNotFoundException e) { }
return null;
}
}
Here is the message.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at ReadNote.readString(ReadNote.java:29)
at ReadNote.main(ReadNote.java:13)
For the specific exception you are getting in readString:
while (s.hasNextLine()) {
text = text + s.next() + " ";
}
You need to either call s.hasNext() in the loop guard, or use s.nextLine() in the body.
As described in this answer.
You have a single extra newline at the end of your file.
hasNextLine() checks to see if there is another linePattern in the buffer.
hasNext() checks to see if there is a parseable token in the buffer, as separated by the scanner's delimiter.
You should modify your code to one of the following
while (s.hasNext()) {
text = text + s.next() + " ";
}
while (s.hasNextLine()) {
text = text + s.nextLine() + " ";
}
There are 2 issues with your code as far as I can tell:
You forgot to check hasNextLine() for your second Scanner s2.
When using Scanner you need to check if there is a next line with hasNextLine(), and it will return null at EOF.
You probably want s.nextLine() instead of s.next() in your while loop since you are checking while (s1.hasNextLine()). In general, you have to match your .hasNext... to your .next....
I am have a project that need to modify some text in the text file.
Like BB,BO,BR,BZ,CL,VE-BR
I need make it become BB,BO,BZ,CL,VE.
and HU, LT, LV, UA, PT-PT/AR become HU, LT, LV, UA,/AR.
I have tried to type some code, however the code fail to loop and also,in this case.
IN/CI, GH, KE, NA, NG, SH, ZW /EE, HU, LT, LV, UA,/AR, BB
"AR, BB,BO,BR,BZ,CL, CO, CR, CW, DM, DO,VE-AR-BR-MX"
I want to delete the AR in second row, but it just delete the AR in first row.
I got no idea and seeking for helps.
Please
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.util.Scanner;
public class tomy {
static StringBuffer stringBufferOfData = new StringBuffer();
static StringBuffer stringBufferOfData1 = stringBufferOfData;
static String filename = null;
static String input = null;
static String s = "-";
static Scanner sc = new Scanner(s);
public static void main(String[] args) {
boolean fileRead = readFile();
if (fileRead) {
replacement();
writeToFile();
}
System.exit(0);
}
private static boolean readFile() {
System.out.println("Please enter your files name and path i.e C:\\test.txt: ");
filename = "C:\\test.txt";
Scanner fileToRead = null;
try {
fileToRead = new Scanner(new File(filename));
for (String line; fileToRead.hasNextLine()
&& (line = fileToRead.nextLine()) != null;) {
System.out.println(line);
stringBufferOfData.append(line).append("\r\n");
}
fileToRead.close();
return true;
} catch (FileNotFoundException ex) {
System.out.println("The file " + filename + " could not be found! "+ ex.getMessage());
return false;
} finally {
fileToRead.close();
return true;
}
}
private static void writeToFile() {
try {
BufferedWriter bufwriter = new BufferedWriter(new FileWriter(
filename));
bufwriter.write(stringBufferOfData.toString());
bufwriter.close();
} catch (Exception e) {// if an exception occurs
System.out.println("Error occured while attempting to write to file: "+ e.getMessage());
}
}
private static void replacement() {
System.out.println("Please enter the contents of a line you would like to edit: ");
String lineToEdit = sc.nextLine();
int startIndex = stringBufferOfData.indexOf(lineToEdit);
int endIndex = startIndex + lineToEdit.length() + 2;
String getdata = stringBufferOfData.substring(startIndex + 1, endIndex);
String data = " ";
Scanner sc1 = new Scanner(getdata);
Scanner sc2 = new Scanner(data);
String lineToEdit1 = sc1.nextLine();
String replacementText1 = sc2.nextLine();
int startIndex1 = stringBufferOfData.indexOf(lineToEdit1);
int endIndex1 = startIndex1 + lineToEdit1.length() + 3;
boolean test = lineToEdit.contains(getdata);
boolean testh = lineToEdit.contains("-");
System.out.println(startIndex);
if (testh = true) {
stringBufferOfData.replace(startIndex, endIndex, replacementText1);
stringBufferOfData.replace(startIndex1, endIndex1 - 2,
replacementText1);
System.out.println("Here is the new edited text:\n"
+ stringBufferOfData);
} else {
System.out.println("nth" + stringBufferOfData);
System.out.println(getdata);
}
}
}
I wrote a quick method for you that I think does what you want, i.e. remove all occurrences of a token in a line, where that token is embedded in the line and is identified by a leading dash.
The method reads the file and writes it straight out to a file after editing for the token. This would allow you to process a huge file without worrying about about memory constraints.
You can simply rename the output file after a successful edit. I'll leave it up to you to work that out.
If you feel you really must use string buffers to do in memory management, then grab the logic for the line editing from my method and modify it to work with string buffers.
static void onePassReadEditWrite(final String inputFilePath, final String outputPath)
{
// the input file
Scanner inputScanner = null;
// output file
FileWriter outputWriter = null;
try
{
// open the input file
inputScanner = new Scanner(new File(inputFilePath));
// open output file
File outputFile = new File(outputPath);
outputFile.createNewFile();
outputWriter = new FileWriter(outputFile);
try
{
for (
String lineToEdit = inputScanner.nextLine();
/*
* NOTE: when this loop attempts to read beyond EOF it will throw the
* java.util.NoSuchElementException exception which is caught in the
* containing try/catch block.
*
* As such there is NO predicate required for this loop.
*/;
lineToEdit = inputScanner.nextLine()
)
// scan all lines from input file
{
System.out.println("START LINE [" + lineToEdit + "]");
// get position of dash in line
int dashInLinePosition = lineToEdit.indexOf('-');
while (dashInLinePosition != -1)
// this line has needs editing
{
// split line on dash
String halfLeft = lineToEdit.substring(0, dashInLinePosition);
String halfRight = lineToEdit.substring(dashInLinePosition + 1);
// get token after dash that is to be removed from whole line
String tokenToRemove = halfRight.substring(0, 2);
// reconstruct line from the 2 halves without the dash
StringBuilder sb = new StringBuilder(halfLeft);
sb.append(halfRight.substring(0));
lineToEdit = sb.toString();
// get position of first token in line
int tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
while (tokenInLinePosition != -1)
// do for all tokens in line
{
// split line around token to be removed
String partLeft = lineToEdit.substring(0, tokenInLinePosition);
String partRight = lineToEdit.substring(tokenInLinePosition + tokenToRemove.length());
if ((!partRight.isEmpty()) && (partRight.charAt(0) == ','))
// remove prefix comma from right part
{
partRight = partRight.substring(1);
}
// reconstruct line from the left and right parts
sb.setLength(0);
sb = new StringBuilder(partLeft);
sb.append(partRight);
lineToEdit = sb.toString();
// find next token to be removed from line
tokenInLinePosition = lineToEdit.indexOf(tokenToRemove);
}
// handle additional dashes in line
dashInLinePosition = lineToEdit.indexOf('-');
}
System.out.println("FINAL LINE [" + lineToEdit + "]");
// write line to output file
outputWriter.write(lineToEdit);
outputWriter.write("\r\n");
}
}
catch (java.util.NoSuchElementException e)
// end of scan
{
}
finally
// housekeeping
{
outputWriter.close();
inputScanner.close();
}
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
inputScanner.close();
e.printStackTrace();
}
}
I have a Method that calls a second method, the second method will:
Create any missing directories
Create a file
Decode a 2D String[] to a String (Not working)
Write content
Write the decoded String to the file with a header (Not working)
First method
public static boolean store(Exception exception, String[][] flags){
return storePrivate(exception, location, flags);
}
Second Method (Not all code just relevant code)
private static boolean storePrivate(Exception exception, String dir, String[][] flags){
String flag = "";
for(int i = 0; i >= flags.length; i++){
flag = flag + "" + flags[i][0] + ": " + flags[i][1] + "\n";
}
try {
File directory = new File(dir);
File file = new File(dir + id + ".txt");
if (!directory.exists()) {
directory.mkdirs();
}
file.createNewFile();
FileWriter filewriter = new FileWriter(file.getAbsoluteFile());
BufferedWriter writer = new BufferedWriter(filewriter);
if(flag != ""){
writer.write("Flags by Developer: ");
writer.write(flag);
}
writer.flush();
writer.close();
return true;
} catch (IOException e) {
return false;
}
}
Call to the first method
public static void main(String[] args) {
try {
test();
} catch (Exception e) {
// TODO Auto-generated catch block
ExceptionAPI.store(e, new String[][]{{"flag1", "Should be part of flag1"}, {"flag2", "this should be flag 2 contence"}});
}
}
public static void test() throws IOException{
throw new IOException();
}
I cant find why this won't work. I think it has to do with the second method, particularly
if(flag != ""){
writer.write("Flags by Developer: ");
writer.write(flag);
}
Thanks if anyone can help me.
Curlip
Try this if you want to just convert an array of strings into a single string:
String[] stringTwoD = //... I think this is a 1D array, and Sting[][] is a 2D, anyway
String stringOneD = "";
for (String s : stringTwoD)
stringOneD += s;//add the string with the format you want
BTW, your loop condition seems wrong and ,so you may change it to :
for(int i = 0; i < flags.length; i++){
flag += flags[i][0] + ": " + flags[i][1] + "\n";
}