how to take input from keyboard in java till some words - java

I want to take input from keyboard in my java program until the user type abc
Here is the code which i have written but it doesn't work. the program continues to take input from keyboard even after i have typed abc and lastly I have to close the program by myself. It takes in input from keyboard and write it on a file named file1.txt
import java.io.*;
import java.util.*;
public class io {
public static void main(String args[]) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("file1.txt", true));
Scanner keyboard = new Scanner(System.in);
do {
writer.write(keyboard.next());
writer.newLine();
} while (keyboard.next() != "abc");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Try this , it works, Just use while loop instead of do while
Code:
import java.io.*;
import java.util.*;
public class io{
public static void main(String args[]) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("file2.txt", true));
Scanner keyboard = new Scanner(System.in);
while(!keyboard.next().equals("abc"))
{
writer.write(keyboard.next());
writer.newLine();
}
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

try {
BufferedWriter writer = new BufferedWriter(new FileWriter("file1.txt", true));
Scanner keyboard = new Scanner(System.in);
writer.keyboard.nextLine(); // if need write 1st string alltime
while (keyboard.hasNext()){
String buffer = keyboard.nextLine();
if (!"abc".equals(buffer)) // !!! using equals on object not null ("abc" - is not null)
{
// do if entered "abc", use break for ending while
}
// do if entered others, use variable name buffer
}
} catch (IOException e) {
e.printStackTrace();
}

As #JonSkeet said - you're calling keyboard.next() twice instead of storing the result in a local variable like you should. Secondly you're comparing strings with the != operator, but this only checks whether you are pointing to the exact same String object. There may be thousands of String objects in memory with the string "abc" in them, and none of them would be equal to each other using ==.
Instead, you need to call the method equals.
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("file1.txt", true));
Scanner keyboard = new Scanner(System.in);
String next;
do {
next = keyboard.next();
writer.write(next);
writer.newLine();
} while (!next.equals("abc"));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}

Related

what method would I use to find space

