Null String for Scanner - java

I have a problem over my application. I want the app to detect that if the user does not input any value for the string (in other words, just press enter after being asked to input something), the app then asks whether he/she wishes to quit the program or not.
Am I doing it right?
words = s.nextLine();
if (words.equals(null)) {

No, you're not doing it right.
nextLine() will return an empty string if the user just hits return. As far as I can tell it will never return null. If the end of the input has been reached, it will throw NoSuchElementException (unlike BufferedReader.readLine() which will return null in that case). So you want:
if (words.equals(""))
or
if (words.length() == 0)
or
if (words.isEmpty())
... and use hasNextLine() if you want to detect the end of input first.

No, you're not.
If the user simply presses enter, you'll get an empty string, not null. This can be checked as
if(words.equals(""))
If there are whitespaces, this would fail. In that case
if(words.trim().equals(""))
should work.

null is not correct, because what you get is an empty String:
use:
words.isEmpty()
or
words.equals("")
or
words.length()==0

This should work:
if (words == null || words.length() == 0) {

the returned string isnt null, its just an empty string.
words.equals("");
should be correct

Related

Can Scanner.next() return null or empty string?

I'm learning Java coming from other programming languages (Js, C and others..)
I'm wondering if under any circumstances the Scanner.next() method could return (without throwing) an invalid string or less than one character (ie. null or empty string ""). I'm used to double-check user input for any possible unexpected/invalid value, but I wanted to know if testing for null and myString.length() < 1 is always unnecessary or could be useful/needed.
I'm asking in particular when reading from the commandline and System.in, not from other Streams of Files. Can I safely get the first character with myString.charAt(0) from the returned value when reading normally from the terminal input (ie. no pipes and no files, straight from terminal and keyboard)?
I searched the Java SE 9 API Docs and couldn't find mentions about possibly unexpected return values. In case anything goes wrong with input it should just throw an Exception, right?
Example (part of main method without imports):
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a selection (from A to E): ");
String res = keyboard.next();
if (res == null || res.length() < 1) {
// Unnecessary if?
}
Scanner#next can never return null and if the user enters an empty string or a string containing whitespaces only then the method will block and wait for input to scan.
Therefore the if condition is redundant and is not needed at all.
Scanner.next can never return null by looking at its source code. From Scanner.next code
while(true){
...
if (token != null) {
matchValid = true;
skipped = false;
return token;
}
...
}
It can throw NoSuchElementException if no more tokens are available or IllegalStateException if the scanner is closed according to the docs. So your checks are redundant.
Given the following input:
a b c
d e
f
g
The breakdown below shows how a certain sequence of calls to a Scanner object, , will read the above input:
A call to scan.next(); returns the next token, a.
A call to scan.next(); returns the next token, b.
A call to scan.nextLine(); returns the next token, c. It's important to note that the scanner returns a space and a letter, because it's reading from the end of the last token until the beginning of the next line.
A call to scan.nextLine(); returns the contents of the next line, d e.
A call to scan.next(); returns the next token, f.
A call to scan.nextLine(); returns everything after f until the beginning of the next line; because there are no characters there, it returns an empty String.
A call to scan.nextLine(); returns g.

How to Test if Input String is Null in Java

So I created some code to check if the first letter of the word that the user enters (stored in the variable word) is a consonant or vowel. If it is neither it outputs saying it is neither. However, I am using nextLine() instead of next() to get input. I understand that next() will not take input until they enter a valid character besides a space, and I know that nextLine() will go to the else statement if they enter just spaces. However, in nextLine when the user just puts enter and does not enter any character, no spaces, the program crashes. I tried checking if the string was equal to null and then making it print out "test" if it was proven true, however for some reason whenever I press enter I still get an error. Below is my code:
import java.util.Scanner;
public class WordStart {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.printf("Please enter a word: ");
String word = in.nextLine();
String lowerWord = word.toLowerCase();
String x = lowerWord.substring(0,1);
String test = null;
String empty = new String();
boolean vowel = x.equals("a")||x.equals("e")||x.equals("i")||
x.equals("o")||x.equals("u");
boolean conc = x.equals("b")||x.equals("c")||x.equals("d")||x.equals("f")||
x.equals("g")||x.equals("h")||x.equals("j")||x.equals("k")||
x.equals("l")||x.equals("m")||x.equals("n")||x.equals("p")||
x.equals("q")||x.equals("r")||x.equals("s")||x.equals("t")||
x.equals("v")||x.equals("w")||x.equals("x")||x.equals("y")||
x.equals("z");
if(vowel){
System.out.printf("%s starts with a vowel.\n", word);
}
else if(conc){
System.out.printf("%s starts with a consonant.\n", word);
}
else if(word.equals("")){
System.out.println("testEmpty");
}
else if(word.isEmpty()){
System.out.println("testNull");
}
else{
System.out.printf("%s starts with neither a vowel nor a consonant.\n", word);
}
}
}
Basically, I am trying to check if the user just pressed enter without entering anything and call them out on it. What method, line of code would help me do that. I tried using word.equals(null), but the IDE said that it was never true. Thanks in advance.
The error code I get when I just press enter is as follows
run:
Please enter a word:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.substring(String.java:1963)
at WordStart.main(WordStart.java:8)
C:\Users\Jordan\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)
I think the problem lies with this line:
String x = lowerWord.substring(0,1);
If the string is empty (nextLine will never return a null string) it is impossible to take a substring. You should probably check that the string is > 0 characters long.
if(x.length > 0)
String x = lowerWord.substring(0,1);
Firstly note that word.equals("") and word.isEmpty() checks the same condition. So there is no need to use them both. To check whether is String null use if (word == null). Checking the null and the emptyness of the String should be the first one you do.
Secondly in case you skip the input (get the empty String ""), you get IndexOutOfBoundsException, because lowerWord.substring(0,1); has no chance to find that index.
So:
if (word != null && !word.isEmpty()) {
// ...
}
Just check if it is null
if(variable==null)
should suffice

