can't figure out initialization error - java [duplicate] - java

This question already has answers here:
Variable might not have been initialized error
(12 answers)
Closed 5 years ago.
I can not for the life of me figure out why I'm getting a "variable key might not have been initialized" error. I've entered my entire code because if I remove the BufferedReader and set the string equal to I don't get the error. Also, if I leave the BufferedReader part in and remove the StringBuffer part, string key initializes just fine. Please help! New to java (and programming in general).
import java.util.*;
import java.io.*;
public class reverseString {
public static void main(String [] args) {
String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String cipher = "";
String input = "";
String newCipher;
String ouput = "";
BufferedReader readerKeyword = null;
String key;
try {
readerKeyword = new BufferedReader(new FileReader("keyword.txt"));
} catch (FileNotFoundException fnfex) {
System.out.println(fnfex.getMessage() + " File not found.");
System.exit(0);
}
try {
while ((key = readerKeyword.readLine()) !=null) {
System.out.println(key);
}
} catch (IOException ioex) {
System.out.println(ioex.getMessage() + " Unable to read file.");
System.exit(0);
}
StringBuffer sb = new StringBuffer();
int len = abc.length();
for(int i = len -1;i>=0;i--)
cipher = cipher + abc.charAt(i);
System.out.println(abc);
System.out.println(cipher);
newCipher = sb.append(key + cipher).toString();
System.out.println(newCipher);
System.out.println(removeDuplicates(newCipher));
}
static String removeDuplicates(String newCipher) {
char[] charArr = newCipher.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for(char ch : charArr) {
charSet.add(ch);
}
StringBuffer StrBuf = new StringBuffer();
for(char c : charSet) {
StrBuf.append(c);
}
return StrBuf.toString();
}
}
Was is not initialized in the while loop at line28?

IDE and Compiler shows it when it is not guaranteed initialization for safety/precaution. Do this and it should go away,
BufferedReader readerKeyword = null;
String key = null;
However, do make sure that it gets initialized.
It is not guaranteed initialization because it is inside a try-catch block and if you get an exception, you can get by without initialization because, you are handling it.

Related

Returning Strings from a file between 2 specified strings in java

