Ask user for command including a filename confusion - java

In this part of my program I ask the user for a command and a filename. The command can be 'read', 'content' or 'count'. In all the different tasks I need a file. I want the user to type in the console something like:
read Alice's Adventures In Wonderland.txt
For some reason I don't get how to implement this in 1 command. Now, I'm first asking the filename and afterwards I ask what to do with it. The following example is the 'read' command which asks for a file and counts all the words in the file:
case "read":
int nrWords=countAllWords();
System.out.println("The number of words in this file is: "+nrWords+"\n");
break;
.
private static int countAllWords() throws IOException
{
Scanner input=new Scanner(System.in);
System.out.println("Please enter file name: ");
String fileName=input.nextLine();
FileInputStream inputStream=new FileInputStream(fileName);
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String line=bufferedReader.readLine();
int nrWords=0;
while(line!=null)
{
String[] wordsInLine=line.split(" ");
nrWords=nrWords+wordsInLine.length;
line=bufferedReader.readLine();
}
return nrWords;
}
Can somebody explain how I can fit those 2 commands into one senctence in which my code understands what relates to what?

Instead what you can do here is to use the split function to break apart your command like so:
String line = bufferedReader.readLine();
String command = line.split(" ")[0];
String fileName = line.substring(command.length);
And that way your fileName will be the rest of the String, and the command just the first element. command should be the command and fileName should be the file's name.

If you get the entire command in one input, you can parse out the first word -- understanding that this is the 'action' -- and then the rest is the filename.
So first you'd get the entire command:
Scanner input=new Scanner(System.in);
System.out.println("Please enter command: ");
String command = input.nextLine();
Then you'll want to parse out the action. It will always be the first word.
String action = command.substring(0, command.indexOf(' ')).trim();
String fileName = command.substring(command.indexOf(' ')).trim();
Now you can check what the action is and use the file as needed.
String's indexOf method will return the index of the first occurrance of the specified character. So in this case we're using it to get the index of the first space. Note that indexOf will return -1 if the character is not present, so you'll want to trap appropriately for that. (Example scenario: user just enters "read" without a filename.)

Related

Accept arbitrary multi-line input of String type and store it in a variable

Is there any possible way to accept a arbitrary(unknown) no. of input lines of string from the user until user explicitly enters -1 and store it in a string for further manipulation.
From what I gather, you're trying to get input from a user until that user types -1. If thats the case, please see my function below.
public static void main (String[] args)
{
// Scanner is used for I/O
Scanner input = new Scanner(System.in);
// Prompt user to enter text
System.out.println("Enter something ");
// Get input from scanner by using next()
String text = input.next();
// this variable is used to store all previous entries
String storage = "";
// While the user does not enter -1, keep receiving input
// Store user text into a running total variable (storage)
while (!text.equals("-1")) {
System.out.println("You entered: " + text);
text = input.next();
storage = storage + "\n" + text
}
}
I've left comments in that code block but I'll reiterate it here. First we declare our I/O object so that we can get input from the keyboard. We then ask the user to "Enter something" and wait for the user to enter something. This process is repeated in the while loop until the user specifically types -1.
Your question makes no sense... You're talking about taking input from a user, but also reaching the end of a file, implying you are taking reading input from a file. Which is it?
If you're trying to say that for each line in a file, the user must enter something for some action to be taken, then yes, that can be done.
I'll assume you already have a File object or String containing the file path, named file.
// make a stream for the file
BufferedReader fileReader = new BufferedReader(new FileReader(file));
// make a stream for the console
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.in));
// declare a String to store the file input
String fileInput;
// use a StringBuilder to construct the user input lines
StringBuilder inputLines = new StringBuilder();
// while there is a line to be read
while ((fileInput = fileReader.readLine()) != null) {
/*
** maybe some output here to instruct the user?
*/
// get some input from the user
String userInput = consoleReader.readLine();
// if the user wants to stop
if (userInput.equals("-1")) {
// exit the loop
break;
}
// else append the input
inputLines.append(userInput+"\r\n");
}
// close your streams
fileReader.close();
consoleReader.close();
// perform your further manipulation
doSomething(inputLines.toString());
Those classes are located in java.io.*. Also, remember to catch or have your method throw IOException.
If you want to perform your manipulation each time you have some input instead of doing it all at the end, get rid of the StringBuilder, and move doSomething(userInput) into the loop before the if statement.