Check if the user input fits

What i'd like to do is that to check if the user input fits and if so then use the user input, otherwise throw exception.
For fit there can only be one true input which is in form of: x,y;x,y;x,y;x,y where x >= 0 & y > 0. (x and y do not have to be same value in every comma separator, for example true input is 0,1;2,3;4,5;6,7) If user types anything else, for example "asd" or 0,1;2,3;4,5 (missing one x,y), he gets the exception. I think i can handle doing the exception throwing but the problem is i don't know how to check if the user input fits. I don't know if it's necessary to provide my code here because the checking part is not in my code yet and anything else is unimportant anyways.
Code was requested, don't know for what reasons but created some for quick example:
TextField tf1 = new TextField();
String inputText = tf1.getText();
if (inputText == form(x,y;x,y;x,y;x,y)) {
// do things;
}
else {
throw exception;
}
From your test case 0,1;2,3;4,5, it is defined that a number of yours ("x") would consist of either zero of a sequence of integers not trended by zero. This would be:
(?:0|[1-9]\d*+)
From there you can quantify a subpattern for repeating the rest of the section "x,y":
(?:0|[1-9]\d*+),[1-9]\d*+(?:;(?:0|[1-9]\d*+),[1-9]\d*+){3}
Here is a regex demo.
Use regexp
if (inputText.matches("[0-9]+,[1-9]+[0-9]*(?:;[0-9]+,[1-9]+[0-9]*){3}"))
{
// do things
}

While not (or equivalent) java

I'm making a program with Java that needs to involve some error checking. I can stop users from entering bad numerical inputs like this (assume the input scanner has already been created):
while (n == 0){
System.out.println("Can't use 0 as a denominator! Please enter a real, nonzero number");
n = input.nextInt();
}
But how do I stop users from entering an invalid string? I can't use !=, because strings can only be compared with the string.equals() method, right? So, is there a while not loop? ie:
while !(string.equals("y") || string.equals("n")){
//here have code
}
Or something of that nature?
While there is no such thing as a while-not loop, you can always invert the condition:
while (!(string.equals("y") || string.equals("n"))){
This is read, "while the string is not equal to "y" or "n"".
You could also apply DeMorgan's identity to rewrite this as:
while (!(string.equals("y")) && !(string.equals("n"))){
which is a bit clearer as "While the string isn't equal to "y" and isn't equal to "n"".
There isn't a while-not instruction, but you can simply negate the condition in a normal while loop. Try this:
while (!string.equals("y") && !string.equals("n"))
Or even better, to guard against the case where the string is null and/or it's in a different case:
while (!"y".equalsIgnoreCase(string) && !"n".equalsIgnoreCase(string))
You almost get it, just change where you position your !
like this:
while (!(string.equals("y") || string.equals("n")))
Why not try regex?
Scanner sc = new Scanner(System.in);
String string = sc.nextLine();
while (!string.matches("(?i)^(?:y|n|yes|no)$"))
{
System.out.println("Invalid input...");
string = sc.nextLine();
}
boolean answer = string.matches("(?i)^(?:y|yes)$");

java String != null not working reading from bufferedReader

In android I am getting the String value from BufferedReader and it is null after reading from file.
intstring = br.readLine();
System.out.println(intstring);
if(intstring != null)
{
System.out.println("Inside if condition");
int istring = Integer.parseInt(intstring);
}
My output is
null
Inside if condition
NumberFormatException
Help me please
Your NumberFormatException is happening because your input isn't a number. Maybe it's a blank line, or maybe it has some non-numeric characters. In fact, your output suggests that it's actually the word "null".
You've got some options.
You could check that the string contains digits and no other characters before you parse it, for example by using a regular expression and a condition like if (intString.matches("\\d+")).
You could catch the NumberFormatException, and do something particular when it happens.
You could check whether your string is blank, if you knew that there weren't going to be any non-numeric characters in the input. For this option, you might write if (!intString.equals(""))).

Categories

Resources