I've been doing some exercises from my study book, and I can't seem to figure out this specific one. The instructions are: repeat Exercise P7.2, but allow the user to specify the file name on the command line. If the user does not specify any file name, then prompt the user for the name.
Ín P7.2, which I've completed, we were supposed to write a program that reads a file containing text, read each line and send it to the output file, preceded by line numbers. Basically, what I'm wondering is what I'm supposed to do exactly?
This is my code right now:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter name of file for reading: ");
String fileNameReading = input.next();
System.out.print("Enter name of file for writing: ");
String fileNameWriting = input.next(); om
input.close();
File fileReading = new File(fileNameReading);
Scanner in = null;
File fileWriting = new File(fileNameWriting);
PrintWriter out = null;
try {
in = new Scanner(fileReading);
out = new PrintWriter(fileWriting); fileWriting
} catch (FileNotFoundException e1) {
System.out.println("Files are not found!");
}
int lineNumber = 1;
while (in.hasNextLine()) {
String line = in.nextLine();
out.write(String.format("/* %d */ %s%n", lineNumber, line));
lineNumber++;
}
out.close();
in.close();
System.out.println();
System.out.println("Filen was read and re-written!");
}
I think your exercise just requires a small refactor to use the command line arguments to specify the file for reading:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String fileNameReading;
// check if input file were passed as a parameter
if (args != null && args.length > 0) {
fileNameReading = args[0];
}
// if not, then prompt the user for the input filename
else {
System.out.print("Enter name of file for reading: ");
fileNameReading = input.next();
}
System.out.print("Enter name of file for writing: ");
String fileNameWriting = input.next();
// rest of your code as is
}
You would run your code, for example, as:
java YourClass input.txt
Here we pass in the name of the input file as a parameter.
Related
I'm trying to read a text file for usernames and passwords for a final project. I can get the scanner to read one line, but only one line. I also need to be able to pass the username information along to print a file base on a role contained in the credentials file. Currently, it will only validate the line by line. If I enter the username and password correctly from the first line of the credentials file, it works as expected. If I enter it incorrectly, it will only accept the username and password from the second line of the credentials file.
My question is how do I parse the credentials file properly to search the entire file, not just an individual line.
I do not need to worry about the hash, only the password which is in parenthesis. I also must then print another text file which references the fourth item in each line, but I haven't gotten that far yet.. Any help would be most appreciated.
Text File:
griffin.keyes 108de81c31bf9c622f76876b74e9285f "alphabet soup" zookeeper
rosario.dawson 3e34baa4ee2ff767af8c120a496742b5 "animal doctor" admin
bernie.gorilla a584efafa8f9ea7fe5cf18442f32b07b "secret password" veterinarian
donald.monkey 17b1b7d8a706696ed220bc414f729ad3 "M0nk3y business" zookeeper
jerome.grizzlybear 3adea92111e6307f8f2aae4721e77900 "grizzly1234" veterinarian
bruce.grizzlybear 0d107d09f5bbe40cade3de5c71e9e9b7 "letmein" admin
My code:
public static void main(String[] args)throws FileNotFoundException {
File file = new File ("C:\\Users\\Rick\\Documents\\NetBeansProjects\\IT145finalproject4\\src\\it145finalproject4\\credentials.txt");
String passWord;
String userName;
Scanner scnr = new Scanner (file);
Scanner sc = new Scanner (System.in);
while(scnr.hasNextLine()){
int attempts = 0;
for (int i = 0; i < 3; i++) {
String line = scnr.nextLine();
System.out.println("Enter a username:" );
userName = sc.nextLine();
System.out.println("Enter a password:");
passWord = sc.nextLine();
if(line.contains(userName) && (line.contains (passWord))){
return;
}
if (!line.contains(userName) && (!line.contains (passWord))){
System.out.println("Please try again.");
}
attempts++;
if (attempts == 3){
System.out.println("Maximum attempts reached program exiting.");
}
}
}
}
I believe this amendment fixes the issues you were describing:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class TestClass
{
public static void main(String[] args) throws FileNotFoundException
{
File file = new File ("C:\\Users\\Mel\\Documents\\test.txt");
String passWord = "";
String userName = "";
Scanner scnr = new Scanner (file);
Scanner sc = new Scanner (System.in);
int attempts = 0, numLines = 0, count = 0;
//Get the number of lines in the file
while(scnr.hasNext())
{
numLines++;
scnr.nextLine();
}
//Reset the scanner
scnr.close();
scnr = new Scanner(file);
while(scnr.hasNextLine())
{
count++;
String line = scnr.nextLine();
//only run this code once per file iteration (at the start)
if (count == 1)
{
System.out.println("Enter a username:" );
userName = sc.nextLine();
System.out.println("Enter a password:");
passWord = sc.nextLine();
}
if(line.contains(userName) && (line.contains (passWord))){
return; //success!
}
//only execute this code once the entire file has been scanned!
if (count == numLines)
{
attempts++;
if (attempts == 3){
System.out.println("Maximum attempts reached program exiting.");
return;
}
if (!line.contains(userName) || (!line.contains (passWord))){
System.out.println("Please try again.");
//reset scanner!
scnr.close();
scnr = new Scanner(file);
count = 0;
}
}
}
}
}
I'm not sure if this is the best solution but I think it is an improvement. Mainly your issue was in not resetting the scanner, but also in calling the input methods too frequently. You will see that the number of lines are initially calculated to help determine when certain code should be called.
I also removed the for loop as it appeared to have no bearing on the code.
I am attempting to write a program that will take user input ( a long message of characters), store the message and search a text file to see if those words occur in the text file. The problem I am having is that I am only ever able to read in the first string of the message and compare it to the text file. For instance if I type in "learning"; a word in the text file, I will get a result showing that is is found in the file. However if I type "learning is" It will still only return learning as a word found in the file even though "is" is also a word in the text file. My program seems to not be able to read past the blank space. So I suppose my questions is, how do I augment my program to do this and read every word in the file? Would it also be possible for my program to read every word, with or without spaces, in the original message taken from the user, and compare that to the text file?
Thank you
import java.io.*;
import java.util.Scanner;
public class Affine_English2
{
public static void main(String[] args) throws IOException
{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.next();
Scanner file = new Scanner(new File("example.txt"));
while(file.hasNextLine())
{
String line = file.nextLine();
for(int i = 0; i < message.length(); i++)
{
if(line.indexOf(message) != -1)
{
System.out.println(message + " is an English word ");
break;
}
}
}
}
}
I recommend you first process the file and build a set of legal English words:
public static void main(String[] args) throws IOException {
Set<String> legalEnglishWords = new HashSet<String>();
Scanner file = new Scanner(new File("example.txt"));
while (file.hasNextLine()) {
String line = file.nextLine();
for (String word : line.split(" ")) {
legalEnglishWords.add(word);
}
}
file.close();
Next, get input from the user:
Scanner input = new Scanner(System.in);
System.out.println("Please enter in a message: ");
String message = input.nextLine();
input.close();
Finally, split the user's input to tokens and check each one if it is a legal word:
for (String userToken : message.split(" ")) {
if (legalEnglishWords.contains(userToken)) {
System.out.println(userToken + " is an English word ");
}
}
}
}
You may try with this. With this solution you can find each word entered by the user in your example.txt file:
public static void main(String[] args) throws IOException
{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.nextLine();
Scanner file = new Scanner(new File("example.txt"));
while (file.hasNextLine())
{
String line = file.nextLine();
for (String word : message.split(" "))
{
if (line.contains(word))
{
System.out.println(word + " is an English word ");
}
}
}
}
As Mark pointed out in the comment, change
scan.next();
To:
scan.nextLine();
should work, i tried and works for me.
If you can use Java 8 and Streams API
public static void main(String[] args) throws Exception{ // You need to handle this exception
String message = "";
Scanner input = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = input.nextLine();
List<String> messageParts = Arrays.stream(message.split(" ")).collect(Collectors.toList());
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
reader.lines()
.filter( line -> !messageParts.contains(line))
.forEach(System.out::println);
}
You have many solution, but when it comes to find matches I suggest you to take a look to the Pattern and Matcher and use Regular Expression
I haven't fully understood your question, but you could do add something like this (I did not tested the code but the idea should work fine):
public static void main(String[] args) throws IOException{
String message = "";
String name = "";
Scanner input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
System.out.println("Please enter in a message: ");
message = scan.next();
Scanner file = new Scanner(new File("example.txt"));
String pattern = "";
for(String word : input.split(" ")){
pattern += "(\\b" + word + "\\b)";
}
Pattern r = Pattern.compile(pattern);
while(file.hasNextLine())
{
String line = file.nextLine();
Matcher m = r.matcher(line);
if(m.matches()) {
System.out.println("Word found in: " + line);
}
}
}
Okay, so i have an issue trying to update a line or sentence in a text file.
The way my program works is this: If a user enters a question the program searches the text file for that exact question(lets say is n). The answer to the question would be on the following line(n + 1). My issue is trying to update the following line(n + 1) to some new line entered by the user.
I keep getting a Exception in thread "main" java.util.NoSuchElementException: No line found when i try to update the line in the text file. my removedata() is where i am trying to update the line of text.
Here is my code
public static void removedata(String s) throws IOException {
File f = new File("data.txt");
File f1 = new File("data2.txt");
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
BufferedReader br = new BufferedReader(new FileReader(f));
PrintWriter pr = new PrintWriter(f1);
String line;
while ((line = br.readLine()) != null) {
if (line.contains(s)) {
System.out.println("Enter new Text :");
String newText = input.readLine();
line = newText;
System.out.println("Thank you, Have a good Day!");
}
pr.println(line);
}
br.close();
pr.close();
input.close();
Files.move(f1.toPath(), f.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
public static void parseFile(String s) throws IOException {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
Scanner forget = new Scanner(System.in);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
System.out.println(scanner.nextLine());
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(scanner.nextLine()); // NoSuchElementException
// error
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
}
}
}
public static void getinput() throws IOException {
Scanner scanner = new Scanner(System.in);
String input = null;
/* End Initialization */
System.out.println("Welcome ");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
parseFile(input);
}
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
getinput();
}
My text file is :
what is the textbook name?
the textbook name is Java
how is the major?
the major is difficult
how much did the shoes cost?
the shoes cost ten dollars
Can someone help me solve this issue?
Change the code in the if block in parsefile to
String temp = scanner.nextLine();
System.out.println(temp);
System.out
.println(" Would you like to update this information ? ");
String yellow = forget.nextLine();
if (yellow.equals("yes")) {
removedata(temp); // NoSuchElementException
// error
} else if (yellow.equals("no")) {
System.out.println("Have a good day");
// break;
}
for an explanation why this works, look at Nick L.s answer.
The problem is here:
while (scanner.hasNextLine()) { //(1)
final String lineFromFile = scanner.nextLine(); //(2)
if (lineFromFile.contains(s)) { //(3)
System.out.println(scanner.nextLine()); //(4)
//....
String yellow = forget.nextLine(); //(5)
if (yellow.equals("yes")) {
removedata(scanner.nextLine()); //(6)
}
}
//....
}
First of all, you are correctly iterating the scanner lines checking whether there is a line (1). Now, you are getting the first line of the scanner on (2), but if the condition (3) succeeds, you are retrieving the next line again at (4) inside System.out.println(....). Same thing applies to (5) and (6) accordingly.
Now, imagine that you have reached the end of file at (2) and the condition at (3) succeeds. You will receive an exception of no such line, as you logically have. The same can happen at (5) and (6).
Each call of the nextLine(), will get the next line of the file opened on the stream.
I suggest that you do one readline inside the loop, then apply the received string when needed.
I want my program to display the contents of the file the user inputs with each line preceded with a line number followed by a colon. The line numbering should start at 1.
This is my program so far:
import java.util.*;
import java.io.*;
public class USERTEST {
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a file name: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
String line = inputFile.nextLine();
while (inputFile.hasNext()){
String name = inputFile.nextLine();
System.out.println(name);
}
inputFile.close();
}
}
I can display the contents of the file so far, but I don't know how to display the contents with the line numbers.
Integer i = 0;
while (inputFile.hasNext()) {
i++;
String line = inputFile.nextLine();
System.out.println(i.toString() + ": " + line);
}
You just need to concat an index to your output string.
int i=1;
while (inputFile.hasNext()){
String name = inputFile.nextLine();
System.out.println(i+ ","+name);
i++;
}
int lineNumber=0;
while (inputFile.hasNext()){
String name = inputFile.nextLine();
`System.out.println(lineNumber+ ":"+name);`
linenumber++;
}
Use an int initialized to 1 and increment it every time you read a line, then just output it before the line contents.
What about creating a numerical counter (increased every time you read a line) ... and putting that in front of the string that you are printing?
hi I have this Java code,
import java.io.*;
import java.util.*;
public class SongWriter
{
public static void main(String[] args)
{
PrintWriter outputStream = null; // Scope must be outside the try/catch structure
try
{
outputStream = new PrintWriter("Song.txt"); // new
FileOutputStream("Song.txt")
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file Song.txt.");
System.exit(0);
}
System.out.println("\n classical songs has many lines");
System.out.println("\nNow enter the three lines of your Song.");
String line = null;
Scanner keyboard = new Scanner(System.in);
int count;
for (count = 1; count <= 3; count++)
{
System.out.println("\nEnter line " + count + ": ");
line = keyboard.nextLine();
outputStream.println(count + "\t" + line);
}
outputStream.close();
System.out.println("\nYour Song has been written to the file Song.txt.\n");
} // end of main
} // end of class
how do I Adjust the program so it first asks for a name of the file to write to. Use the Scanner class and its next() method. Read in the file name as a string variable after informing the reader the file name should end in the suffix .txt
Eg:- Song with the file names Haiku1.txt, Haiku2.txt and Haiku3.txt.
You almost had it.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter first file name:");
String first = keyboard.nextLine();
System.out.println("Enter second file name:");
String second = keyboard.nextLine();
System.out.println("Enter third file name:");
String third = keyboard.nextLine();
//and so on and continue whatever you want to do..
EDIT: After your comment.
First store the 3 lines in a StringBuilder and then ask for the file name to write. Now you have the lyrics and file name.
Using the Scanner class to get input from the user:
String fileName1;
Scanner keyboard = new Scanner(System.in); //creates Scanner object
System.out.print ("Enter the name of the file. The file should end in the suffix .txt") //prompt the user to enter the file name
fileName1 = keyboard.next(); //store the name of the file
You should do this before the try/catch block so that you can use the filename that the user entered instead hardcoding it (like you did here with song.txt).
You can prompt the user this way for as many file names as you need.