Java: Skipping the first line of user input when appending a text file?

So I'm trying to accept lines of text from the user so that it can be appended to a txt file. However, after the program runs, the first line the user entered does not appear in the appended file.
Here is a portion of the code:
System.out.println("enter advice (hit return on empty line to quit):");
String advice = keyboard.nextLine();
FileWriter fw = new FileWriter(inputFile, true);
PrintWriter pw = new PrintWriter(fw);
for(int n = 1; n <= 2; ++n)
{
advice = keyboard.nextLine();
pw.print(advice);
}
pw.close();
keyboard.close();
Here is a sample run of the code:
$ java Advice
enter input filename: Advice.txt **enter**
1: fully understand the given problem
2: do analysis and design first before typing
enter advice (hit return on empty line to quit):
a **enter**
b **enter**
Thank you, goodbye!
$ cat Advice.txt
1: fully understand the given problem
2: do analysis and design first before typing
b
Any thoughts?
Thanks!
The first line the user enters is being captured but not being written to the file.
String advice = keyboard.nextLine();
When you write to the file you are taking in the next user input

Removing a specific line from file handling text file java

File RaptorsFile = new File("raptors.txt");
File tempFile = new File("raptorstemp.txt");
BufferedWriter output = new BufferedWriter (new FileWriter ("raptorstemp.txt"));
System.out.println("Please enter the following infomation");
System.out.println("Please enter the Player's Name");
String PlayerName=sc.nextLine();
System.out.println("Please enter the Player's FG%");
String FieldGoal=sc.nextLine();
System.out.println("Please enter the Player's 3P%");
String ThreePointer=sc.nextLine();
System.out.println("Please enter the Player's FT%");
String FreeThrow=sc.nextLine();
System.out.println("Please enter the Player's REB");
String Rebounds=sc.nextLine();
System.out.println("Please enter the Player's AST");
String Assists=sc.nextLine();
System.out.println("Please enter the Player's Points");
String Points=sc.nextLine();
String currentLine;
while((currentLine = Raptors.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(PlayerName+"," +FieldGoal+"," +ThreePointer+"," +FreeThrow+"," +Rebounds+"," +Assists+"," +Points)) continue;
output.write(currentLine + System.getProperty("line.separator"));
}
boolean successful = tempFile.renameTo(RaptorsFile);
output.close();
System.out.println("The CarsTemp file will have the new list");
options(Raptors,s);
I am having a problem i just want the user to input only player's name, for example if he inputs Kyle Lowry i want it to delete all of Kyle Lowry's stats. Below is sample of text field.
Lou Williams,41.1,36.3,87.6,60,53,508
Kyle Lowry,44.9,35.1,81.3,160,260,702
Patrick Patterson,48.8,46.0,75.0,177,61,286
Terrence Ross,42.9,38.7,87.9,119,30,411
Jonas Valanciunas,54.2,0.0,79.2,283,16,414
So basically you loop through the file and check the beginning of each line of text to see if it starts with the user input. You can use the String method startsWith() to determine if the line starts with the user input, if it returns false, write the line to a temporary file, if it returns true, skip to the next line in the input file. When you've scanned the entire input file, close them both, rename the original to a backup file and rename the temporary file to the original file. Not a very complicated problem.
You can either use the String.startsWith() method or match to a regular expression.
Solution 1
while ((currentLine = Raptors.readLine()) != null) {
if (!currentLine.startsWith(PlayerName + ",")) { // you could use continue as well, but imho it is more readable to put the output.write inside the condition
output.write(currentLine);
output.newLine();
}
}
This solution has better performance but can result in false positives
Solution 2
while ((currentLine = Raptors.readLine()) != null) {
if (!currentLine.matches(PlayerName + ",\\d[\\d.+],\\d[\\d.+],\\d[\\d.+]),\\d+\\d+,\\d+\\s*") {
output.write(currentLine);
output.newLine();
}
}
This solution exactly matches your criteria but has worse performance and looks uglier.
I think Solution 1 should work well.
Please note, that I have not tested the above pieces of code.
PS: it is always a good idea to adhere to the official coding conventions, such as variable names should start with lowercase characters and so on.
PS2: You could use a PrintWriter instead of BufferedWriter, which gives you additional methods, such as println, which combines write(…) and newLine().

reading text file and assigning strings from file to variables

I have a few problems with my code. I want to be able to read input from a text file and take the strings from each line or between spaces and assign them to variables that I will pass to an object.
My first problem is that my program misreads one of my lines and omits the first letter from a variable, and the second problem is I don't know how to make my program read two strings on the same line and assign them to different variables.
System.out.println("Input the file name of the text file you want to open:(remember .txt)");
keyboard.nextLine();
String filename=keyboard.nextLine();
FileReader freader=new FileReader(filename);
BufferedReader inputFile=new BufferedReader(freader);
courseName=inputFile.readLine();
while (inputFile.read()!= -1) {
fName=inputFile.readLine();
lName=inputFile.readLine();
officeNumber=inputFile.readLine();
}
System.out.println(fName);
Instructor inst=new Instructor(fName,lName,officeNumber);
System.out.println(inst);
inputFile.close();
}
I am not very good at using filereader and have tried to use the scanner keyboard method, but it lead me to even more errors :(
Output:
Input from a file (F) or keyboard (K):
F
Input the file name of the text file you want to open: (remember .txt)
test.txt
un bun
un bun won won's office number is null
text file:
professor messor
bun bun
won won
You have to read one line with readLine() then you say that you want to split with whitespace.
So you have to do something like this
String line=null;
List<Course> courses = new ArrayList<>();
while ((line = inputFile.readLine())!= null) {
String[] arrayLine= line.split("\\s+"); // here you are splitting with whitespace
courseName = arrayLine[0]
lName=arrayLine[1];
officeNumber=arrayLine[2];
list.add(new Course(courseName,lName,officeNumber));
// you sure want do something with this create an object for example
}
// in some part br.close();
Here you have an example How to read a File
When you call read() in the condition of the while loop, the "cursor" of the BufferedReader advances one character. You don't want to do this to check if the stream can be read, you want to use the ready() method.
This is another solution using StringTokenizer
String line=null;
List<Course> courses = new ArrayList<>();
while ((line = inputFile.readLine())!= null) {
StringTokenizer sToken = new StringTokenizer(input, " ");
list.add(new Course(sToken.nextToken(),sToken.nextToken(),sToken.nextToken()));
}

Using a text file to carry commands in Java

Hello I am fairly new to java and programming. I was wondering how to read a text file (test.txt) and implement it to carry out a procedure, such as creating and deleting nodes in a linked list as well as assigning them a value. For example if the txt file read:
insert 1
insert 3
delete 3
I would want the program to make a node and assign it a value 1, make a node and assign it a value 3 and then delete that node that has the assigned value 3.
This is some rough code I have so far. Thank you.
CODE:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try
{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}
catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
If the command format in the file is always correct, you can wrap the input stream with Scanner and read word with next(), followed by nextInt() to read the number. No need for complex input validation. This will even allow the number to be on different line from the command.
If you expect invalid input, to make it simple, you can use the current scheme of reading line by line and check the command. Trim and tokenize the line by space with .trim().split("\\s+"). Then compare the first item in the array of tokens and check whether it is a valid command or not. Call the corresponding function to handle the command if valid, print error message otherwise.
If you have multiple commands, you can use Command pattern to make your code more manageable.

Categories