im writing a program that subs out any spaces with hypens. The program compiles but it inserts a hyphen at the beginning of the program instead of every instance of a space the source code is as follows:
package Exercises;
import java.io.*;
import java.util.Scanner;
public class filehyphen {
public static void main(String[] args)
throws IOException{
DataOutputStream wr;
DataInputStream re;
Scanner type = new Scanner(System.in);
FileOutputStream text;
FileInputStream open;
String OgTxt;
try {
wr = new DataOutputStream(new FileOutputStream("random.txt"));
System.out.println(" Type whatever youd like");
OgTxt = type.nextLine();
wr.writeUTF(OgTxt);
System.out.println(" heres what you typed : " + OgTxt);
wr.close();
type.close();
}
catch(IOException exc) {
System.out.println("cannot write to this file");
}
System.out.println("heres what the text would be with spaces as hyphens");
try {
re = new DataInputStream(new FileInputStream("random.txt"));
OgTxt = re.readUTF();
if(OgTxt.contains(" ")) {
System.out.print("'");
System.out.println(OgTxt);
re.close();
}
}
catch(IOException exc) {
System.out.println("Read error");
}
I think it has something to with the contains method but im not sure. Answers appreciated. Thanks you!!
I have provided the Main method below for your solution.
public static void main(String[] args) throws IOException{
DataOutputStream wr;
DataInputStream re;
Scanner type = new Scanner(System.in);
FileOutputStream text;
FileInputStream open;
String OgTxt;
try {
wr = new DataOutputStream(new FileOutputStream("random.txt"));
System.out.println("Type whatever youd like");
OgTxt = type.nextLine();
wr.writeUTF(OgTxt);
System.out.println("heres what you typed : " + OgTxt);
wr.close();
type.close();
}
catch(IOException exc) {
System.out.println("cannot write to this file");
}
System.out.println("heres what the text would be with spaces as hyphens");
try {
re = new DataInputStream(new FileInputStream("random.txt"));
OgTxt = re.readUTF();
String replacedString = OgTxt.replace(" ", "-");
System.out.println(replacedString);
re.close();
}
catch(IOException exc) {
System.out.println("Read error");
}
}
I removed the if statement in your second try...catch block and made use of the replace method provided natively by the String class.
In your post you say that spaces should be replaced by hyphens, however you are trying to replace spaces with single quotation marks. Assuming you meant hyphens I corrected that.

Writing to files issue

So this may or may not be a dumb question but here we go!
So I'm trying to write to a file and it doesn't override but it writes over and over again so I need help.
Method:
#SuppressWarnings("resource")
public static void writeFile(File file, String index) {
try {
boolean wri = false;
PrintWriter out = new PrintWriter(new FileWriter(file, true));
Scanner scanner = new Scanner(file);
while(scanner.hasNext()) {
String str = scanner.nextLine();
if(str.equals(index)) {
System.out.println(index);
scanner.close();
wri = true;
break;
} else {
wri = false;
break;
}
}
if(wri != false)
return;
out.write(index);
out.write("\n");
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
You code is full of errors.
Don't use hasNext() with nextLine(). Use hasNextLine() instead.
You don't close scanner if index is not found.
You don't close out if index is found.
You open file for writing, even if you don't need to write anything.
You ignore exceptions.
if(wri != false) is a very obscure way to write if (wri).
No need to wrap FileWriter in a PrintWriter if you're only using write() method.
Since you explicitly call FileWriter constructor in append mode, I'd assume you want to write index to file, if and only if file doesn't already contain that text.
Please be aware that your logic will not work if index contains line break characters.
Since you're only reading lines, you should use BufferedReader instead of Scanner, since Scanner has a very large overhead.
As for your lack of closing the resources, use try-with-resources.
Your code should be like this:
public static void writeFile(File file, String index) {
if (file.exists()) {
try (BufferedReader in = new BufferedReader(new FileReader(file))) {
for (String line; (line = in.readLine()) != null; )
if (line.equals(index))
return;
} catch (Exception e) {
throw new RuntimeException("Error reading file: " + file, e);
}
}
try (FileWriter out = new FileWriter(file, true)) {
out.write(index);
out.write(System.lineSeparator());
} catch (Exception e) {
throw new RuntimeException("Error appending to file: " + file, e);
}
}
Test
File file = new File("C:/temp/test.txt");
writeFile(file, "Hello");
writeFile(file, "World");
writeFile(file, "Hello");
File Content
Hello
World
try with false
PrintWriter out = new PrintWriter(new FileWriter(file, false));

Java - How to remove blank lines from a text file

I want to be able to remove blank lines from a text file, for example:
Average Monthly Disposable Salary
1
Switzerland
$6,301.73
2014
2
Luxembourg
$4,479.80
2014
3
Zambia
$4,330.98
2014
--To This:
Average Monthly Disposable Salary
1
Switzerland
$6,301.73
2014
2
Luxembourg
$4,479.80
2014
3
Zambia
$4,330.98
2014
All of the code I have is below:
public class Driver {
public static void main(String[] args)
throws Exception {
Scanner file = new Scanner(new File("src/data.txt"));
PrintWriter write = new PrintWriter("src/data.txt");
while(file.hasNext()) {
if (file.next().equals("")) {
continue;
} else {
write.write(file.next());
}
}
print.close();
file.close();
}
}
The problem is that the text file is empty once I go back and look at the file again.
Im not sure why this is acting this way since they all seem to be blank characters, \n showing line breaks
Your code was almost correct, but there were a few bugs:
You must use .nextLine() instead of .next()
You must write to a different file while reading the original one
Your print.close(); should be write.close();
You forgot to add a new line after each line written
You don't need the continue; instruction, since it's redundant.
public static void main(String[] args) {
Scanner file;
PrintWriter writer;
try {
file = new Scanner(new File("src/data.txt"));
writer = new PrintWriter("src/data2.txt");
while (file.hasNext()) {
String line = file.nextLine();
if (!line.isEmpty()) {
writer.write(line);
writer.write("\n");
}
}
file.close();
writer.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
If you want to keep the original name, you can do something like:
File file1 = new File("src/data.txt");
File file2 = new File("src/data2.txt");
file1.delete();
file2.renameTo(file1);
Try org.apache.commons.io and Iterator
try
{
String name = "src/data.txt";
List<String> lines = FileUtils.readLines(new File(name));
Iterator<String> i = lines.iterator();
while (i.hasNext())
{
String line = i.next();
if (line.trim().isEmpty())
i.remove();
}
FileUtils.writeLines(new File(name), lines);
}
catch (IOException e)
{
e.printStackTrace();
}
You could copy to a temporary file and rename it.
String name = "src/data.txt";
try(BufferedWriter bw = new BufferedWriter(name+".tmp)) {
Files.lines(Paths.get(name))
.filter(v -> !v.trim().isEmpty())
.forEach(bw::println);
}
new File(name+".tmp").renameTo(new File(name));
This piece of code solved this problem for me
package linedeleter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class LineDeleter {
public static void main(String[] args) throws FileNotFoundException, IOException {
File oldFile = new File("src/data.txt"); //Declares file variable for location of file
Scanner deleter = new Scanner(oldFile); //Delcares scanner to read file
String nonBlankData = ""; //Empty string to store nonblankdata
while (deleter.hasNextLine()) { //while there are still lines to be read
String currentLine = deleter.nextLine(); //Scanner gets the currentline, stories it as a string
if (!currentLine.isBlank()) { //If the line isn't blank
nonBlankData += currentLine + System.lineSeparator(); //adds it to nonblankdata
}
}
PrintWriter writer = new PrintWriter(new FileWriter("src/data.txt"));
//PrintWriter and FileWriter are declared,
//this part of the code is when the updated file is made,
//so it should always be at the end when the other parts of the
//program have finished reading the file
writer.print(nonBlankData); //print the nonBlankData to the file
writer.close(); //Close the writer
}
}
As mentioned in the comments, of the code block, your sample had the print writer declared after your scanner meaning that the program had already overwritten your current file of the same name. Therefore there was no code for your scanner to read and thus, the program gave you a blank file
the
System.lineSeparator()
Just adds an extra space, this doesn't stop the program from continuing to write on that space, however, so it's all good

input values to console from a text file instead of manually entering the value

I have a program Main.java:
public class Main {
public static void main() throws FileNotFoundException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter no: \t");
int sq=0;
try {
sq=Integer.parseInt(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(sq*sq);
}
}
I am not supposed to edit the above code(Main.java) and I should execute this program from another java program. So, I figured out the following code:
public class CAR {
public static void main(String[] args) {
try {
Class class1 = Class.forName("executor.Main"); // executor is the directory in which the files Main.java and CAR.java are placed
Object object = class1.newInstance();
Method method = class1.getMethod("main", null);
method.invoke(object, null);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
By running CAR.java, the following is the output:
Enter no:
2 // this is the number I entered through the console
square is: 4
This works fine.But now, I need to input value to "sq" (variable in Main.java) not from the console but from a text file using the program CAR.java without editing Main.java. And I couldn't figure out how to do this with out editing the Main.java.
For example, If chech.txt has content as: 10 100.
Then, by running CAR.java I should read the value 10 and give it to the waiting console to be asigned to the values of "sq" and compare the output printed on the console with 100.
And print the output of the CAR.java as "Test passed".
Please suggest a solution for this.
The following code snippet could be added to CAR.java to read values from a file:
File f = new File("check.txt");
BufferedReader bf = new BufferedReader(new FileReader(f));
String r = bf.readLine();
String[] r1 = r.split(" ");
System.out.println("Input= " + r1[0] + " Output= " + r1[1]);
System.setIn() did the magic...
It specifies the jvm, to change the way of taking inputs from "System.in". Example:
System.setIn(new FileInputStream("chech.txt"));
This takes the input from "check.txt" instead of waiting for input from the console. Example program:
public class systemSetInExample {
public static void main(String[] args) {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter input: ");
String st=br.readLine(); // takes input from console
System.out.println("Entered: "+st);
System.setIn(new FileInputStream("test.txt"));
br=new BufferedReader(new InputStreamReader(System.in));
st=br.readLine(); // takes input from file- "test.txt"
System.out.println("Read from file: "+st);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Passing FileWriter as a parameter to a method

I'm sure there is a fairly simple answer to this question, so here we go.
I'm trying to use a FileWriter to write text to a file. My program reads text in from an already existing file, specified by the user and then asks whether to print the text to the console or to a new file, also to be named by the user.
I believe my problem is with passing the FileWriter to the "FileOrConsole" method. Am I not passing or declaring the FileWriter in the "FileOrConsole" method correctly? The file is always created but nothing is written to it.
Here is the code:
import java.io.*;
import java.util.*;
public class Reader {
public static void main(String[] args) throws IOException {
Scanner s = null, input = new Scanner(System.in);
BufferedWriter out = null;
try {
System.out.println("Would you like to read from a file?");
String answer = input.nextLine();
while (answer.startsWith("y")) {
System.out.println("What file would you like to read from?");
String file = input.nextLine();
s = new Scanner(new BufferedReader(new FileReader(file)));
System.out
.println("Would you like to print file output to console or file?");
FileOrConsole(input.nextLine(), s, input, out);
System.out
.println("\nWould you like to read from the file again?");
answer = input.nextLine();
}
if (!answer.equalsIgnoreCase("yes")) {
System.out.println("Goodbye!");
}
} catch (IOException e) {
System.out.println("ERROR! File not found!");
// e.printStackTrace();
} finally {
if (s != null) {
s.close();
}
if (out != null) {
out.close();
}
}
}
public static void FileOrConsole(String response, Scanner s, Scanner input,
BufferedWriter out) {
if (response.equalsIgnoreCase("console")) {
while (s.hasNext()) {
System.out.println(s.nextLine());
}
} else if (response.equalsIgnoreCase("file")) {
System.out.println("Name of output file?");
response = input.nextLine();
try {
out = new BufferedWriter(new FileWriter(response));
} catch (IOException e) {
e.printStackTrace();
}
while (s.hasNext()) {
try {
out.write(s.nextLine());
out.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Sorry, invalid response. File or console?");
response = input.nextLine();
FileOrConsole(response, s, input, out);
}
}
}
you make classic error forgetting that parameters passed by value in case of java it is a value of the reference. The thing is that your assignment
out = new BufferedWriter(new FileWriter(response));
actually does not change the variable declared in main() it stays null
BufferedWriter out = null;
and then in finally it skips the close() by the if(out==null)
and as it is Buffered and you do no flush nothing is written to file.
what you got to do is out.close(); in side the FileOrConsole method call
OR
do the out = new BufferedWriter(new FileWriter(response));
outside of it. You choose :-)
Try flushing your stream, but more importantly, remember to close it.
Here's a code example of recommended practice for handling streams. Same approach can be used for input streams too and things like database code where it's important to always clean up after yourself to get the expected results.
BufferedWriter out = null;
try {
out = // ... create your writer
// ... use your writer
} catch(IOException ex) {
// maybe there was a problem creating or using the writer
} finally {
if (null != out) {
out.flush();
out.close();
out = null;
}
}

Categories