I'm trying to write my java console output to a .txt file in my desktop.
But when that method starts, i have the console output and the txt file gets created, but it's empty and I realized that the BufferedReader (in) is not working... (Because of the "ok1 - i" statement)
The question is WHY?? or WHAT'S WRONG WITH MY CODE??
This is my code, so you can see and run it
package noobxd;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class Main {
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\Mario\\Desktop\\output.txt";
generate_codes();
writetxt(path);
}
private static void writetxt(String path) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new FileWriter(path));
try {
String inputLine;
inputLine = "";
int i=0;
System.out.println("Starting");
while (!inputLine.isEmpty()){
System.out.println("ok1"+i);
inputLine = in.readLine();
System.out.println("ok2"+i);
out.write(inputLine);
System.out.println("ok3"+i);
out.newLine();
System.out.println("ok4"+i);
i++;
}
System.out.print("Write Successful");
} catch (IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
in.close();
}
}
private static void generate_codes() {
Random rnd = new Random();
for (int i = 0; i < 30; i++) {
int code = rnd.nextInt(201) + 100;
int students = rnd.nextInt(31) + 40;
int j = rnd.nextInt(4);
String type = new String();
switch (j) {
case 0:
type = "Theory";
break;
case 1:
type = "Lab";
break;
case 2:
type = "Practice";
break;
case 3:
type = "Exam";
break;
}
System.out.println("TEL" + code + "-TopicNumber" + i + "-" + students + "-" + type);
}
}
}
Thanks for your time, please help me solve my problem.
String inputLine;
inputLine = "";
...
while (!inputLine.isEmpty()) // this is false and so the loop is not executed
In the future, please learn to use debugging tools and simply read your code more carefully. If you're trying to read until EOF, use
while ((inputLine = in.readLine()) != null) {
...
}
If you want to keep looping until the user enters an empty line at the console, you probably want something like
while (true) {
System.out.println("ok1"+i);
inputLine = in.readLine();
if (inputLine.isEmpty())
break;
// the rest of your loop
}
You probable should do something like this:
inputLine = in.readLine();
while (inputLine != null && !inputLine.isEmpty()){
System.out.println("ok1"+i);
System.out.println("ok2"+i);
out.write(inputLine);
System.out.println("ok3"+i);
out.newLine();
System.out.println("ok4"+i);
i++;
inputLine = in.readLine();
}
Related
I am new to java and this might sound really stupid but !
Assume you have this txt file somewhere in your pc
The_txt.txt
Anthony
anthonyk#somewhere.com
01234567891
location
Maria
maria#somewhere.com
1234561234
location2
George
george#somewhere.com
1234512345
location3
What i want to do with this txt is that , I prompt the user to insert a Phone number so if for example the user provides Maria's phone number (1234561234) the program will output
Maria
maria#somewhere.com
1234561234
location2
My piece of code for this task :
private static void Search_Contact_By_Phone(File file_location){
Scanner To_Be_String = new Scanner(System.in);
String To_Be_Searched = To_Be_String.nextLine();
System.out.println("\n \n \n");
BufferedReader Search_Phone_reader;
try {
Search_Phone_reader = new BufferedReader(new FileReader (file_location));
String new_line = Search_Phone_reader.readLine();
while (new_line != null) {
if (To_Be_Searched.equals(new_line)){
for (int i=0;i<=3;i++){
System.out.println(new_line);
new_line = Search_Phone_reader.readLine();
}
break;
}
new_line = Search_Phone_reader.readLine();
}
Search_Phone_reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Thank you in advance!!!
package com.mycompany.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
// For a small file
Path path = Paths.get("The_txt.txt");
String toBeSearched = "1234512345";
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
// Better performance if i starts at 2 and i += 4
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).equals(toBeSearched)) {
System.out.println(lines.get(i - 2));
System.out.println(lines.get(i - 1));
System.out.println(lines.get(i));
System.out.println(lines.get(i + 1));
}
}
// Else
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
String line1;
while ((line1 = reader.readLine()) != null) {
String line2 = reader.readLine();
String line3 = reader.readLine();
if (line3.equals(toBeSearched)) {
// Found
System.out.println(line1);
System.out.println(line2);
System.out.println(line3);
System.out.println(reader.readLine());
break;
} else {
reader.readLine();
}
}
}
}
}
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).
What I am trying to do here is read a file and count each character. Each character should add +1 to the "int count" and then print out the value of "int count".
I hope that what I am trying to do is clear.
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
int count = 0;
Scanner scan = null;
Scanner cCount = null;
try {
scan = new Scanner(new BufferedReader(new FileReader("greeting")));
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
}
finally {
if (scan != null) {
scan.close();
}
}
try {
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext("")) {
count++;
}
}
finally {
if (cCount != null) {
scan.close();
}
}
System.out.println(count);
}
}
Add a catch block to check for exception
Remove the parameter from hasNext("")
Move to the next token
cCount = new Scanner(new BufferedReader(new FileReader("greeting")));
while (cCount.hasNext()) {
count = count + (cCount.next()).length();
}
Using java 8 Stream API, you can do it as follow
package example;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CountCharacter {
private static int count=0;
public static void main(String[] args) throws IOException {
Path path = Paths.get("greeting");
try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
count = lines.collect(Collectors.summingInt(String::length));
}
System.out.println("The number of charachters is "+count);
}
}
Well if your looking for a way to count only all chars and integers without any blank spaces and things like 'tab', 'enter' etc.. then you could first remove those empty spaces using this function:
st.replaceAll("\\s+","")
and then you would just do a string count
String str = "a string";
int length = str.length( );
First of all, why would you use try { } without catch(Exception e)
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("greetings.txt"));
String line = null;
String text = "";
while ((line = reader.readLine()) != null) {
text += line;
}
int c = 0; //count of any character except whitespaces
// or you can use what #Alex wrote
// c = text.replaceAll("\\s+", "").length();
for (int i = 0; i < text.length(); i++) {
if (!Character.isWhitespace(text.charAt(i))) {
c++;
}
}
System.out.println("Number of characters: " +c);
} catch (IOException e) {
System.out.println("File Not Found");
} finally {
if (reader != null) { reader.close();
}
}
My assignment is as following Create Java program that reads from file create one person Object per line and stores object in a collection write the object out sorted by last name. this is what I have so far it compiles just fine but it doesn't print out anything. This is what I have so far
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileTester {
public static void main(String[] args) {
File testFile;
Scanner fileScanner;
try {
testFile = new File("sample.txt");
fileScanner = new Scanner(testFile);
fileScanner.useDelimiter(",");
while (fileScanner.hasNext()) {
System.out.println(fileScanner.next());
}
fileScanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
If it is a text file, please use BufferedReader. Then use String#split() to get the data. Instantiate as necessary.
BufferedReader reader = new BufferedReader(...);
String line = null;
while( (line = reader.readLine()) != null){
// magic
}
I do not know what you want to do. But this program take a file called "sample.txt" and divide in tokens this. For example if in the txt is "carlos,jose,herrera,matos" you program out
carlos
jose
herrera
matos
now if you want to sort this, you must create a class Person and implement the Comparable
Try this,
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(fileName)));
String content = null;
while((content = bufferedReader.readLine()) != null)
{
String[] details = content.split(",");
int i = 1;
for(String value : details)
{
switch(i)
{
case 1:
{
System.out.println("Name : "+value);
i=2;
break;
}
case 2:
{
System.out.println("Address : "+value);
i=3;
break;
}
case 3:
{
System.out.println("Number : "+value);
i = 1;
break;
}
}
}
}
I want to make a program which get questions and their answers from file with specific structure and let the user give answers to them. The program also have to count right answers and show them to the user.
Here is the sample of the text file structure:
What year is it right now?
2
1) 1900
2) 2014
3) 3200
---
Which is the biggest country in the world?
1
1) Russia
2) United States of America
3) United Kingdom
---
That's the code I wrote, but there something wrong and I can't see what exactly is:
public class testLoader {
private static BufferedReader br;
private static int answerCounter;
public static void main(String[] args) {
try {
br = new BufferedReader(new FileReader("D:/test.txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
String answer=null;
if(line.startsWith("*")){
answer = line;
}
while (line != "---") {
line = br.readLine();
sb.append(line);
sb.append(System.lineSeparator());
}
System.out.println(sb.toString());
answerCheck(answer);
line = br.readLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("You have " + answerCounter + "correct answers");
}
public static void answerCheck(String rightAnswer) {
System.out.println("What's your answer?");
Scanner input = new Scanner(System.in);
String answer = input.nextLine();
answerCounter = 0;
if (answer == rightAnswer){
answerCounter++;
System.out.println("Correct!");
} else {
System.out.println("Wrong!");
}
}
}
I'll apreciate any help you can give. If there are any better way to complete the task, I'll be glad to see it.
Thanks in advance!
Here is the corrected version of your program.
You had a few bugs in there.
My program works OK on the file format you posted
here (without the asterisks that is).
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class testLoader {
private static BufferedReader br;
private static int answerCounter = 0;
public static void main(String[] args) {
try {
br = new BufferedReader(new FileReader("C:/Various/test.txt"));
StringBuilder sb = new StringBuilder();
String line = null;
do {
line = br.readLine();
if (line != null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
} else {
break;
}
String answer = br.readLine().trim();
while (!"---".equals(line)) {
line = br.readLine();
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
System.out.println(sb.toString());
answerCheck(answer);
sb.setLength(0);
} while (true);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("You have " + answerCounter + " correct answers");
}
public static void answerCheck(String rightAnswer) {
System.out.println("What's your answer?");
Scanner input = new Scanner(System.in);
String answer = input.nextLine();
// answerCounter = 0;
if (answer.equals(rightAnswer)) {
answerCounter++;
System.out.println("Correct!");
} else {
System.out.println("Wrong!");
}
}
}
You want to seperate right answer from wrong ones with * sign but you are not providing it on your text file.
Even if you add * sign to the head of right answer, you won't make right answer value assigned to answer string variable.
Besides all of above, why do you want to check right answer with a * sign if you write the right answer's number below the question?
You have to compare strings with equals() method since you are dealing with values of strings, not memory addresses of them.
You have declared a StringBuilder object to append questions/answers and print them to screen but with this code, you will always add previous questions/answers to the current question. (i.e you are printing 2. question with first one above of it)
answerCounter variable will not hold user's total correct answers as you always assign it to 0 whenever you call the method.
So with all of these are corrected, I think you want to achieve something like below:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class testLoader
{
private static BufferedReader br;
private static int answerCounter = 0;
public static void main(String[] args)
{
try
{
br = new BufferedReader(new FileReader("C:/test.txt"));
StringBuilder sb;
String line, answer = null;
while((line = br.readLine()) != null)
{
sb = new StringBuilder();
do
{
if(line.length() == 1) //This is a bad choice of digit comparison but it will work with your case (lol)
{
answer = line;
line = br.readLine();
continue;
}
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
while(!line.equals("---"));
System.out.println(sb.toString());
answerCheck(answer);
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
br.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
System.out.println("You have " + answerCounter + "correct answers");
}
public static void answerCheck(String rightAnswer)
{
System.out.println("What's your answer?");
Scanner input = new Scanner(System.in);
String answer = input.nextLine();
if(answer.equals(rightAnswer))
{
answerCounter++;
System.out.println("Correct!");
}
else
{
System.out.println("Wrong!");
}
}
}