So I'm trying to create a program that takes input in the form of a First and Last Name and then printing it to a Output.txt file.
I'm sort of new to programming, and I think I'm derping on this.
I just keep getting an error on the last part of my program.
PrintInitials.java:21: error: <identifier> expected
} output.close();
^
1 error
Here's my Code
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.*;
public class PrintInitials
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String first; // first name
String last; // last name
System.out.print("Enter your first and last name separated by a space: ");
first = stdIn.next();
last = stdIn.next();
File file = new File("Output.txt");
FileWriter writer = new FileWriter(file, true);
PrintWriter output = new PrintWriter(writer);
output.print("Your initials are " + first.charAt(0) + last.charAt(0) + ".");
} output.close();
}
do it like this:
Scanner stdIn = new Scanner(System.in);
System.out.print("Enter your first and last name separated by a space: ");
String first = stdIn.next(); // first name
String last = stdIn.next(); // last name
stdIn.close();
try (FileWriter writer = new FileWriter(new File("Output.txt"), true); // autocloseable
PrintWriter output = new PrintWriter(writer)) { // autocloseable
output.print("Your initials are " + first.charAt(0) + last.charAt(0) + ".");
} catch (IOException e) {
e.printStackTrace();
}
The Writers will be closed automatically.
The problem is that before closing the stream, you are closing the method body. so the 'output.close();' is outside the method and into the class body.
Your new code should look like this:
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.*;
public class PrintInitials{
public static void main(String[] args){
try{
Scanner stdIn = new Scanner(System.in);
String first; // first name
String last; // last name
System.out.print("Enter your first and last name separated by a space: ");
first = stdIn.next();
last = stdIn.next();
File file = new File("Output.txt");
FileWriter writer = new FileWriter(file, true);
PrintWriter output = new PrintWriter(writer);
output.print("Your initials are " + first.charAt(0) + last.charAt(0) + ".");
output.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
If you havent already, have a look into Java Basic Syntax
and the docs of PrintWriter to check what exceptions are thrown by what method so you can either catch them and handle them like i did above, or just pass them on.
Also, using an IDE such as eclipse, will show you all syntax errors real-time as you code so you dont have to compile every time yourself to check if your syntax is correct. Also most IDE's often come with sugested solutions for perticular errors. Other than this, it will warn you about what method throws what exception so you can catch them.
try this
BufferedWriter br= new BufferedWriter(new FileWriter(file)){
br.write(first + " " + last);
}
Related
I have a program taking user input and setting students in a text file, I want to sort these students in separate text files using the grade average
import java.nio.file.*;
import java.io.*;
import static java.nio.file.StandardOpenOption.*;
import java.util.Scanner;
public class NewClass2
{
public static void main(String[] args)
{
String recOut = "";
String delimiter = ",";
Scanner input = new Scanner(System.in);
final int QUIT = 999;
NewClass1 student = new NewClass1();
try
{
System.out.println("Enter Student ID: ");
student.setStudentId(input.nextInt());
while(student.getStudentId() != QUIT)
{
System.out.println("Enter Student Last Name: ");
student.setLastName(input.next());
System.out.println("Enter Student First Name: ");
student.setFirstName(input.next());
System.out.println("Enter Student Grade Point: ");
student.setGradePoint(input.nextDouble());
if(student.getGradePoint()>=3.6)
{
Path fileOut = Paths.get("HonorsStudentList.txt");
OutputStream output = new BufferedOutputStream(Files.newOutputStream(fileOut, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
recOut = student.getStudentId() + delimiter + student.getLastName() + delimiter + student.getFirstName() + delimiter + student.getGradePoint();
writer.write(recOut, 0,recOut.length());
writer.newLine();
writer.close();
}
if(student.getGradePoint()<3.6 && student.getGradePoint()>=2.0)
{
Path fileOut = Paths.get("GoodStandingStudentList.txt");
OutputStream output = new BufferedOutputStream(Files.newOutputStream(fileOut, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
recOut = student.getStudentId() + delimiter + student.getLastName() + delimiter + student.getFirstName() + delimiter + student.getGradePoint();
writer.write(recOut, 0,recOut.length());
writer.newLine();
writer.close();
}
if(student.getGradePoint()<2.0)
{
Path fileOut = Paths.get("ProbationStudentList.txt");
OutputStream output = new BufferedOutputStream(Files.newOutputStream(fileOut, CREATE));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
recOut = student.getStudentId() + delimiter
+ student.getLastName() + delimiter
+ student.getFirstName() + delimiter
+ student.getGradePoint();
writer.write(recOut, 0,recOut.length());
writer.newLine();
writer.close();
}
System.out.println("Enter Student ID: ");
student.setStudentId(input.nextInt());
}
}
catch(Exception e)
{
System.out.println("<<Something bad happened!>>");
System.out.println(e.getMessage());
}
}
}
I've been experimenting with if statements but that's not working because I can't close the writer correctly causing it to only take in one line then stopping.
How do I do this correctly?
The problem is not with how you're closing the file but with how your opening the file. Every time you're opening the file you are creating a new file and writing one line, then closing it, which is overwriting the old file that existed before. What you want to do is create the file if it does not exist, but if it does exist append one line.
Simply change
Files.newOutputStream(fileOut, CREATE)
to
Files.newOutputStream(fileOut, CREATE, APPEND)
Alternatively, you could open/close the files outside the loop or use “try with resources” too.
Since these are only three files, it is probably the easiest to open all three writers at once at the start and keep them open until the end.
If you don't want to close the writers manually (ans at least java 7 or 8 i think), you can use a try-with-resources statement.
Btw you probably don't need to wrap the OutputStream in a BufferedOutputStream, since you already use a buffered writer.
Instead of writing each time in file why don't you try to make three lists(one for every grade range you need) and when you have no more students then write them to separate files.
Something like this:
List<Student> honorsStudent = new ArrayList<Student>();
List<Student> goodStandingStudent = new ArrayList<Student>();
List<Student> probationStudent = new ArrayList<Student>();
// ....
if (student.getGrade() >= 3.6) {
honorsStudent.add(student);
} else if (student.getGrade() >= 2) {
goodStandingStudent.add(student);
}
else {
probationStudent.add(student);
}
//while loop end
//write your files
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
For some reason I keep on getting the following error when I compile my code. I have the correct preprocessor directives (import statements), and no syntax errors but whenever I compile my code I am given
probably,your dateFile is empty which might be the reason for this exception
public int nextInt()
Scans the next token of the input as an int.
An invocation of this method of the form nextInt()
Returns:
the int scanned from the input
Throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
refer http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Reader
{
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException, IOException
{
File dateFile = new File("test.txt");
FileWriter fw = new FileWriter(dateFile);
BufferedWriter bw = new BufferedWriter(fw);
Scanner reader = new Scanner(dateFile);
try
{
// if file doesnt exists, then create it
if (!dateFile.exists())
{
dateFile.createNewFile();
bw.write("1");
bw.close();
System.out.println("Done");
}else
{
int duration;
String ans = JOptionPane.showInputDialog ("Enter the amount of problems per training session (with number in minutes):");
while(!ans.matches("[0-9]+"))
{
ans = JOptionPane.showInputDialog ("Please re-enter the amount of problems per training session (with number in minutes):" );
}
duration = Integer.parseInt(ans);
System.out.println(duration);
bw.write(""+duration);
bw.flush();
int numSessions = reader.nextInt();
System.out.println("Number of sessions is: " + numSessions);
String fileName = ("sessionNumber"+numSessions);
File newSession = new File(""+fileName+".txt");
System.out.println(fileName);
if (!newSession.exists())
{
newSession.createNewFile();
System.out.println("IT DOES NOT EXIST!");
}
fw = new FileWriter(newSession.getAbsoluteFile());
bw = new BufferedWriter(fw);
bw.write(duration);
bw.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Now it should work.
I add this two lines:
bw.write(""+duration);
bw.flush();
you were never write in the File.
Remember to .flush() your buffer.. if you want it to write on the file before you close it!
notice that i changed the path of the file to let it work on my pc so change it again
im studying for my programming final exam. I have to write a program which opens a file which is stored in the string fileName and look in the file for a String called personName and this should print the first string after personName then the program should terminate after printing it,
if the argument personName is not in the file then it should print "this name doen't exsit" then if an IOException occurs it should then print "there is an IO Error" and the program should exsit using system.exit(0)
the program should use the file info.txt and each line should contain two strings
first string name and second age.
everything must be in one method
data.txt contains
Max 60.0
joe 19.0
ali 20.0
my code for this so far is :
public class Files{
public void InfoReader(String fileName, String personName)
{
try{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C://rest//data.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//Read File Line By Line
while ((fileName = br.readLine()) != null) {
// Print the content on the console
(new Files()).infoReader("info.txt","Joe"); //this prints the age
}
//Close the input stream
in.close();
}
catch (IOException e)
{//Catch exception if any
System.out.println(" there is an IO Error");
System.exit(0);
}
}
catch (Exception e)
{//Catch exception if any
System.out.println("that name doesn't exists");
}
}
}
infoReader(info.txt,Joe); should print 19.0
But I am getting a java.lang.StackOverflowError
any help would be much appreciated!!
Thanks in advance!
This is what I think you are trying to do. And if doesn't, at least can work as an example. Just as amit mentions, your current error is because of the recursive call, which I think is not necessary.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Files {
public void InfoReader(String fileName, String personName) {
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(fileName);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
//Loop until there are no more lines in the file
while((line = br.readLine()) != null) {
//Split the line to get 'personaName' and 'age'.
String[] lineParts = line.split(" ");
//Compare this line personName with the one provided
if(lineParts[0].equals(personName)) {
//Print age
System.out.println(lineParts[1]);
br.close();
System.exit(0);
}
}
br.close();
//If we got here, it means that personName was not found in the file.
System.out.println("that name doesn't exists");
} catch (IOException e) {
System.out.println(" there is an IO Error");
}
}
}
If you use the Scanner class, it would make your life so much easier.
Scanner fileScanner = new Scanner (new File(fileName));
while(fileScanner.hasNextLine()
{
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
String name = lineScanner.next(); // gets the name
double age = Double.parseDouble(lineScanner.next()); // gets the age
// That's all really! Now do the rest!
}
Use commons-io and dont forget the encoding!
List<String> lines = FileUtils.readLines(file, encoding)
I was asked to write an assignment wherein the user would be prompted to input a key and/or a value.
So far, here is my code:
import java.util.Scanner;
import java.io.*;
class bTree
{
//Fields
static Scanner input = new Scanner(System.in);
static boolean done = false;
public static void main(String args[])throws Exception
{
FileWriter fWriter = new FileWriter("data.txt");
do
{
System.out.print("Enter command: ");
String enter[] = input.nextLine().split(" ", 3);
if(enter[0].toLowerCase().equals("insert"))
{
fWriter.write(enter[1] + "\n" + enter[2] + "\n");
fWriter.flush();
}
else if(enter[0].toLowerCase().equals("select"))
{
FileReader fReader = new FileReader("data.txt");
Scanner fileInput = new Scanner(fReader);
while(fileInput.hasNext() && done == false)
{
if(fileInput.nextLine().equals(enter[1]))
{
System.out.println(fileInput.nextLine());
done = true;
}
else
{
fileInput.nextLine();
}
}
done = false;
}
else if(enter[0].toLowerCase().equals("update"))
{
fWriter.write(enter[2]);
fWriter.flush();
}
else if(enter[0].toLowerCase().equals("exit"))
{
System.exit(0);
}
}
while(true);
}
}
Problem: When i open the data.txt, there are no spaces. So if i enter "insert 1001 gen" and "10001 genny", in notepad, it would come out as "1001gen10001genny". Any suggestions?
The problem is that notepad.exe is picky about line endings, and there are many possibilities. When you write "\n" to a FileWriter, it writes a single character, namely '\n'. But notepad expects the sequence "\r\n" instead. It shows a single "\n" as nothing.
Here is your code, slightly modified to work around some pitfalls.
package so7696816;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.Scanner;
public class Excercise {
public static void main(String args[]) throws Exception {
final Scanner input = new Scanner(System.in);
PrintWriter fWriter = new PrintWriter("data.txt");
while (true) {
System.out.print("Enter command: ");
String enter[] = input.nextLine().split(" ", 3);
final String command = enter[0].toLowerCase(Locale.ROOT);
if (command.equals("insert")) {
fWriter.println(enter[1]);
fWriter.println(enter[2]);
fWriter.flush();
} else if (command.equals("select")) {
FileReader fReader = new FileReader("data.txt");
Scanner fileInput = new Scanner(fReader);
while (fileInput.hasNextLine()) {
String key = fileInput.nextLine();
String value = fileInput.nextLine();
if (key.equals(enter[1])) {
System.out.println(value);
break;
}
}
fReader.close(); // don't leave files open
} else if (command.equals("update")) {
fWriter.write(enter[2]);
fWriter.flush();
} else if (command.equals("exit")) {
return;
} else {
System.err.println("Unknown command: " + command);
}
}
}
}
Remarks:
I used a PrintWriter instead of a FileWriter to get the line endings correct.
For the select command I closed the fReader after using it.
I avoided to type enter[0].toLowerCase() multiple times.
I used the proper variant of toLowerCase.
I added error handling for unknown commands.
I rewrote the select command to be a little more concise.
The problem is String enter[] = input.nextLine().split(" ", 3);, it kills the Spaces. So append a space after each array entry or write an additional " " everytime you use fWriter.write.
look here
As already stated the line feed character is incorrect for notepad. Alternatively you could wrap that FileWriter in a BufferedWriter and use the newLine method to always insert the correct line feed.
I think you are running your program in UNIX. In unix system "\r\n" is the line feed.
If you are running your program in Windows, I think the file should contain something like this.
1001
gen
10001
genny