I've been searching the web and I can't seem to find a working solution.
I have a file containing theses lines:
Room 1
Coffee
Iron
Microwave
Room_end
Room 2
Coffee
Iron
Room_end
I want to print all Strings between Room 1 and Room_end. I want my code to start when it find Room 1, print line after Room 1 and stop when it get to the first Room_end it find.
private static String LoadRoom(String fileName) {
List<String> result = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
result = reader.lines()
.dropWhile(line -> !line.equals("Room 1"))
.skip(1)
.takeWhile(line -> !line.equals("Room_end"))
.collect(Collectors.toList());
} catch (IOException ie) {
System.out.println("Unable to create " + fileName + ": " + ie.getMessage());
ie.printStackTrace();
}
for (int i = 0; i < result.size(); i++) {
System.out.println(result.get(i).getname());//error on getname because it cant work with Strings
}
}
class Model {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I am able to get a method to print all Strings of the file but not specific range of Strings. I also tried to work with Stream. My code feel quite messy, but I've been working on it for a while an it seems it only get messier.
I think there is a problem if you want to use lambda expression here:
lambda expressions are functional programming, and functional programming requires immutability, that means there should not be state related issue, you can call the function and give it same parameters and the result always will be the same, but in your case, there should be a state indicating whether you should print the line or not.
can you try this solution? I write it in python, but mainly it is just about a variable should_print that located outside of the scope
should_print = False
result = reader.lines()
for line in result:
if line == "Room end":
break
if should_print:
print(line)
if line == "Room 1":
should_print = True
keep a boolean value outside of the iteration, and check/update the value in each iteration
public static Map<String, List<String>> getRooms(String path) throws IOException {
Map<String, List<String>> result = new HashMap<>();
try (Scanner sc = new Scanner(new File(path))) {
sc.useDelimiter("(?=Room \\d+)|Room_end");
while (sc.hasNext()) {
Scanner lines = new Scanner(sc.next());
String room = lines.nextLine().trim();
List<String> roomFeatures = new ArrayList<>();
while (lines.hasNextLine()) {
roomFeatures.add(lines.nextLine());
}
if (room.length() > 0) {
result.put(room, roomFeatures);
}
}
}
return result;
}
is one way of doing it for your 'rooms file' though it should really be made more OO by making a Room bean to hold the data. Output with your file: {Room 2=[Coffee, Iron ], Room 1=[Coffee, Iron, Microwave]}
Switched my code and used this:
private static String loadRoom(String fileName) {
BufferedReader reader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
reader = new BufferedReader(new FileReader(fileName));
String line = null; //we start with empty info
String ls = System.getProperty("line.separator"); //make a new line
while ((line = reader.readLine()) != null) { //consider if the line is empty or not
if (line.equals("Room 1")) { //condition start on the first line being "Room 1"
line = reader.readLine(); // read the next line, "Room 1" not added to stringBuilder
while (!line.equals("Room_end")) { //check if line String is "Room_end"
stringBuilder.append(line);//add line to stringBuilder
stringBuilder.append(ls);//Change Line in stringBuilder
line = reader.readLine();// read next line
}
}
}
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
Here's a solution that uses a scanner and a flag. You may choose to break the loop when it reads "Room_end"
import java.util.Scanner;
import java.io.*;
public class Main{
private static String loadRoom(String fileName) throws IOException {
Scanner s = new Scanner(new File(fileName));
StringBuilder sb = new StringBuilder();
boolean print = false;
while(s.hasNextLine()){
String line = s.nextLine();
if (line.equals("Room 1")) print = true;
else if (line.equals("Room_end")) print = false;
else if (print) sb.append(line).append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
try {
String content = loadRoom("content.txt");
System.out.println(content);
}catch(IOException e){
System.out.println(e.getMessage());
}
}
}

JAVA write on specific line using BufferedWriter [duplicate]

How do I replace a line of text found within a text file?
I have a string such as:
Do the dishes0
And I want to update it with:
Do the dishes1
(and vise versa)
How do I accomplish this?
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JCheckBox checkbox = (JCheckBox) e.getSource();
if (checkbox.isSelected()) {
System.out.println("Selected");
String s = checkbox.getText();
replaceSelected(s, "1");
} else {
System.out.println("Deselected");
String s = checkbox.getText();
replaceSelected(s, "0");
}
}
};
public static void replaceSelected(String replaceWith, String type) {
}
By the way, I want to replace ONLY the line that was read. NOT the entire file.
At the bottom, I have a general solution to replace lines in a file. But first, here is the answer to the specific question at hand. Helper function:
public static void replaceSelected(String replaceWith, String type) {
try {
// input the file content to the StringBuffer "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
StringBuffer inputBuffer = new StringBuffer();
String line;
while ((line = file.readLine()) != null) {
inputBuffer.append(line);
inputBuffer.append('\n');
}
file.close();
String inputStr = inputBuffer.toString();
System.out.println(inputStr); // display the original file for debugging
// logic to replace lines in the string (could use regex here to be generic)
if (type.equals("0")) {
inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0");
} else if (type.equals("1")) {
inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");
}
// display the new file for debugging
System.out.println("----------------------------------\n" + inputStr);
// write the new string with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("notes.txt");
fileOut.write(inputStr.getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
Then call it:
public static void main(String[] args) {
replaceSelected("Do the dishes", "1");
}
Original Text File Content:
Do the dishes0
Feed the dog0
Cleaned my room1
Output:
Do the dishes0
Feed the dog0
Cleaned my room1
----------------------------------
Do the dishes1
Feed the dog0
Cleaned my room1
New text file content:
Do the dishes1
Feed the dog0
Cleaned my room1
And as a note, if the text file was:
Do the dishes1
Feed the dog0
Cleaned my room1
and you used the method replaceSelected("Do the dishes", "1");,
it would just not change the file.
Since this question is pretty specific, I'll add a more general solution here for future readers (based on the title).
// read file one line at a time
// replace line as you read the file and store updated lines in StringBuffer
// overwrite the file with the new lines
public static void replaceLines() {
try {
// input the (modified) file content to the StringBuffer "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
StringBuffer inputBuffer = new StringBuffer();
String line;
while ((line = file.readLine()) != null) {
line = ... // replace the line here
inputBuffer.append(line);
inputBuffer.append('\n');
}
file.close();
// write the new string with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("notes.txt");
fileOut.write(inputBuffer.toString().getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
Since Java 7 this is very easy and intuitive to do.
List<String> fileContent = new ArrayList<>(Files.readAllLines(FILE_PATH, StandardCharsets.UTF_8));
for (int i = 0; i < fileContent.size(); i++) {
if (fileContent.get(i).equals("old line")) {
fileContent.set(i, "new line");
break;
}
}
Files.write(FILE_PATH, fileContent, StandardCharsets.UTF_8);
Basically you read the whole file to a List, edit the list and finally write the list back to file.
FILE_PATH represents the Path of the file.
If replacement is of different length:
Read file until you find the string you want to replace.
Read into memory the part after text you want to replace, all of it.
Truncate the file at start of the part you want to replace.
Write replacement.
Write rest of the file from step 2.
If replacement is of same length:
Read file until you find the string you want to replace.
Set file position to start of the part you want to replace.
Write replacement, overwriting part of file.
This is the best you can get, with constraints of your question. However, at least the example in question is replacing string of same length, So the second way should work.
Also be aware: Java strings are Unicode text, while text files are bytes with some encoding. If encoding is UTF8, and your text is not Latin1 (or plain 7-bit ASCII), you have to check length of encoded byte array, not length of Java string.
I was going to answer this question. Then I saw it get marked as a duplicate of this question, after I'd written the code, so I am going to post my solution here.
Keeping in mind that you have to re-write the text file. First I read the entire file, and store it in a string. Then I store each line as a index of a string array, ex line one = array index 0. I then edit the index corresponding to the line that you wish to edit. Once this is done I concatenate all the strings in the array into a single string. Then I write the new string into the file, which writes over the old content. Don't worry about losing your old content as it has been written again with the edit. below is the code I used.
public class App {
public static void main(String[] args) {
String file = "file.txt";
String newLineContent = "Hello my name is bob";
int lineToBeEdited = 3;
ChangeLineInFile changeFile = new ChangeLineInFile();
changeFile.changeALineInATextFile(file, newLineContent, lineToBeEdited);
}
}
And the class.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
public class ChangeLineInFile {
public void changeALineInATextFile(String fileName, String newLine, int lineNumber) {
String content = new String();
String editedContent = new String();
content = readFile(fileName);
editedContent = editLineInContent(content, newLine, lineNumber);
writeToFile(fileName, editedContent);
}
private static int numberOfLinesInFile(String content) {
int numberOfLines = 0;
int index = 0;
int lastIndex = 0;
lastIndex = content.length() - 1;
while (true) {
if (content.charAt(index) == '\n') {
numberOfLines++;
}
if (index == lastIndex) {
numberOfLines = numberOfLines + 1;
break;
}
index++;
}
return numberOfLines;
}
private static String[] turnFileIntoArrayOfStrings(String content, int lines) {
String[] array = new String[lines];
int index = 0;
int tempInt = 0;
int startIndext = 0;
int lastIndex = content.length() - 1;
while (true) {
if (content.charAt(index) == '\n') {
tempInt++;
String temp2 = new String();
for (int i = 0; i < index - startIndext; i++) {
temp2 += content.charAt(startIndext + i);
}
startIndext = index;
array[tempInt - 1] = temp2;
}
if (index == lastIndex) {
tempInt++;
String temp2 = new String();
for (int i = 0; i < index - startIndext + 1; i++) {
temp2 += content.charAt(startIndext + i);
}
array[tempInt - 1] = temp2;
break;
}
index++;
}
return array;
}
private static String editLineInContent(String content, String newLine, int line) {
int lineNumber = 0;
lineNumber = numberOfLinesInFile(content);
String[] lines = new String[lineNumber];
lines = turnFileIntoArrayOfStrings(content, lineNumber);
if (line != 1) {
lines[line - 1] = "\n" + newLine;
} else {
lines[line - 1] = newLine;
}
content = new String();
for (int i = 0; i < lineNumber; i++) {
content += lines[i];
}
return content;
}
private static void writeToFile(String file, String content) {
try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"))) {
writer.write(content);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String readFile(String filename) {
String content = null;
File file = new File(filename);
FileReader reader = null;
try {
reader = new FileReader(file);
char[] chars = new char[(int) file.length()];
reader.read(chars);
content = new String(chars);
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return content;
}
}
Sharing the experience with Java Util Stream
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public static void replaceLine(String filePath, String originalLineText, String newLineText) {
Path path = Paths.get(filePath);
// Get all the lines
try (Stream<String> stream = Files.lines(path, StandardCharsets.UTF_8)) {
// Do the line replace
List<String> list = stream.map(line -> line.equals(originalLineText) ? newLineText : line)
.collect(Collectors.toList());
// Write the content back
Files.write(path, list, StandardCharsets.UTF_8);
} catch (IOException e) {
LOG.error("IOException for : " + path, e);
e.printStackTrace();
}
}
Usage
replaceLine("test.txt", "Do the dishes0", "Do the dishes1");
//Read the file data
BufferedReader file = new BufferedReader(new FileReader(filepath));
StringBuffer inputBuffer = new StringBuffer();
String line;
while ((line = file.readLine()) != null) {
inputBuffer.append(line);
inputBuffer.append('\n');
}
file.close();
String inputStr = inputBuffer.toString();
// logic to replace lines in the string (could use regex here to be generic)
inputStr = inputStr.replace(str, " ");
//'str' is the string need to update in this case it is updating with nothing
// write the new string with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream(filer);
fileOut.write(inputStr.getBytes());
fileOut.close();
Well you would need to get a file with JFileChooser and then read through the lines of the file using a scanner and the hasNext() function
http://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html
once you do that you can save the line into a variable and manipulate the contents.
just how to replace strings :) as i do
first arg will be filename second target string third one the string to be replaced instead of targe
public class ReplaceString{
public static void main(String[] args)throws Exception {
if(args.length<3)System.exit(0);
String targetStr = args[1];
String altStr = args[2];
java.io.File file = new java.io.File(args[0]);
java.util.Scanner scanner = new java.util.Scanner(file);
StringBuilder buffer = new StringBuilder();
while(scanner.hasNext()){
buffer.append(scanner.nextLine().replaceAll(targetStr, altStr));
if(scanner.hasNext())buffer.append("\n");
}
scanner.close();
java.io.PrintWriter printer = new java.io.PrintWriter(file);
printer.print(buffer);
printer.close();
}
}

Removing redundant letters then declaring string as charArr

I'm trying to encrypt and decrypt strings using cipher text with a random keyword. The random keyword will be in a file "keyword.txt":
TROYONLINE
The string(s) will be in a separate file "input.txt":
THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG
more lines here....
The cipher should use the keyword and a reversed alphabet without redundant letters. The cipher for keyword "TROYONLINE" would be:
TROYNLIEZXWVUSQPMKJHGFDCBA
Using this cipher, the above string will be encrypted to this:
HEN MGZOW RKQDS LQC XGUPNY QFNK HEN VTAB YQI
So far, I have this code:
import java.util.*;
import java.io.*;
public class reverseString
{
public static void main(String [] args)
{
String abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String cipher = "";
String newCipher;
String encrypt = "";
String ouput = "";
BufferedReader readerKeyword = null;
String key = "";
try
{
readerKeyword = new BufferedReader(new FileReader("keyword.txt"));
}
catch (FileNotFoundException fnfex)
{
System.out.println(fnfex.getMessage() + " File not found.");
System.exit(0);
}
try
{
while ((key = readerKeyword.readLine()) !=null)
{
StringBuffer sb = new StringBuffer();
int len = abc.length();
for(int i = len -1;i>=0;i--)
cipher = cipher + abc.charAt(i);
newCipher = sb.append(key).append(cipher).toString();
System.out.println(key);
System.out.println(removeDuplicates(newCipher));
}
}
catch (IOException ioex)
{
System.out.println(ioex.getMessage() + " Unable to read file.");
System.exit(0);
}
BufferedReader readerInput = null;
String lineInput;
try
{
readerInput = new BufferedReader(new FileReader ("input.txt"));
}
catch (FileNotFoundException fnfex)
{
System.out.println(fnfex.getMessage() + " File not found.");
System.exit(0);
}
try
{
while ((lineInput = readerInput.readLine()) !=null)
{
char[] inputArray = lineInput.toCharArray();
System.out.println(inputArray);
}
}
catch (IOException ioex)
{
System.out.println(ioex.getMessage() + " Unable to read file.");
}
}
static String removeDuplicates(String newCipher)
{
char[] charArr = newCipher.toCharArray();
Set<Character> charSet = new LinkedHashSet<Character>();
for(char ch : charArr)
{
charSet.add(ch);
}
StringBuffer StrBuf = new StringBuffer();
for(char c : charSet)
{
StrBuf.append(c);
}
char[] cipherArray = removeDuplicates(newCipher).toCharArray();
System.out.println(cipherArray);
return StrBuf.toString();
}
}
But I'm getting the below error:
TROYONLINE
Exception in thread "main" java.lang.StackOverflowError
at java.util.HashMap.<init>(HashMap.java:456)
at java.util.LinkedHashMap.<init>(LinkedHashMap.java:347)
at java.util.HashSet.<init>(HashSet.java:161)
at java.util.LinkedHashSet.<init>(LinkedHashSet.java:154)
at reverseString.removeDuplicates(reverseString.java:83)
at reverseString.removeDuplicates(reverseString.java:94)
With a ton of repeats of the last line ...(reverseString.java:94)
EDIT
Belows is how I would do this in your situation. But keep this in mind:
It makes no sense to have your key and the input text in files. If you have a lot of input lines then you would pass the key as a command line argument and have only one while loop that reads the input file and uses the same key to encrypt and decrypt. If you do have multiple keys, then you need to read each key and then read the whole input file line by line, then read the next key and read the input file again, etc., etc.
I have all of the logic in the main method but you should break it down into separate methods.
Main class:
String defaultAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
BufferedReader keyInputLine;
String key;
String cipher = "";
BufferedReader inputLine;
String inputText;
StringBuilder encryptedText;
StringBuilder decryptedText;
try {
keyInputLine = new BufferedReader(new FileReader("keyword.txt"));
while ((key = keyInputLine.readLine()) != null) {
System.out.println("key: " + key);
StringBuilder stringBuilder = new StringBuilder();
// cipher is the key word plus the reverse of the alphabet
cipher = stringBuilder.append(key).append(new StringBuilder(defaultAlphabet).reverse().toString()).toString();
System.out.println("cipher: " + cipher);
// remove duplicates from cipher
cipher = removeDuplicates(cipher);
System.out.println("replaced cipher: " + cipher);
}
inputLine = new BufferedReader(new FileReader("input.txt"));
while ((inputText = inputLine.readLine()) != null) {
System.out.println("original: " + inputText);
encryptedText = new StringBuilder();
for (char c : inputText.toCharArray()) {
// find the input letter in the alphabet
if (defaultAlphabet.indexOf(c) != -1) {
// replace with same index from the cipher
encryptedText.append(cipher.toCharArray()[defaultAlphabet.indexOf(c)]);
} else {
// if not found, use default (ex: space)
encryptedText.append(c);
}
}
System.out.println("encrypted: " + encryptedText.toString());
decryptedText = new StringBuilder();
for (char c : encryptedText.toString().toCharArray()) {
// find the encrypted letter in the cipher
if (cipher.indexOf(c) != -1) {
// replace with same index from the cipher
decryptedText.append(defaultAlphabet.toCharArray()[cipher.indexOf(c)]);
} else {
// if not found, use default (ex: space)
decryptedText.append(c);
}
}
System.out.println("decrypted: " + decryptedText.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
The remove duplicates method:
static String removeDuplicates(String cipher) {
Set<Character> charSet = new LinkedHashSet<Character>();
for (char ch : cipher.toCharArray()) {
charSet.add(ch);
}
StringBuilder stringBuilder = new StringBuilder();
for (char c : charSet) {
stringBuilder.append(c);
}
return stringBuilder.toString();
}
Previous Answer
It's like the error says, the "lineKeyword" variable is not initialized before being used. Consider that it is possible that there is an exception in your second try/catch. The exception is caught and you print a message but "lineKeyword" is still uninitialized.
There is a good answer here: Uninitialized variables and members in Java
The language defines it this way.
Instance variables of object type default to being initialized to null. Local variables of object type are not initialized by default and it's a compile time error to access an undefined variable.
See section 4.5.5 in here http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html#96595
I ended up putting my cipher code in a the while loop on the BufferedReader code and it cleared it up.
{
BufferedReader readerKeyword = null;
String key = "";
try
{
readerKeyword = new BufferedReader(new FileReader("keyword.txt"));
}
catch (FileNotFoundException fnfex)
{
System.out.println(fnfex.getMessage() + " File not found.");
System.exit(0);
}
try
{
while ((key = readerKeyword.readLine()) !=null)
{
StringBuffer sb = new StringBuffer();
int len = abc.length();
for(int i = len -1;i>=0;i--)
cipher = cipher + abc.charAt(i);
newCipher = sb.append(key).append(cipher).toString();
System.out.println(key);
System.out.println(removeDuplicates(newCipher));
}
}
catch (IOException ioex)
{
System.out.println(ioex.getMessage() + " Unable to read file.");
System.exit(0);
}

Why is there no output when I run my code?

I am trying to read a file called ecoli.txt, which contains the DNA sequence for ecoli, and store its contents into a string. I tried to print the string to test my code. However, when I run the program, there is no output. I am still new to java so I am sure there is an error in my code, I just need help finding it.
package codons;
import java.io.*;
public class codons
{
public static void main(String[] args)
{
try
{
FileReader codons = new FileReader("codons.txt");
FileReader filereader = new FileReader("ecoli.txt");
BufferedReader ecoli = new BufferedReader(filereader);
StringBuilder dna_string = new StringBuilder();
String line = ecoli.readLine();
while(line != null);
{
dna_string.append(line);
line = ecoli.readLine();
}
String string = new String(dna_string);
System.out.println(string);
ecoli.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
edit:
I was still having trouble getting the program to work the way I wanted it to so I attempted to complete writing the rest of what I wanted in the program and I am still not getting any output. Anyway, this is where I am at now:
package codons;
import java.io.*;
import java.util.*;
import java.lang.*;
import java.text.*;
public class codons
{
public static void main(String[] args)
{
try
{
FileReader filecodons = new FileReader("codons.txt");
FileReader filereader = new FileReader("ecoli.txt");
BufferedReader ecoli = new BufferedReader(filereader);
StringBuilder dna_sb = new StringBuilder();
String line = ecoli.readLine();
while(line != null)
{
dna_sb.append(line);
line = ecoli.readLine();
}
String dna_string = new String(dna_sb);
ecoli.close();
BufferedReader codons = new BufferedReader(filecodons);
StringBuilder codon_sb = new StringBuilder();
String codon = codons.readLine();
while(codon != null)
{
codon_sb.append(codon);
line = codons.readLine();
}
String codon_string = new String(codon_sb);
codons.close();
for(int x = 0; x <= codon_sb.length(); x++)
{
int count = 0;
String codon_ss = new String(codon_string.substring(x, x+3));
for(int i = 0; i <= dna_sb.length(); i++)
{
String dna_ss = new String(dna_string.substring(i, i+3));
int result = codon_ss.compareTo(dna_ss);
if(result == 0)
{
count += 1;
}
}
System.out.print("The codon '");
System.out.print(codon_ss);
System.out.print("'is in the dna sequence");
System.out.print(count);
System.out.println("times.");
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Remove the ; after while(line != null), it causes an infinite loop instead of executing the next instructions.
The reason is explained here: Effect of semicolon after 'for' loop (the question is about the C language, but it is equivalent in Java).

Reverse a string without using string functions [duplicate]

This question already has answers here:
Printing reverse of any String without using any predefined function?
(34 answers)
Closed 9 years ago.
How to write a java program to reverse a string without using string functions?
String a="Siva";
for(int i=0;i<=a.length()-1;i++)
{
System.out.print(a.charAt(i));
}
System.out.println("");
for(int i = a.length() - 1; i >= 0; --i)
{
System.out.print(a.charAt(i));
}
here charAt() and a.length() are string functions
This will help
public class StringReverse {
public static void main(String[] args){
String str = "Reverse";
StringBuilder sb = new StringBuilder(str);
str = sb.reverse().toString();
System.out.println("ReverseString : "+str);
}
}
There is no usage of String methods
String s = "abcdef";
char c[] = s.toCharArray();
for( int i = c.length -1; i>=0; i--)
System.out.print(c[i]);
Use StringBuilder class or StringBuffer class they have already a method reverse() for reversing the string
StringBuilder str = new StringBuilder("india");
System.out.println("string = " + str);
// reverse characters of the StringBuilder and prints it
System.out.println("reverse = " + str.reverse());
// reverse is equivalent to the actual
str = new StringBuilder("malayalam");
System.out.println("string = " + str);
// reverse characters of the StringBuilder and prints it
System.out.println("reverse = " + str.reverse());
http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
Below is ugly hack. It concept but it not invoke any String methods.
import java.io.*;
import java.util.*;
public class Hello {
public static String reverceWithoutStringMethods(String word){
String result = "";
//------ Write string to file -----------
BufferedWriter writer = null;
try {
writer = new BufferedWriter( new FileWriter("tempfile"));
writer.write(word);
}
catch ( IOException e) {}
finally {
try{
if ( writer != null) writer.close( );
}
catch ( IOException e){}
}
//------ read string from file -------------
RandomAccessFile f=null;
try {
f = new RandomAccessFile("tempfile", "r"); // Open file
int length = (int) f.length(); // Get length
// Read file
byte[] data = new byte[length];
f.readFully(data);
// Reverse data
for (int i=data.length; i>=0; i--){
result += (char)data[i-1];
}
} catch(Exception e){}
finally {
try{
f.close();
}
catch (Exception e){}
}
return result;
}
public static void main(String[] args) {
System.out.println(reverceWithoutStringMethods("Test"));
System.out.println(reverceWithoutStringMethods(""));
}
}
Output:
tseT

Categories