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.
Related
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
So I'm trying to write a code that searches a txt file for a specific string, then prints all lines on which the string occurs.
The most straightforward way to do this seems to be running a Scanner and a LineNumberReader through the document, adding lines that fit the bill to the "found" string. However, whenever it stumbles across a line that doesn't contain the word, it throws a NullPointerException and kills the loop no matter what. Can anyone tell me what I'm doing wrong?
FileReader r = new FileReader(f);
LineNumberReader l = new LineNumberReader(r);
Scanner s = new Scanner(l);
int i = 1;
String found = "Instances of string found:\n";
{
while (s.hasNextLine()) {
try {
if (s.findInLine(keyword).isEmpty() == false) {
found = found + l.readLine() + "\n";
s.nextLine();
} else {
s.nextLine();
}
} catch (NullPointerException e) {
s.nextLine();
}
}
display(found, "Match found!");
}
Check the documentation of scanner: If no such pattern is detected in the input up to the next line separator, then null is returned and the scanner's position is unchanged.
You call s.findInLine(keyword).isEmpty() == false, if the word is not contained in findInLine(keyword) will be null, thus you'd be calling null.isEmpty(). There's your exception ;)
You don't have to check for isEmpty(), s.findInLine(keyword)!= null should be enough.
If you're using a method that is documented as returning null in some cases, then you should assign the result of the method to a variable (if you're going to use it for something else) and use == or != to test it for null. It is very poor programming practice to use the result as a reference and then rely on try/catch on NullPointerException to see if it's null. For one thing, what if there's an unexpected null somewhere else in the try body? Now it will be catching the exception for the wrong reason. NullPointerException always indicates a program bug. It should never be part of the "normal" program logic.
As for why it "kills the loop": It shouldn't. Even though your use of try/catch is poor practice, it should still work the way I think you intended, and shouldn't kill the loop. I just tested something similar to your code, but without l.readLine(), and it seemed to behave. If you want the line number, it's l.getLineNumber(), not l.readLine(), which tries to read a line of text and could sabotage the Scanner.
Im trying to go on a loop while the input file has a string on the following line but im getting an error. Any idea why?
while( !((input = in.nextLine()).equals(""))){
...
}
Output:
Enter file name: input1.txt
evil live
Exception in thread "main" This is a palindrome
level
This is a palindrome
dog
Not a palindrome
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1516)
at Palindrome.main(Palindrome.java:41)
Your code is not correct, because it is possible that the input would end without providing an empty line. You should check if a line is available before checking it for being empty:
while(in.hasNextLine() && !((input = in.nextLine()).equals(""))){
...
}
There is no line after the end of file. When the last line is read the next call to nextLine() will fail. Use hasNextLine() to protect against this.
in.nextLine() is probably returning a null, which is being assigned to input, which you are trying to invoke equals on.
Use hasNextLine (documentation here) to make sure you can get the next line.
The way your loop is setup, it will never reach a "" string because it will hit the end of the file before doing so. it should be something like
while (input.hasNextLine()) {
...
}
This means that it will continue until the file has no next line.
Compare against null as well to check against End-Of-File
as
while(((input = in.nextLine())!= null) && !(input.equals(""))){
Or try:
while(in.hasNextLine(){
input = in.nextLine();
if(input != null && !(input.equals(""))){
........
}
}
Try to use this type of thing, catching the exception if needed:
input = in.nextLine();
while( !(input.equals(""))){
...
}
and if it throws an error, then set up a try...catch loop
May be you need,
while(in.hasNextLine()){
input = in.nextLine();
}
Scanner throws an exception when it runs out of input. You seem to be thinking that it will return a zero-length string.
Are you using Scanner to read a file a line at a time? That's not what it's for. You may want to look at BufferedReader.
Ok, so I can't seem to get this to work, though many people have told me the syntax and logic is correct. Can anyone reveal for me what I could possibly be doing wrong?
public Scanner in = new Scanner(System.in);
public void movePlayer() {
System.out.print("move: ");
String str = in.nextLine();
in.nextLine();
char c = str.charAt(0);
if (c == 'l' || c == 'L') {
player.moveLeft();
}
}
The program gets caught at char c = str.charAt(0);
And I am being returned this error:
java.lang.StringIndexOutOfBoundsException:
String index out of range: 0 (in java.lang.String)
you did not input anything though the console, so str is empty. this is the reason why chatAt(0) throw an exception
You don't want to use nextLine(). You want to use next().
String str = in.next();
This is the Javadoc for nextLine()
Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
You want next() instead:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.
This will stop you from consuming the empty line and raising an exception.
This means that str is empty. You should check if it is not null and not empty.
if (str != null && !str.isEmpty()) {
...
}
Add a check for Empty String and Null as well . You will avoid a lot of headaches.
If you press Enter key in console, Scanner will be considered a complete line, regardless of whether or not there is text entered.
Press Enter at the beginning of a line, returns a String "" to the method Scanner.nextLine().
Add a check with str.lenght () > 0 before str.charAt(0).
Use in.next() instead. For whatever reason, nextLine() doesn't work with CharAt() sometimes.
I've been trying different methods for converting a user string input into an int I could compare and build an "if-then" statement. Every time I tried testing it, it just threw exception. Can anyone look at my Java code and help me find the way? I'm clueless about it (also a noob in programming). If I'm breaking any rules please let me know I'm new here. Thank you.
Anyway, here is the code:
System.out.println("Sorry couldn't find your user profile " + userName + ".");
System.out.println("Would you like to create a new user profile now? (Enter Y for yes), (Enter N for no and exit).");
try {
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
Character i = new Character(addNewUser.charAt(0));
String s = i.toString();
int answerInDecimal = Integer.parseInt(s);
System.out.println(answerInDecimal);
}
catch(Exception e) {
System.out.println("You've mistyped the answer.");
e.getMessage();
}
It seems like you are trying to convert the string (which should be a single character, Y or N) into its character value, and then retrieve the numerical representation of the character.
If you want to turn Y or N into their decimal representation, you have to perform a cast to int:
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.charAt(0);
int integerChar = (int) i; //The important part
System.out.println(integerChar);
This will return the integer representation of the character that the user input. It may also be useful to call the String.toUpperCase() method in order to ensure that different inputs of Y/N or y/n do not give different values.
However, you could also do an if-else based upon the character itself, rather than converting it to an integer.
BufferedReader answer = new BufferedReader(new InputStreamReader(System.in));
String addNewUser = answer.readLine();
char i = addNewUser.toUpperCase().charAt(0);
if (i == 'Y') {
//Handle yes
} else if (i == 'N') {
//Handle no
} else {
System.out.println("You've mistyped the answer.");
}
I think you meant to ask them to Enter 0 for yes and 1 for No ? Maybe?
You're asking the user to type Y or N and then you're trying to parse that to an integer. That will always throw an exception.
EDIT -- As others have pointed out, if you want to continue to use Y or N, you should do something along the lines of
String addNewUser = answer.readLine();
if ( addNewUser.toLowerCase().startsWith("y") ) {
// Create new profile
}
parseInt is just for converting text numbers into integers: everything else gets a NumberFormatException.
If you want the decimal ASCII value of a character, just cast it to an int.
Use if (addNewUser.startsWith("Y") || addNewUser.startsWith("y")) { instead.
Or (as Mark pointed) if (addNewUser.toLowerCase().startsWith("y")) {.
BTW maybe look at Apache Commons CLI?
You cannot convert String to int, unless you know the String contains a valid integer.
Firstly, using the Scanner class for input is better, since its faster
and you don't need to get into the hassle of using streams, if you're
a beginner. This is how Scanner will be used to take input:
import java.util.Scanner; // this is where the Scanner class resides
...
Scanner sc = new Scanner(System.in); // "System.in" is the stream, you could also pass a String, or a File object to take input from
System.out.println("Would you like to ... Enter 'Y' or 'N':");
String input = sc.next();
input = input.toUpperCase();
char choice = sc.charAt(0);
if(choice == 'Y')
{ } // do something
else if(choice == 'N')
{ } // do something
else
System.err.println("Wrong choice!");
This code could also be shortened to one line (however you won't be
able to check a third "wrong choice" condition):
if ( new Scanner(System.in).next().toUpperCase().charAt(0) == 'Y')
{ } // do something
else // for 'N'
{ } // do something
Secondly, char to int conversion just requires an explicit type
cast:
char ch = 'A';
int i = (int)ch; // explicit type casting, 'i' is now 65 (ascii code of 'A')
Thirdly, even if you take input from a buffered input stream, you
will take input in a String. So extracting the first character from
the string and checking it, simply requires a call to the charAt()
function with 0 as a parameter. It returns a character, which can
then be compared to a single character in single quotes like this:
String s = in.readLine();
if(s.charAt(0) == 'Y') { } // do something
Fourthly, its a very bad idea to put the whole program in a try
block and catch Exception at the end. An IOException can be
thrown by the readline() function, and parseInt() could throw a
NumberFormatException, so you won't be able to handle the 2
exceptions separately. In this question, the code is small enough for
this to be ignored, but in practice, there will be many functions
that can throw exceptions, hence it becomes easy to lose track of exactly which function threw what exception and proper exception handling becomes quite difficult.