How to Use the Scanner class and its next() method in Java? - java

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.

Related

Command line arguments

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.

Why am I getting the output of zero when scanning the file for a word? [duplicate]

This question already has an answer here:
Scanner only reads file name and nothing else
(1 answer)
Closed 5 years ago.
I am trying to read a file inputted by the user then print the number of occurrences of a word also inputted by the user, even though there is multiple instances of a word I still get zero and I am unsure why.
try {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the filename: ");
String sfile = scan.next();
System.out.println("Please enter a word: ");
String wordname = scan.next();
FileReader fin = new FileReader(sfile);
Scanner scanner = new Scanner(sfile);
int count = 0;
while (scanner.hasNextLine()) {
String c = scanner.next();
if (c.equalsIgnoreCase(wordname)) {
count++;
}
} System.out.println(count);
scan.close();
fin.close();
scanner.close();
}
Pass the FileReader object into your Scanner, at the moment you're passing it a String
Scanner scanner = new Scanner(fin);
Also make sure that your file is in the root directory of your project.
Please enter the filename:
hi.txt
Please enter a word:
lol
2
File content:
lol
lol

Parsing an entire text file in Java

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.

How can I reloop this code?

My program requires the user to input a file name that they have in the working directory (which contains text) and then enter the output file name that is also already in the same directory. After that the user then must choose whether they want to Capitalize or lowercase all the text in the file.
Once they have chosen that they should be given the option to process another file. That's where I'm having trouble. After printing "Would you like to process another file? Y for Yes or N for No?" how do I Get it to loop back to the beginning?
Right now my code keeps looping back to the "Capitalize or lowercase all words" I need it to stop doing that and ask the user if they want to process another file, if so it needs to go back and ask the input and output file names again.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the input data file name:");
String fileInput = sc.next();
System.out.println("Please enter the output data file name:");
String fileOutput = sc.next();
while(true){
System.out.println("A: Capitalize all words.\nB: Lowercase all words.");
System.out.println("enter choice:");
char choice = sc.next().charAt(0);
if(choice == 'A'){
capitalize(fileInput, fileOutput);
}else{
lowercase(fileInput, fileOutput);
}
}
System.out.println("Process another file? Y for Yes or N for No");
}
You simply need to wrap all your code in the while loop, as follows; the while loop only repeats the code in it:
public static void main(String[] args) {
while (true) {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the input data file name:");
String fileInput = sc.next();
System.out.println("Please enter the output data file name:");
String fileOutput = sc.next();
System.out.println("A: Capitalize all words.\nB: Lowercase all words.");
System.out.println("enter choice:");
char choice = sc.next().charAt(0);
if (choice == 'A') {
capitalize(fileInput, fileOutput);
} else {
lowercase(fileInput, fileOutput);
}
System.out.println("Process another file? Y for Yes or N for No");
String processAnother = sc.next();
if (processAnother.equals("N") || processAnother.equals("n")) break;
}
}

How can I display file with line numbers in my Java program?

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?

Categories