I reading a .txt file and want to skip a listing of code in this text, when putting result in StringBuilder.
The example of text:
The following Bicycle class is one possible implementation of a
bicycle:
/* The example of Bicycle class class Bicycle {
int cadence = 0;
int speed = 0; } */
So that's what I could come to:
public class Main {
public static BufferedReader in;
public static StringBuilder stringBuilder = new StringBuilder();
public static void main(String[] args) {
String input = "input_text.txt";
try {
in = new BufferedReader(new FileReader(input));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String inputText;
try {
while ((inputText = in.readLine()) != null) {
if (inputText.startsWith("/*")) {
// The problem is there:
while (!inputText.endsWith("*/")) {
int lengthLine = inputText.length();
in.skip((long)lengthLine);
}
}
stringBuilder.append(inputText);
}
} catch (IOException e) {
e.printStackTrace();
}
I got the infinity while loop and can't jump to next line.
You never reset the value of inputText in your while loop, so it will never not end with */ resulting in an infinite loop. Also you don't need to use the skip() method as simply reading the lines until you encounter a */ will work. Try changing your loop to:
while (!inputText.endsWith("*/")) {
String temp = in.readLine();
if(temp == null) {break;}
inputText = temp;
}
Output: (With printing the StringBuilder)
The following Bicycle class is one possible implementation of a bicycle:
Related
Facing some issues with my lab codes
I've done trouble shooting to find that both there's nothing wrong with my filereader/bufferedreaders, Vehicle method and LinkedList values
I'm found out that I'm having Problems getting the if statement to work
I do not know How do I compare the current linkedlist data extracted from my file.txt using tokenizer to pass into given fields with userinput using if/else ?
Main method
package test6;
// import packages
import java.util.LinkedList;
import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Lab6 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// Declare variables for reading file
FileReader fr = null;
BufferedReader br = null;
String inFile = "Vehicle_Records.txt";
final String INPUT_PROMPT = "\nPlease enter the search word " + "that you would like to obtain more information on:";
String line;
StringTokenizer tokenizer;
// Declare variables to contain the record fields
String group;
String brand;
String model;
double rate;
// Declare and instantiate a new LinkedList
LinkedList<Vehicle> list = new LinkedList<Vehicle>();
try {
// Instantiate FileReader & BufferedReader objects
fr = new FileReader(inFile);
br = new BufferedReader(fr);
//read a line from the file
line = br.readLine();
// While line is not null
while (line != null) {
// Tokenize the records
tokenizer = new StringTokenizer(line, ",");
group = tokenizer.nextToken();
brand = tokenizer.nextToken();
model = tokenizer.nextToken();
rate = Double.parseDouble(tokenizer.nextToken());
// Create a new Vehicle object of the record
Vehicle newVehicle = new Vehicle(group, brand, model, rate);
System.out.println(newVehicle);
// Add this item object into the LinkedList
list.add(newVehicle);
// Read another line from file
line = br.readLine();
}
// Close BufferedReader
br.close();
}
catch (FileNotFoundException e)
{
System.out.println("The file" + inFile + "was not found");
}
catch (IOException e)
{
System.out.println("Reading error!" + e);
}
finally
{
//Check if FileReader is opened
if (fr != null) {
try {
//close FileReader
fr.close();
} catch (IOException e) {
System.out.println("Error closing file!");
}
}
}
// Print out the input prompt
System.out.println(INPUT_PROMPT);
try
{
// Create readers to read from user input
//FileReader ufr = new FileReader(INPUT_PROMPT);
BufferedReader ubr = new BufferedReader(new InputStreamReader (System.in));
// Read one line from user input
String uline=ubr.readLine();
// Loop through all the records in the LinkedList
for(int i = 0; i< list.size(); i++)
{
// if the record is the same as the input from user
// (Hint: use contains() in String class to check whether
// search word is found in the records
String temp = new String(uline);
if(list.get(i)== uline.contains(temp))
{
//print out the information of the vehicle that match user input
System.out.println(list.get(i));
}
}
}
catch(IOException e)
{
System.out.println(e);
}
catch (Exception e)
{
System.out.println("Input error!" + e);
}
}
}//main
Vehical Class
package lab6;
public class Vehicle {
// Declare all the variables to contain the fields of a record
String group;
String brand;
String model;
double rate;
// Creates a constructor to store all the fields into the variables
public Vehicle(String group, String brand, String model, double rate)
{
this.group=group; this.brand=brand; this.model=model; this.rate=rate;
}
// Create a toString() method to return string in the same delimited
// format as the input record
public String toString()
{
return(group+","+brand+","+model+","+rate);
}
}
Your code is not inside a method , so you are facing a problem.
I assume since your looking through vehicle objects trying to find a match of one its four variables. Your approach is wrong since you're comparing an object with a String.
Instead you could use a Comparable interface inside the Vehicle class where you would simply compare multiple strings.
Edit:
public class Vehicle implements Comparable<String>{
/* This method returns 0 if the search matches
* Else it return a negative or a positive number*/
#Override
public int compareTo(String o) {
int cmp = this.getBrand().compareToIgnoreCase(o);
if(cmp == 0) return cmp;
cmp = this.getGroup().compareToIgnoreCase(o);
if(cmp == 0) return cmp;
cmp = this.getModel().compareToIgnoreCase(o);
if(cmp == 0) return cmp;
/* Edited this part to work with doubles */
try{
cmp = (int)(this.getRate() - Double.parseDouble(o));
}
catch(NumberFormatException e){
return cmp;
}
return cmp;
}
}
And here is how you would loop through it:
for(int i = 0; i< list.size(); i++){
if(list.get(i).compareTo(uline) == 0)
{
System.out.println(list.get(i));
}
}
Hope it help.
PS. I'm also new to this :)
AAAAAAAND I FINALLY FIGURED IT OUT TOGETHER WITH MY OTHER FRIEND
Still, I'd love to thank all of you for extending a hand to help me :')
Shall post the solution to my problem here
//-etc-
// Create readers to read from user input
//FileReader ufr = new FileReader(INPUT_PROMPT);
BufferedReader ubr = new BufferedReader(new InputStreamReader (System.in));
// Read one line from user input
String uline=ubr.readLine();
// Loop through all the records in the LinkedList
for(int i = 0; i< list.size(); i++)
{
// if the record is the same as the input from user
// (Hint: use contains() in String class to check whether
// search word is found in the records
Vehicle vehicle = list.get(i);
if(vehicle.group.contains(uline) ||
vehicle.brand.contains(uline) ||
vehicle.model.contains(uline))
{
//print out the information of the vehicle that match user input
System.out.println(list.get(i));
}
I have been working on this code for the day and am almost at the finish line. What I want is that the code should work as a clip card, remembering the number of purchased coffees, and awarding the customer a free coffee every 10th purchase. I'm writing to a file and reading from it in order for a customer to be able to continue his clip card where he left of last time. So to my problem...I have properly been able to write my "count" variable to a file, and it is storing it correctly. However, every time I run the program again it starts off a 0 and I don't see why. I need it to save the current count, and read the count once run again. For example, if a customer has previously purchased 7 coffees and is returning to the store, his counter needs to start at 7. For some reason it is not doing that.
Here's what I have so far:
public class FelixNeww {
public static void main(String [] args) {
Scanner key;
String entry;
int count = 0;
String password = "knusan01";
FelixNeww f = new FelixNeww();
System.out.println(f.readFromFile());
while(true) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
entry = key.nextLine();
if(entry.compareTo(password) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought "
+ count + " coffe(s)");
f.saveToFile(count);
}
if(count == 10 && count != 0){
System.out.println("YOU'VE GOT A FREE COFFE!");
count = 0;
}
if(entry.compareTo(password) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}
public void saveToFile(int count)
{
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("C:\\Temp\\countStorage.txt"))));
bw.write(Integer.toString(count));
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(bw != null)
{
try
{
bw.close();
}
catch(IOException e) {}
}
}
}
public int readFromFile()
{
BufferedReader br = null;
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Temp\\countStorage.txt"))));
String line = br.readLine();
int count = Integer.parseInt(line);
return count;
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(br != null)
{
try
{
br.close();
}
catch(IOException e) {}
}
}
return 0;
}
}
You are currently setting your count variable to 0. You should set it to the value that's in the file. Do this just before the while loop:
count = f.readFromFile();
while(true) {
You should also implement a way to gracefully exit the while loop. For example, if the user enters "q", you can execute the break; statement to exit the while loop. And after your while loop, call key.close(); to close the Scanner object.
The scope of count variable is local in both instances
public static void main(String [] args) {
Scanner key;
String entry;
int count = 0;
String password = "knusan01";
System.out.println(f.readFromFile());
public int readFromFile()
{
BufferedReader br = null;
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Temp\\countStorage.txt"))));
String line = br.readLine();
int count = Integer.parseInt(line);
return count;
In the readFromFile function, you read it from the file, return it, but don't keep track of it in a variable, why don't you replace the println with this inside your main:
count=f.readFromFile
My file has:
public class MyC{
public void MyMethod()
{
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
The code below does the following.
1. If line count equals num[index],it checks whether if that line contains the string from
VALUES1[index]. If true, it replace that string from the first index in VALUES[index] and writes to a new file.
2.If num index not equal num[index],it simply writes the line to new file as it is.
The problem am getting is that after writing to new file, original line 1 and 2 still appears in the new file. How to remove that.
Heres my code:
public class MainTest {
static int i ;
public static void main(String[] arg)
{
try {
int num[] = {1,2,4}; //Line Numbers
String[] VALUES = new String[] {"AB","BC","CD"}; //Correct Solutions
String[] VALUES1 = new String[] {"class","void","System"}; //To Replace
FileInputStream fs= new FileInputStream("C:\\Users\\Antish\\Desktop\\Test_File.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileWriter writer1 = new FileWriter("C:\\Users\\Antish\\Desktop\\Test_File1.txt");
String line;
String line1 = null;
Integer count =0;
line = br.readLine();
count++;
while(line!=null){
for(int index =0;index<num.length;index++){
if(count == num[index]){
if(line.contains(VALUES1[index])){
line1= line.replace(VALUES1[index], VALUES[index]);
writer1.write(line1+System.getProperty("line.separator"));
}
}
}
writer1.write(line+System.getProperty("line.separator"));
line = br.readLine();
count++;
}
writer1.close();
}
catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
Here is my result:
public AB MyC{
**public class MyC{ //This still appears.**
public BC MyMethod()
**public void MyMethod()//This still appears.**
{
CD.out.println("My method has been accessed");
System.out.println("My method has been accessed");
System.out.println("hi");
}
}
you should add an indicator to show if this line is replaced
while(line!=null){
boolean exists = false;
for(int index =0;index<num.length;index++){
if(count == num[index]){
if(line.contains(VALUES1[index])){
exists = true;
line1= line.replace(VALUES1[index], VALUES[index]);
writer1.write(line1+System.getProperty("line.separator"));
}
}
}
if (!exists)
writer1.write(line+System.getProperty("line.separator"));
comment this line in code
writer1.write(line+System.getProperty("line.separator"));
then try
Using the readLine() method of BufferedReader, can you print the first N lines of a stream in reverse order without using a list or an array?
I think you can do it through recursion with something like:
void printReversed(int n)
{
String line = reader.readLine();
if (n > 0)
printReversed(n-1);
System.out.println(line);
}
How about recursion to reverse the order?
Pseudo code:
reverse(int linesLeft)
if (linesLeft == 0)
return;
String line = readLine();
reverse(linesLeft - 1);
System.out.println(line);
Nice question. Here you have one solution based on coordinated threads. Although it's heavy on resources (1 thread/line of the buffer) it solves your problem within the given constrains. I'm curious to see other solutions.
public class ReversedBufferPrinter {
class Worker implements Runnable {
private final CountDownLatch trigger;
private final CountDownLatch release;
private final String line;
Worker(String line, CountDownLatch release) {
this.trigger = new CountDownLatch(1);
this.release = release;
this.line = line;
}
public CountDownLatch getTriggerLatch() {
return trigger;
}
public void run() {
try {
trigger.await();
} catch (InterruptedException ex) { } // handle
work();
release.countDown();
}
void work() {
System.out.println(line);
}
}
public void reversePrint(BufferedReader reader, int lines) throws IOException {
CountDownLatch initialLatch = new CountDownLatch(1);
CountDownLatch triggerLatch = initialLatch;
int count=0;
String line;
while (count++<lines && (line = reader.readLine())!=null) {
Worker worker = new Worker(line, triggerLatch);
triggerLatch = worker.getTriggerLatch();
new Thread(worker).start();
}
triggerLatch.countDown();
try {
initialLatch.await();
} catch (InterruptedException iex) {
// handle
}
}
public static void main(String [] params) throws Exception {
if (params.length<2) {
System.out.println("usage: ReversedBufferPrinter <file to reverse> <#lines>");
}
String filename = params[0];
int lines = Integer.parseInt(params[1]);
File file = new File(filename);
BufferedReader reader = new BufferedReader(new FileReader(file));
ReversedBufferPrinter printer = new ReversedBufferPrinter();
printer.reversePrint(reader, lines);
}
}
Here you have another alternative, based on BufferedReader & StringBuilder manipulations. More manageable in terms of computer resources needed.
public void reversePrint(BufferedReader bufReader, int lines) throws IOException {
BufferedReader resultBufferReader = null;
{
String line;
StringBuilder sb = new StringBuilder();
int count = 0;
while (count++<lines && (line = bufReader.readLine())!=null) {
sb.append('\n'); // restore new line marker for BufferedReader to consume.
sb.append(new StringBuilder(line).reverse());
}
resultBufferReader = new BufferedReader(new StringReader(sb.reverse().toString()));
}
{
String line;
while ((line = resultBufferReader.readLine())!=null) {
System.out.println(line);
}
}
}
it will also require implicit data structures, but you can spawn threads, run them inorder, and make each thread read a line and wait a decreasing amount of time. the result will be: the last thread will run first, and the first one will run last, each one printing its line. (the interval between them will have to be large enough to ensure large "safety margins")
I have no idea how, if any, that can be done with no explicit/implicit data storage.
Prepend each line you read to a string, and print the string. If you run out of lines to read, you just print what you have.
Alternatively, if you are certain of the number of lines you have, and you do not wish to use a string:
void printReversed(int n, BufferedReader reader)
{
LineNumberReader lineReader = new LineNumberReader(reader);
while (--i >= 0)
{
lineReader.setLineNumber(i);
System.out.println(lineReader.readLine());
}
}
I am trying to write a simple method to save my document to a file (overwriting any previous contents of the file.) Unfortunately, my implementation does not seem to work. I am calling it on my document, which is, for all intents and purposes, an array of String. What I'd like to do is to write the contents of my array, with a separate line for each value in the array, the value in position [0] on the first line, and the value for [1] on the second. How would I go about this ?
This is my implementation so far :
public void save()
{
try
{
PrintWriter outputFile =
new PrintWriter(new BufferedWriter(new FileWriter(docName)));
int lineNo = 1;
while (lineNo != lineNo) // CHANGE THIS!!!
{ outputFile.println(" ~ ");
lineNo++;
}
outputFile.flush();
}
catch (Exception e)
{
System.out.println("Document: Touble writing to "+docName);
System.exit(1);
}
}
If a is an array of strings,
for (String s : a)
outputFile.println(s);
will print the array line-by-line to outputFile.
Iterator over the array, and write the current element.
String document[] = {"String1","String2","String3"};
PrintWriter outputFile =
new PrintWriter(new BufferedWriter(new FileWriter(docName)));
int lineNo = 1;
for(int i = 0; i < document.length; i++)
{ outputFile.println(document[i]);
lineNo++;
}
// myDoc is the "array of string"
foreach (String line : myDoc) {
outputFile.println(line);
}
I might write it more like this:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
/**
* FileDemo
* #author Michael
* #since 2/26/11
*/
public class FileDemo
{
public static void main(String[] args)
{
try
{
FileDemo fd = new FileDemo();
fd.save("out/test.txt", args);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public void save(String filePath, String [] lines) throws FileNotFoundException
{
PrintStream ps = null;
try
{
ps = new PrintStream(new FileOutputStream(filePath));
int lineNum = 1;
for (String line : lines)
{
ps.printf("%5d %s\n", lineNum++, line);
}
}
finally
{
close(ps);
}
}
public static void close(PrintStream ps)
{
if (ps != null)
{
ps.flush();
ps.close();
}
}
}
I didn't see any actual content in your code, so I added some. I didn't how a file with line numbers was very interesting. You'd be able to modify this to make it differently if you wish.