So i have a program that creates a new file but need it to have a default file name if the user was to not enter anything, and was wondering if anyone could help with it.
So far i have the program asking the user for the file name but not sure what to do to set the default to for say "output.txt".
Here is a snip-it of my code:
//Creates a Scanner Object for keyboard input.
Scanner keyboard = new Scanner(System.in);
//Get the filename.
System.out.print("Enter a filename: ");
filename = keyboard.nextLine();
Test what the user has entered as a filename. If it is an empty string, use the default filename.
You may want to "trim" the string too. A filename with leading or trailing whitespace characters would be a bad idea.
You have to test if the string is empty, which can be done with String#isEmpty in conjuction with String#trim, from the documentation:
isEmpty
public boolean isEmpty()
Returns true if, and only if, length() is 0.
That means, once we trim to remove whitespace, we can test if length is 0. Thus, any inputs that consist of just spaces will not be used as filenames, and will default, else it will used the given. You can apply this like so:
File file = new File(filename.trim().isEmpty() ? "output.txt" : filename);
try {
file.createNewFile();
} catch(IOException ex) {
//file was not created successfully
}
This will create a new File object, which will have a filename based on if the user inputted anything (whitespace excluded). file.createNewFile() will just create the file if it does not exist.
It's sure you need some condition for achieve this.
Perhaps, you probably need simple method like this:
isNotNullOrEmpty(filename) ? filename : defaultFileName;
private static boolean isNotNullOrEmpty(String str) {
return str != null && !str.isEmpty();
}
Related
I'm new to java and I need help with this problem I encountered. This class reads data from text file and adds it to the array Movie. The problem is that when it reads the text file, it skips every other line.
public class ReadFile{
private File f;
Scanner sc;
int index;
public ReadFile(){
f = new File("db.txt");
try {
sc = new Scanner(f);
} catch (FileNotFoundException e) {
System.out.println("An Error occured, File couldn't be opened.");
}
}
public int FileRead(Movie[] film, int index){
sc.useDelimiter(",");
this.index = index;
while(sc.hasNext()){
film[index] = new Movie();
film[index].setTitle(sc.next());
film[index].setYear(sc.next());
film[index].setRuntime(sc.next());
film[index].setActorOne(sc.next());
film[index].setActorTwo(sc.next());
film[index].setDirector(sc.next());
if(sc.hasNextLine()){
sc.nextLine();
}
index++;
}
System.out.println("count is "+ index);
sc.close();
return index;
}
}
nextLine() doesn't actually do what you think it does.
Furthermore, neither does .useDelimiter(",") - presumably, your file is something like:
Jurassic Park,1993,128,Jeff Goldblum,Jeff Goldblum's looks,Steven Spielberg
The Fly,1986,96,Jeff Goldblum,A fly,David Cronenberg
The problem is, computer is as computer does. You said the separator between tokens is a comma. And nothing else. So, this whole thing is a single token:
Steven Spielberg
The Fly
As in, "Steven Spielberg\nThe Fly" is what your sc.next() call returns for the first movie in the setDirector line. Seems stupid? Well, you told the computer: Tokens are things separated by commas. That whole thing is surrounded by commas so, you asked for it, you got it: That's the next() token in the file. Then you do an otherwise useless nextLine call which eats the rest of that The Fly line, thus, resulting in not only skipping every other movie, but having a mangled combo of the directory and the name of the movie on the next (otherwise skipped) line, mangled together. You know, like The Fly? Get it? [Note to self: It's a movie from 1987, no, they wont get it!]
The fix is possibly to tell scanner that either a comma or a newline counts as a separator; .useDelimiter(",|\r?\n") would do that. And forget about the hasNextLine + nextLine part, that does nothing, you should just get rid of that. Your code will fail if there's a 'broken' line in there (one that doesn't include precisely 5 commas), and that nextLine stuff isn't going to fix that problem, thus, get rid of it.
Alternatively, forget scanner - read line by lines using e.g. Files.readAllLines, then process line-by-line, using .split(",") to break it into parts.
this is my first post so forgive me if i have posted incorrectly. I have a task that i need to complete but i cant get it to work properly. the compiler that i use is bluej. what i need to do is to use scanner to read a text file and compare a user input to the text file. if the input string compares then it should print out that ""The word is on the text file". Unfortunately i cant get this to work. My code reads the file because it prints out to the console but no comparison it s happening. please have a look at my code and give me some pointers. i have been trying to use .equals():
private boolean searchFromRecord(String recordName, String word) throws IOException
{
// Please write your code after this line
File file = new File(recordName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
for(int i = 0; scanner.hasNextLine(); i++){
String compare = scanner.nextLine();
IO.outputln("word#" + i + ":" + compare);
}
scanner.close();
if (scanner.equals(word)){
return true;
} else{
return false;
}
}
return true;
}
this is what i get output in the console:
Input a word: IRON
AA 888
word#0:BULLET
word#1:1
word#2:AE 1688
word#3:CHEERS
word#4:GAMES
word#5:IRON MAN
word#6:WOLF
word#7:Testing
word#8:Wonderful
The word "IRON" is not in the record.
Here are some problems, along with why they are problems & a suggestion on how they could be fixed:
Problem: closing a scanner within the a loop that uses it will cause an exception. Reason: after we go through the loop once, the scanner will be closed. when we loop through again, an error will occur since the loop uses the scanner, which means the scanner should be "open". Possible solution: move scanner.close() to after the while loop.
Problem: we shouldn't return true at the end of this method. Reason: I'm guessing that this method is supposed to return true if the word is found, and false otherwise. Now, the only way to get to this return statement is if our word doesn't exist in the recordFile; it should return false. Possible solution: return false at the end of the method instead.
Problem: the first line in recordFile will never be checked for equality with word Reason: each method call of scanner.nextLine() will return each line from the recordFile as a String once and only once. In your code, it is called once in the beginning of the while loop's body, but not used to compare with word, then after, it is used in the for loop for comparison Possible solution: remove the line: System.out.println(scanner.nextLine());.
Problem: scanner.equals(word) will probably always return false. Reason: scanner is a Scanner, and word is a String, they should never be equal. Possible solution: replace scanner.equals(word) with compare.equals(word)
Problem: word is not actually compared with each compare. Reason: it is outside the for loop. Possible solution: move the if else block into the end of the for loop's body.
I don't think the while loop is really needed. I strongly recommend that the while loop, is removed, but keep the body.
Problem: Moving the if else block into the for loop, and above the scanner.close() means that the scanner.close() will never be run. Reason: once a return statement is executed, the flow of control immediatly exits the method, and returns to where the method was invoked which makes code after return statements useless. Possible solution: instead of returning right away, declare some sort of boolean variable that will store the return value. have the return value be modified throughout the method, then return the variable at the very end, after scaner.close()
There are many many other ways to fix each of these problems other than the ones suggested here.
I hope you find this helpful! :)
your code, refactored to implement the suggested solutions above:
private boolean searchFromRecord(String recordName, String word) throws IOException {
// Please write your code after this line
Boolean wordFound = false; // indicates if word exists in recordFile.
File file = new File(recordName); // file at path "recordName"
Scanner scanner = new Scanner(file); // reads records from "file"
// iterate through the recordFile, to see if "word" already exists
// within recordFile.
for(int i = 0; scanner.hasNextLine(); i++) {
// read the record from the file
String compare = scanner.nextLine();
IO.outputln("word#" + i + ":" + compare);
// compare the record with our word
if (compare.equals(word)){
wordFound = true;
break; // bail out of loop, our work here is done
}
}
// clean up, and return...
scanner.close();
return wordFound;
}
First, scanner is not a String and it will not equal a String. Second, you are dropping lines - scanner.nextLine() gets the next line, and you print it (but don't save it or compare it). I think you wanted something more like this,
// eats and tosses input.
// System.out.println(scanner.nextLine());
String line = scanner.nextLine();
for(int i = 0; scanner.hasNextLine(); i++){
String compare = scanner.nextLine();
IO.outputln("word#" + i + ": " + compare + " to line: " + line);
if (line.contains(compare)){ // "IRON MAN" starts with "IRON", it doesn't equal IRON.
return true;
}
}
scanner.close();
return false; // <-- default.
Another flavor is to read the whole file into a String variable and look for specified String inside the String.
Code:
File file = new File("C:\\Users\\KICK\\Documents\\NetBeansProjects"
+ "\\SearchWordinFile\\src\\searchwordinfile\\words.txt");
String s="";
try(Scanner input = new Scanner(file)){
input.useDelimiter("\\A");
if (input.hasNext()) {
s = input.next();
}
}catch(Exception e){
System.out.println(e);
}
if(s.contains("IRON"))
System.out.println("I found IRON");
}
Output:
I found IRON
My File content
BULLET
1
AE 1688
CHEERS
GAMES
IRON MAN
WOLF
Testing
Wonderful
I want to make a command line, just to run basic commands. So far, I've made it so that people can tell the program their name. When I don't enter a name, however, it treats it as if I did. Here is my class:
public static void main(String args[])
throws IOException
{
int a = 1;
do
{
System.out.print("$$: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String wtt = null; // wtt = what they typed!
wtt = br.readLine();
if(wtt == null)
{
System.out.println("Why wont you tell me your name!");
}
else
{
System.out.println("Thanks for the name, " + wtt);
}
}
while(a == 1);
}
Here is the output
$$: well
Thanks for the name, well
$$: hole
Thanks for the name, hole
$$:
Thanks for the name,
Why does it not work?
Calling readLine() on a BufferedReader will only return null on end of input. Here, the input hasn't ended, you've just entered an empty line, so "" (the empty string) is the result.
You will need to end the input stream, usually with Ctrl-C. Then you'll get "Why wont you tell me your name!". But then you'll need to break out of your infinite loop.
use this
if (wtt == null || wtt.trim().length() == 0)
Try
wtt.length()==0
instead of checking for null
It's because although you set the string to null at first, you are then setting it to br.readLine() which will have a line to read even though the user didn't type anything before hitting enter, so it will set the string to an empty string.
You should also (or instead) compare your string to "" (an empty string) to see if they entered anything.
You should compare wtt to "" as well to make sure the line isn't empty.
if (wtt == null) {
becomes
if (wtt == null && !!("".equals(wtt))) {
Instead of comparing wtt to null, compare it to empty string:
if ("".equals(wtt))
{
System.out.....
}
readLine method doesn't give you end of line characters (e.g. \n, \r). So, you cannot expect the loop to exit when you press just enter without entering anything. You can use read method instead to read characters and determine if there was a new line character or use Scanner class which seems to me better suitable in your situation.
I'm getting the error
the local variables name and password may not have been initialized,
for the if-statement. These errors go away if I change the second string in parentheses to something in quotes, or if I set the variables to 0, but then I would also need to change them to int and I need them to be String.
I'm trying to compare the username and password from a text file to a newly input username and password. The program should also quit after 3 bad attempts so I probably put the System.out.println("Goodbye!"); in the wrong place too.
public static void main(String[] args) {
int numberOfAttempts = 1;
String fileName = "logins.txt";
Scanner inputStream = null;
String name, password, line, secondname;
String secondpassword;
do
{
System.out.println("Please enter your username: ");
Scanner keyboard = new Scanner(System.in);
secondname = keyboard.nextLine();
System.out.println("Please enter your password: ");
secondpassword = keyboard.nextLine();
try
{
inputStream = new Scanner(new File(fileName));
}
catch(FileNotFoundException e)
{
System.out.println("Error opening the file " +
fileName);
System.exit(0);
}
while (inputStream.hasNextLine())
{
line = inputStream.nextLine();
}
if ((name.equalsIgnoreCase(secondname))&&
(password.equalsIgnoreCase(secondpassword)))
{System.out.println("Welcome!");
numberOfAttempts = 4;
}
else
System.out.println("Invalid. Please try again.");
numberOfAttempts++;
}
while ( numberOfAttempts <4);
System.out.println("Goodbye!");
inputStream.close();
}
}
You never initialize name and password, so of course you'll get this error.
You initialize secondname and secondpassword, but your condition checks name and password which are not initialized.
In JAVA methods, any local variable must be initialized first it can be used. In your case you are trying to compare the name & password in your code are never initialized or assigned a value.. It will be a good idea to initialize your strings either as NULL or empty string such as "" or any desired value.
You have a bunch of problems.
The errors are caused by the fact that you never assign any values to the variables "name" and "password", but you then check to see if those variables match the secondname and secondpassword variables you do read. Because name and password never get any values at all, the comparison can't possibly be what you intend, so the compiler flags it as an error.
You can make the error go away by assigning name and password to some values when you declare them, but your program still isn't going to work correctly, because no matter what value you assign, it probably won't be the thing that the user of your program would want to be comparing against.
Presumably your intent is to read the value of name and password from the input file you've opened and read in, but in fact you aren't doing anything with the values in that file except immediately throwing them away. Look at the loop
while(inputStream.hasNextLine()) {
line = inputStream.nextLine();
}
This loop will read in every line from the file, but as soon as you read one line, you throw away whatever you read into the line variable because you have to reuse that variable to read the next line, which you'll also throw away immediately. At the end of the loop, you'll have saved the last line from the file into line, but the rest of the program doesn't use the line variable either.
You need to put some logic inside that loop to read whatever you wanted to read from the file, store it in the name and password variables, and then you'll have some hope that when you do the equalsIgnoreCase stuff that you'll actually be comparing variables that have some meaning to your program.
I'm reading a text file line by line and converting it into a string.
I'm trying to figure out how to check if the last line of the file is a specific word ("FILTER").
I've tried to use the endsWith(String) method of String class but it's not detecting the word when it appears.
Rather naive solution, but this should work:
String[] lines = fileContents.split("\n");
String lastLine = lines[lines.length - 1];
if("FILTER".equals(lastLine)){
// Do Stuff
}
Not sure why .endsWith() wouldn't work. Is there an extra newline at the end? (In which case the above wouldn't work). Do the cases always match?
.trim() your string before checking with endsWith(..) (if the file really ends with the desired string. If not, you can simply use .contains(..))
public static boolean compareInFile(String inputWord) {
String word = "";
File file = new File("Deepak.txt");
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
word = input.next();
if (inputWord.equals(word)) {
return true;
}
}
} catch (Exception error) {
}
return false;
}
With
myString.endsWith("FILTER")
the very last characters of the last line are checked. Maybe the method
myString.contains("FILTER")
is the right method for you? If you only want to check the last ... e.g.20 chars try to substring the string and then check for the equals method.