I have a programming assignment for my Intro to Java Programming class and I am stuck with a couple of minor problems. Here is the assignment:
I am to write a program that accepts two inputs from the user: one will be the name of a .txt file, and the second input will be a whole number of type long. It will create a new File object with the file name inputted by the user, and then it will get a PrintWriter object by passing the File object to the PrintWriter constructor. If the file is found, it will read in the whole number.
It will then use a recursive method to reverse the number inputted by the user (for example, if the user entered a number 123456, it would reverse the number to 654321). It will then write that reversed number both to the .txt file and to the screen.
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
public class Prog2c
{
public static void main(String[] args)
{
File inputFile = null; // File object for user's file
Scanner fileReader = null; // reads user's file
PrintWriter fileWriter = null; // writes to user's file
Scanner scan = new Scanner(System.in);
String fileName = null;
long number = 0;
try
{
fileName = scan.nextLine();
number = scan.nextLong(); // reads the whole number from the user
inputFile = new File(fileName); // creates new File object with user's file
fileReader = new Scanner(inputFile); // reads contents of user's file
System.out.println("Program 2, Christopher Moussa, masc1754");
if (inputFile.exists())
{
System.out.println("The file " + fileName + " is ready for writing."); // throws FileNotFoundException if
fileWriter = new PrintWriter(inputFile);
number = reverseNumber(number);
fileWriter.println(number); // performs recursive method on number inputted by user
System.out.println("File " + inputFile + " exists? " + inputFile.exists()); // checks to see if file exists
while (fileReader.hasNextLong())
{
number = fileReader.nextLong();
System.out.println(number); // prints contents of the file
}
}
}
catch (FileNotFoundException exception) // in case the file is not found or does not exist
{
System.out.println("FileNotFoundException file was not found: " + exception.getMessage());
System.exit(0);
}
finally
{
if (null != fileReader)
{
scan.close(); // closes scanner
fileWriter.close();
}
}
}
public static long reverseNumber(long number) // Recursive Method
{
if (number < 10) // Base Case 1: In case the number
{ // is a single digit number, I will
System.out.println(number); // just return the number
return number;
}
else // Recursion: This will take the
{ // remainder of the original number
System.out.print(number % 10); // and print it. It will then divide
reverseNumber(number/10); // the number by 10 to truncate it by
return number; // one digit. It will then return the value.
}
}
}
Here are my problems:
When I run the program, the number that is written to the .txt file is the original number that I inputted, not the number reversed (the reversed number is what should be written to the .txt file). It is also not printing out the content of the .txt file (the reversed number) to the screen, even though I have a scanner which should read the contents of the file and print the number to the screen (which is the function of the while statement in my program, right?). My idea as to why the PrintWriter is not writing the reversed number into the .txt file is because you cannot assign the result of a method to a variable? I am not completely sure. Any advice/suggestions as to how to write the reversed number into the .txt file and then print the content of that .txt file (which only has the reversed number) to the screen would be much appreciated, thank you.
You're reading from the file, while editing it. First, finish writing the number to file, then close to writer. Next open the reader.
Related
I can't get my scanner to read in the integer from a text file.
The file looks something like this (a matrix size followed by a matrix)
3
0 1 1
1 1 1
1 0 0
These two methods belong to ReadMatrix
public void openFile() {
try {
scanner = new Scanner(System.in); // create a scanner object
System.out.println("File to read: ");
fileName = scanner.nextLine(); // get name of file
System.out.println("File " + fileName + " is opened.");
br = new BufferedReader(new FileReader(fileName));
} catch (Exception e) {
System.out.println("can't find the funky file");
}
}
public int readInteger() {
sc = new Scanner(System.in);
// while(sc.hasNextInt()){
// sc.nextLine();
anInt = sc.nextInt();
System.out.println("Trying to read integerrrrrr help");
// }
return anInt;
}
Here are 2 classes
public class MainMethodHere {
public static void main(String[] args) {
// TODO Auto-generated method stub
RunMainMethod running = new RunMainMethod();
}
}
public class RunMainMethod {
ReadMatrix a = new ReadMatrix();
public RunMainMethod(){
a.openFile();
a.createFile();
System.out.println("just createdFile"); //<--- this is where the program ends
a.readInteger();
System.out.println("just readInteger");
a.helpMeWrite();
System.out.println("Just write sample ");
a.closeResources();
}
}
Writing to the file works fine, but I can't get the program to read the given text file to start the manipulation.
I tried finding the solutions in a few SO posts: how to read Integer from a text file in Java
Reading numbers from a .txt file into a 2d array and print it on console
How to read integer values from text file
I also tried ReadFile() and WriteFile(), but when I try to track my code via printing into the console, my simple integers shows up as different values. Is that something related to bytes? So I try reverting back to using a scanner, but somehow it's not working. Please let me know if I should clarify something further. I am new to coding and SO.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This code is supposed to get N values from the user. Then input the values into a .txt file. I'm having trouble getting the values to show in the .txt file. Not sure why.
// This program writes data into a file.
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("namef.txt");
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
PrintWriter outputfile = new PrintWriter("/Users/******/Desktop/namef.txt");
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for ( int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
input.nextInt();
outputfile.print(N);
}
System.out.println("Data entered into the file.");
inputFile.close(); // Close the file.
}
} // End of class
In your program you seemed to have thrown everything and hoping that it works. To find out what class you should use you should search it in Javadoc of you Java version.
Javadoc of Java 12
PrintWriter:
Prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.
FileWriter:
Writes text to character files using a default buffer size. Encoding from characters to bytes uses either a specified charset or the platform's default charset.
Scanner (File source):
Constructs a new Scanner that produces values scanned from the specified file. Bytes from the file are converted into characters using the underlying platform's default charset.
Now you can see what each class is for. Both PrintWriter and FileWriter are used to write file however PrintWriter offer more formatting options and Scanner(File source) is for reading files not writing files.
Since there is already an answer with PrintWriter. I am writing this using FileWriter.
public static void main(String[] args) throws Exception {
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
// You can provide file object or just file name either would work.
// If you are going for file name there is no need to create file object
FileWriter outputfile = new FileWriter("namef.txt");
System.out.print("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++) {
System.out.print("Enter the number into the file: ");
// Writing the value that nextInt() returned.
// Doc: Scans the next token of the input as an int.
outputfile.write(Integer.toString(input.nextInt()) + "\n");
}
System.out.println("Data entered into the file.");
input.close();
outputfile.close(); // Close the file.
}
Output:
Enter the number of data (N) you want to store in the file: 2
Enter 2 numbers below:
Enter the number into the file: 2
Enter the number into the file: 1
Data entered into the file.
File:
2
1
Here's a working variant of what you want to achieve:
import java.io.*; // Needed for File I/O class.
import java.util.Scanner; // Needed for Scanner class.
public class program01
{
public static void main (String [] args) throws IOException
{
int fileName;
int num;
// Create a Scanner object for keyboard input.
Scanner input = new Scanner(System.in);
File fname = new File ("path/to/your/file/namef.txt");
PrintWriter outputfile = new PrintWriter(fname);
System.out.println("Enter the number of data (N) you want to store in the file: ");
int N = input.nextInt(); // numbers from the user through keyboard.
System.out.println("Enter " + N + " numbers below: ");
for (int i = 1; i <= N; i++)
{
// Enter the numbers into the file.
int tmp = input.nextInt();
outputfile.print(tmp);
}
System.out.println("Data entered into the file.");
outputfile.close(); // Close the file.
}
}
Several comments on above:
1) Got rid of redundant rows:
Scanner inputFile = new Scanner(fname); // Create a Scanner object for keyboard input.
FileWriter outFile = new FileWriter ("namef.txt", true);
You actually didn't use them at all.
2) In PrintWriter we pass File object, not String.
3) In for loop there was a logic mistake - on every iteration you should have written N instead of actual number which user entered on console.
4) Another mistake was in closing wrong file in the last line.
EDIT: adding according to comment.
in point 2) there's an alternative way - you can skip creating File object and pass as a String a path to even non-existing file directly in PrintWriter, like this:
PrintWriter outputfile = new PrintWriter("path/to/your/file/namef.txt");
I'm trying to read in a file and change some lines.
The instruction reads "invoking java Exercise12_11 John filename removes the string John from the specified file."
Here is the code I've written so far
import java.util.Scanner;
import java.io.*;
public class Exercise12_11 {
public static void main(String[] args) throws Exception{
System.out.println("Enter a String and the file name.");
if(args.length != 2) {
System.out.println("Input invalid. Example: John filename");
System.exit(1);
}
//check if file exists, if it doesn't exit program
File file = new File(args[1]);
if(!file.exists()) {
System.out.println("The file " + args[1] + " does not exist");
System.exit(2);
}
/*okay so, I need to remove all instances of the string from the file.
* replacing with "" would technically remove the string
*/
try (//read in the file
Scanner in = new Scanner(file);) {
while(in.hasNext()) {
String newLine = in.nextLine();
newLine = newLine.replaceAll(args[0], "");
}
}
}
}
I don't quite know if I'm headed in the correct direction because I'm having some issue getting the command line to work with me. I only want to know if this is heading in the correct direction.
Is this actually changing the lines in the current file, or will I need different file to make alterations? Can I just wrap this in a PrintWriter to output?
Edit: Took out some unnecessary information to focus the question. Someone commented that the file wouldn't be getting edited. Does that mean I need to use PrintWriter. Can I just create a file to do so? Meaning I don't take a file from user?
Your code is only reading file and save lines into memory. You will need to store all modified contents and then re-write it back to the file.
Also, if you need to keep newline character \n to maintain format when re-write back to the file, make sure to include it.
There are many ways to solve this, and this is one of them. It's not perfect, but it works for your problem. You can get some ideas or directions out of it.
List<String> lines = new ArrayList<>();
try {
Scanner in = new Scanner(file);
while(in.hasNext()) {
String newLine = in.nextLine();
lines.add(newLine.replaceAll(args[0], "") + "\n"); // <-- save new-line character
}
in.close();
// save all new lines to input file
FileWriter fileWriter = new FileWriter(args[1]);
PrintWriter printWriter = new PrintWriter(fileWriter);
lines.forEach(printWriter::print);
printWriter.close();
} catch (IOException ioEx) {
System.err.println("Error: " + ioEx.getMessage());
}
I am working on a program that involves me having to search a specific line in a .txt file and convert the string inside of it into something else.
For example, the string is actually made of numbers which I suppose I can convert into ints. The main thing is that for example, on line 2, there are 5 digits for zip code stored. I need to convert that into certain outputs, depending on the numbers. In other words, I need variables from digits 0-9 and depending on each digit, output a specific output.
Right now here is the code I have to prompt the user for information that is stored in the file, and can read and print all of the information that was just typed, but I'm unsure how to go about the rest.
import java.io.*;
import java.util.*;
import java.io.FileReader;
import java.io.IOException;
public class ObjectTest2 {
public static void main(String [] args) throws FileNotFoundException, IOException {
// The name of the file to open.
String fileName = "information.txt";
Scanner myScanner = new Scanner(System.in);
try {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
// append a newline character.
//This shit here prompts the user for information and stores it in seperate lines to be
//called on by the later section.
System.out.print("What is your name? ");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your 5 digit zip code?");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your +4 digit zip? ");
bufferedWriter.write(myScanner.nextLine());
bufferedWriter.newLine();
System.out.print("What is your address? ");
bufferedWriter.write(myScanner.nextLine());
// Always close files.
bufferedWriter.close();
//reads the information file and prints what is typed
BufferedReader reader = new BufferedReader(new FileReader("information.txt")); {
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
System.out.println(line);
}
}
}
catch(IOException ex) {
System.out.println(
"Error writing to file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
You are left with no choice but to iterate over each line of the file and search for the String. If you want to get a line of string from the file based on line number, consider creating a method. If the operation is required to be performed several times on the same file and if the contents of the file do not change, use a map to cache the file contents based on the line number.
I am a noobie at programming and I can't seem to figure out what to do.
I am to write a Java program that reads in any number of lines from a file and generate a report with:
the count of the number of values read
the total sum
the average score (to 2 decimal places)
the maximum value along with the corresponding name.
the minimum value along with the corresponding name.
The input file looks like this:
55527 levaaj01
57508 levaaj02
58537 schrsd01
59552 waterj01
60552 boersm01
61552 kercvj01
62552 buttkp02
64552 duncdj01
65552 beingm01
I program runs fine, but when I add in
score = input.nextInt(); and
player = input.next();
The program stops working and the keyboard input seems to stop working for the filename.
I am trying to read each line with the int and name separately so that I can process the data and complete my assignment. I don't really know what to do next.
Here is my code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class Program1 {
private Scanner input = new Scanner(System.in);
private static int fileRead = 0;
private String fileName = "";
private int count = 0;
private int score = 0;
private String player = "";
public static void main(String[] args) {
Program1 p1 = new Program1();
p1.getFirstDecision();
p1.readIn();
}
public void getFirstDecision() { //*************************************
System.out.println("What is the name of the input file?");
fileName = input.nextLine(); // gcgc_dat.txt
}
public void readIn(){ //*********************************************
try {
FileReader fr = new FileReader(fileName + ".txt");
fileRead = 1;
BufferedReader br = new BufferedReader(fr);
String str;
int line = 0;
while((str = br.readLine()) != null){
score = input.nextInt();
player = input.next();
System.out.println(str);
line++;
score = score + score;
count++;
}
System.out.println(count);
System.out.println(score);
br.close();
}
catch (Exception ex){
System.out.println("There is no shop named: " + fileName);
}
}
}
The way you used BufferReader with Scanner is totally wrong .
Note: you can use BufferReader in Scanner constructor.
For example :
try( Scanner input = new Scanner( new BufferedReader(new FileReader("your file path goes here")))){
}catch(IOException e){
}
Note: your file reading process or other processes must be in try block because in catch block you cannot do anything because your connection is closed. It is called try catch block with resources.
Note:
A BufferedReader will create a buffer. This should result in faster
reading from the file. Why? Because the buffer gets filled with the
contents of the file. So, you put a bigger chunk of the file in RAM
(if you are dealing with small files, the buffer can contain the whole
file). Now if the Scanner wants to read two bytes, it can read two
bytes from the buffer, instead of having to ask for two bytes to the
hard drive.
Generally speaking, it is much faster to read 10 times 4096 bytes
instead of 4096 times 10 bytes.
Source BufferedReader in Scanner's constructor
Suggestion: you can just read each line of your file by using BufferReader and do your parsing by yourself, or you can use Scanner class that gives you ability to do parsing tokens.
difference between Scanner and BufferReader
As a hint you can use this sample for your parsing goal
Code:
String input = "Kick 20";
String[] inputSplited = input.split(" ");
System.out.println("My splited name is " + inputSplited[0]);
System.out.println("Next year I am " + (Integer.parseInt(inputSplited[1])+1));
Output:
My splited name is Kick
Next year I am 21
Hope you can fixed your program by given hints.