I need to print out each letter from a text file using a list. I'm not sure where it is currently messing up.
Here is the code that I have so far. It currently only prints out the first letter from the file. For instance if the first character was "H" it would just print out the "H" and not continue with the rest of the file. I tested with multiple files to make sure it wasn't just the file I was working with. It takes the phrase from a standard .txt file.
Any help would be greatly appreciated!
package parsephrase;
/**
*
* #author Matt
*/
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Scanner;
public class ParsePhrase {
private final Path filePath;
private ArrayList<String> inputList = new ArrayList<String>();
private ArrayList<Character>outputList = new ArrayList<Character>();
public ParsePhrase(String inputFile) {
filePath = Paths.get(inputFile);
}
public void readLines() {
try (Scanner input = new Scanner(filePath)) {
while (input.hasNextLine()) {
logInputLine(input.nextLine());
}
input.close();
}
catch (IOException e) {
System.out.println("Unable to access file.");
}
}
public void logInputLine(String lineIn) {
Scanner input = new Scanner(lineIn);
inputList.add(input.nextLine());
input.close();
}
public void displayOutput() {
for (int inputListIndex = 0; inputListIndex < inputList.size(); inputListIndex++) {
String inputString = inputList.get(inputListIndex);
for (int inputStringIndex = 0; inputStringIndex < inputString.length(); inputStringIndex++) {
if (outputList.isEmpty()) {
outputList.add(inputString.charAt(inputStringIndex));
continue;
}
for (int outputListIndex = 0; outputListIndex < outputList.size(); outputListIndex++) {
if (Character.isLetter(inputString.charAt(inputStringIndex))) {
if (inputString.charAt(inputStringIndex) <= outputList.get(outputListIndex));
displayCharArray(outputList);
break;
}
else if (inputString.charAt(inputStringIndex) > outputList.get(outputListIndex)) {
if (outputListIndex == outputList.size() - 1) {
outputList.add(inputString.charAt(inputStringIndex));
displayCharArray(outputList);
break;
} else {
continue;
}
}
}
}
}
}
public void displayCharArray(ArrayList<Character> listIn) {
for (Character c : listIn) {
System.out.println(c);
}
System.out.println();
}
public static void main(String[] args)throws IOException {
ParsePhrase parser = new ParsePhrase("C:\\devel\\cis210\\Week 3\\Test.txt");
parser.readLines();
parser.displayOutput();
}
}
Though not tested, yet the issue could be caused by an if condition that is currently resulting being redundant :
if (inputString.charAt(inputStringIndex) <= outputList.get(outputListIndex)); // if terminated by semi colon
displayCharArray(outputList); // display the first character
break; // executed certainly
should ideally be :
if (inputString.charAt(inputStringIndex) <= outputList.get(outputListIndex)) {
displayCharArray(outputList);
break;
}
Related
I am trying to write a program which converts all G1 lines of a G code to lines which say MOVX (x-coordinate of G1 command)
Eg. G1 X0.1851 should become MOVX(0.1851)
At the moment the program is just appending the text file that has been read and printing the new code below the old one in the same text file.
The problem is that when I try to create an array list of the number after the X in the G-Code, I get a problem with the memory in the heap space overflowing.
I have added a clear() statement after each iteration of a line of the G-Code to try to prevent the array list becoming larger and larger but it keeps overflowing.
Here is my code:
package textfiles;
import java.io.IOException;
import java.util.ArrayList;
public class FileData {
public static void main(String[] args) throws IOException {
String file_name = "C:/blabla";
try {
ReadFile file = new ReadFile(file_name);
WriteFile data = new WriteFile(file_name, true);
String[] aryLines = file.OpenFile();
int i;
int j;
int y;
for (i=0; i < aryLines.length; i++ ) { //goes through whole text file
System.out.println( aryLines[ i ]);
if (i == 0) {
data.writeToFile("");
System.lineSeparator();
}
char[] ch = aryLines[ i ].toCharArray();
ArrayList<Character> num = new ArrayList<Character>();
String xCo = null;
boolean counterX = false;
if ((ch[0]) == 'G' && ch[1] == '1') {
for (j = 0; j < ch.length; j++) { //goes through each line of text file
for (y = 0; counterX == true; y++) {
num.add(ch[j]);
}
if (ch[j] == 'X') {
counterX = true;
}
else if (ch[j] == ' ') {
counterX = false;
}
}
xCo = num.toString();
data.writeToFile("MOVX (" + xCo + ")");
}
num.clear();
}
}
catch (IOException e) {
System.out.println( e.getMessage() );
}
System.out.println("Text File Written To");
}
}
I'd suggest to avoid reading data into memory and to use streaming instead.
Then function which converts lines could look like:
public void convertFile(String fileName, String tmpFileName) throws IOException {
try (FileWriter writer = new FileWriter(tmpFileName, true)){
Pattern pG1_X = Pattern.compile("^G1 X");
Files.newBufferedReader(Paths.get(fileName)).lines().forEach(line -> {
try {
double x = Double.parseDouble(pG1_X.split(line)[1]); // get coordinate
String newLine = String.format("MOVX(%f)\n",x); // attempt to replace coordinate format
writer.write(newLine);
} catch (Exception e) {
LOGGER.log(Level.WARNING, String.format("error wile converting line %s", line), e);
}
});
}
}
Testcase which demonstrates how it works:
package com.github.vtitov.test;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Random;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.nio.file.StandardCopyOption;
#RunWith(Theories.class)
public class ReadWriteTest {
final static Logger LOGGER = Logger.getLogger(ReadWriteTest.class.getName());
public void convertFile(String fileName, String tmpFileName) throws IOException {
try (FileWriter writer = new FileWriter(tmpFileName, true)){
Pattern pG1_X = Pattern.compile("^G1 X");
Files.newBufferedReader(Paths.get(fileName)).lines().forEach(line -> {
try {
double x = Double.parseDouble(pG1_X.split(line)[1]); // get coordinate
String newLine = String.format("MOVX(%f)\n",x); // attempt to replace coordinate format
writer.write(newLine);
} catch (Exception e) {
LOGGER.log(Level.WARNING, String.format("error wile converting line %s", line), e);
}
});
}
}
#DataPoints static public Long[] fileSizes() {return new Long[]{100L,10_000L,1_000_000L}; }
#Theory
public void readWriteTest(Long fileSize) throws Exception {
TemporaryFolder folder = TemporaryFolder.builder().parentFolder(new File("target")).build();
folder.create();
File file = folder.newFile(UUID.randomUUID() + ".txt");
File tmpFile = folder.newFile(file.getName() + ".tmp");
createFile(fileSize, file);
String filePath = file.getPath();
LOGGER.info(String.format("created file %s of %d lines", filePath, fileSize));
String tmpFilePath = filePath + ".tmp";
convertFile(filePath, tmpFilePath);
LOGGER.info(String.format("file %s converted to %s", filePath, tmpFilePath));
//assert false;
Files.move(new File(tmpFilePath).toPath(), new File(filePath).toPath(),
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
LOGGER.info(String.format("file %s moved to %s", tmpFilePath, filePath));
folder.delete();
}
private void createFile(long fileSize, File file) throws Exception {
try (FileWriter writer = new FileWriter(file,true)) {
Random rnd = new Random();
rnd.doubles(fileSize).forEach(l -> {
try { writer.write(String.format("G1 X%f\n", l)); } catch (IOException ignored) {}
});
}
}
}
I have my code. I think it's all right, but it is not. It keeps telling me at the beginning of each method that there is a ';' expected and it's also an 'illegal start of expression' with the void. I do not know how to fix it. Can someone please help me fix these errors?
Here's an example of the Errors:
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:203: error: ';' expected
void arrayList **()** throws FileNotFoundException();
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: illegal start of expression
**void** output()
F:\COMP SCI\Topic 29 - Data Structures -- Robin Hood\Problem Set\RobinHoodApp.java:212: error: ';' expected
void output **()**
My code:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp{
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// scrubber();
//Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
void arrayList() throws FileNotFoundException();
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
//Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
// void scrubber()
// {
//
// }
//
//
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
}
You should use a Java IDE like Eclipse when programming Java, it would point out to you the most obvious mistakes in your code.
You missed a } after the while loop for your readFile() method (thanks to Sweeper for this one).
The syntax in your arrayList() method is wrong.
void arrayList() throws FileNotFoundException(); {
No semicolon at the end of this defintion, no parenthesis at the end too, you are describing the class, not a method. Here is the correct way:
void arrayList() throws FileNotFoundException {
1 useless } at the end of your class file.
Find below your code, with a proper layout and without syntax errors. Please use an IDE next time, that would avoid you an awful lot of trouble.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import static java.lang.System.out;
import java.util.ArrayList;
import javax.swing.JFrame;
public class RobinHoodApp {
public static void main(String[] args) throws FileNotFoundException, IOException {
RobinHood app = new RobinHood();
app.readFile();
app.arrayList();
app.wordCount();
app.countMenAtArms();
app.writeToFile();
}
}
class RobinHood extends JFrame
{
private static final ArrayList<String>words = new ArrayList<>();
private static Scanner book;
private static int count;
private static int wordCount;
public RobinHood()
{
try {
// Prints All Words 1 by 1: Works!
book = new Scanner(new File("RobinHood.txt") );
book.useDelimiter("\r\n");
} catch (FileNotFoundException ex)
{
out.println("Where's your text fam ?");
}
}
void readFile()
{
while(book.hasNext())
{
String text = book.next();
out.println(text);
}
}
void arrayList() throws FileNotFoundException
{
Scanner add = new Scanner(new File("RobinHood.txt"));
while(add.hasNext())
{
words.add(add.next());
}
}
void output()
{
out.println(words);
}
void countMenAtArms()
{
// Shows 23 times
String find = "men-at-arms";
count = 0;
int x;
String text;
for(x=0; x< wordCount; x++ )
{
text = words.get(x);
text = text.replaceAll("\n", "");
text = text.replaceAll("\n", "");
if (text.equals(find))
{
count++;
}
}
out.println("The amount of time 'men-at-arms' appears in the book is: " + count);
}
void wordCount()
{
{
wordCount=words.size();
out.println("There are "+wordCount+" words in Robin Hood.");
}
}
public void writeToFile()
{
File file;
file = new File("Dominique.dat");
try (FileOutputStream data = new FileOutputStream(file)) {
if ( !file.exists() )
{
file.createNewFile();
}
String wordCountSentence = "There are "+ wordCount +" words in Robin Hood. \n";
String countTheMen = "The amount of time 'men-at-arms' appears in the book is: " + count;
byte[] strToBytes = wordCountSentence.getBytes();
byte[] menToBytes = countTheMen.getBytes();
data.write(strToBytes);
data.write(menToBytes);
data.flush();
data.close();
}
catch (IOException ioe)
{
System.out.println("Error");
}
}
}
throws FileNotFoundException();
This should be
throws FileNotFoundException
and similarly in all cases.
Rather trivial. Don't just make up the syntax. Look it up.
I am writing this to take in data about books from a txt file. (ISBN, Price, Stock) I keep running into FileNotFoundException problems and cant figure out where the problem is. Sorry if the code is bad or whatever i'm still very now to programming.
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileNotFoundException;
import java.io.File;
public class BookInventory {
static ArrayList ISBN = new ArrayList();
static ArrayList Price = new ArrayList();
static ArrayList Stock = new ArrayList();
public static void main(String[] args)throws FileNotFoundException{
if(handleArgs(args)){
for(int j = 0; j < args.length; j++){
getInventory(args, j);
}
}
}
public static void getInventory(String[]args, int j)throws FileNotFoundException{
Scanner input = null;
try {
File inputFile = new File(args[j]);
Scanner booksFile = new Scanner(inputFile);
if(booksFile.hasNextDouble()){
while (booksFile.hasNext()) {
try {
ISBN.add(booksFile.next());
Price.add(booksFile.next());
Stock.add(booksFile.next());
} catch (java.util.InputMismatchException ex) {
throw ex;
}
}
}
} catch (FileNotFoundException ex) {
System.out.println("Error: File " + args[j] + " not found. Exiting program.");
System.exit(1);
}
}
public static boolean handleArgs(String[]args){
if(args.length < 2){
System.out.println("Incorrect number of command line arguments.");
System.out.println("Program requires at least 2 files.");
return false;
}
return true;
}
}
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
class airport {
private static final String STDIN_FILENAME = "-";
public static treemap load_database (String database_name) {
treemap tree = new treemap ();
try {
Scanner database = new Scanner (new File (database_name));
for (int linenr = 1; database.hasNextLine(); ++linenr) {
String line = database.nextLine();
if (line.matches ("^\\s*(#.*)?$")) { continue;
//there is a problem with the below line
String[] keyvalue = line.split (":");
if (keyvalue.length != 2) {
misc.warn (database_name, linenr, "invalid line");
continue;
}
tree.put (keyvalue[0], keyvalue[1]);
}
database.close();
}
}
catch (IOException error) {
misc.warn (error.getMessage());
}
return tree;
}
}
if (line.matches ("^\\s*(#.*)?$")) {
continue;
// unreachable code
Execution does not go past continue. So everything after it in that block is unreachable.
Maybe you wanted to close the } after continue?
i am having a program in java.which system.out some strings,i need to save each of them in a text file
it is showing in a format
ruo1 row2 row3
i want it in
row1
row2
row3
how can i do that in java?
import java.util.Arrays;
import java.io.*;
public class BruteForce {
public static FileOutputStream Output;
public static PrintStream file;
public static String line;
public static void main(String[] args) {
String password = "javabeanc";
char[] charset = "abcdefghijklmnopqrstuvwxyz".toCharArray();
BruteForce bf = new BruteForce(charset, 8);
String attempt = bf.toString();
while (true) {
FileWriter writer;
try {
writer = new FileWriter("test.txt");
writer.write(attempt+"\n");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
attempt = bf.toString();
System.out.println("Tried: " + attempt);
bf.increment();
}
}
private char[] cs; // Character Set
private char[] cg; // Current Guess
public BruteForce(char[] characterSet, int guessLength) {
cs = characterSet;
cg = new char[guessLength];
Arrays.fill(cg, cs[0]);
}
public void increment() {
int index = cg.length - 1;
while(index >= 0) {
if (cg[index] == cs[cs.length-1]) {
if (index == 0) {
cg = new char[cg.length+1];
Arrays.fill(cg, cs[0]);
break;
} else {
cg[index] = cs[0];
index--;
}
} else {
cg[index] = cs[Arrays.binarySearch(cs, cg[index]) + 1];
break;
}
}
}
public String toString() {
return String.valueOf(cg);
}
}
Very quick code. I apologize if there are compile errors.
import java.io.FileWriter;
import java.io.IOException;
public class TestClass {
public static String newLine = System.getProperty("line.separator");
public static void main(String[] a) {
FileWriter writer;
try {
writer = new FileWriter("test.txt");
for(int i=0;i<3;i++){
writer.write(row+i+newLine);
}
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
how about adding a new line character "\n" to each row ?
u can use PrintWriter pw;
pw.println(row+i)
in above instead of hard coding newLine
Using JDK 11 one can write:
public void writeToFile() {
String content = "Line 1\nLine 2";
Path path = Paths.get("./resources/sample-new.txt");
Files.writeString(path, content);
}